Triangle angle classification - python

I need to make a function to make that will give me an angle classification like acute right or obtuse and I need it to loop until the user wants to exit the function:
this is my code so far:
side_a = float(input('Enter length of side a: '))
side_b = float(input('Enter length of side b: '))
side_c = float(input('Enter length of side c: '))
def is_valid_triangle(a,b,c):
if a+b>=c and b+c>=a and c+a>=b:
return True
else:
return False
# Function definition for type of triangle
def type_of_triangle(a,b,c):
if a==b and b==c:
print('Triangle is Equilateral.')
elif a==b or b==c or a==c:
print('Triangle is Isosceles.')
else:
print('Triangle is Scalane')
return False
if is_valid_triangle(side_a, side_b, side_c):
type_of_triangle(side_a, side_b, side_c)
else:
print('Tringle is not possible from given sides.')
def triangle_angle (a, b, c, ) :
a = int(input ("enter side a: "))
b = int(input("enter side b : "))
c = int(input("enter side c : "))

I'm assuming you want to know how to constantly loop code.
You can use:
try:
while True:
pass # replace with whatever code you want to run
except KeyboardInterrupt:
print('Exiting...')
Which will constantly loop until the user presses Ctrl+C.
I think this answers your question.

Related

Python program to read function inputs

Hi guy’s I’m trying to write a python program here and I’m just learning at the moment. what I’m trying to do is get the user to enter a 6 digit number and if they enter a number which is not 6 digits I want an error message to come us stating they must enter a 6 digit number. I have a function called def example_check_message(m): where I have stated that the number must be 6 digits and I have a function called def example_get_number(): when the user enters the number the get number function should call the def example_check_message(m) function to check the number being entered is correct but nothing is happening. I know I’m close to it but just can’t see where I’m going wrong.
def example_check_message(m):
b = False,
try:
if m == int >= '100000' and '<1000000':
b = True
except:
print 'You must enter a number'
return b
def example_get_number():
example_check_message(1)
b = False
while b == False:
num = raw_input('Please enter a 6 digit number:')
if example_check_message(num) == True:
b = True
continue
value = int(num)
return value
if __name__ == '__main__':
example_check_message(1)
example_get_number()
I think you want something like:
def example_check_message(m):
try:
m = int(m)
if m >= 100000 and m < 1000000:
return m # <- return something useful!
except:
print 'You must enter a number'
return False
but there are errors in this - ill give you some hint where. this shouldn't work as-is, you'll still need to do some work and learning.
def example_get_number():
example_check_message(1)
b = False
while b == False: # not b is the right way here
num = raw_input('Please enter a 6 digit number:')
if example_check_message(num) == True: # This could be simpler
b = True
continue # <- no need to continue here, just return
value = int(num) # <- do this already on the input!
return value

Python "if" statement not working

I was writing a complex program and I was getting an if statement...
(this isn't the complex code, this is just an example)
print("The 24 game will give you four digits between one and nine")
print("It will then prompt you to enter an ewuation one digit at a time.")
import random
a = random.randint(1,9)
b = random.randint(1,9)
c = random.randint(1,9)
d = random.randint(1,9)
print(a,b,c,d)
f=input("Enter one of the above numbers")
if f==a:
print("ok")
elif f != a:
print("No")
No matter what I type it always outputs "NO".
It would work after converting the user input string to a number:
if int(f) == a:
print("ok")

Python calculator - How can I make this better

im pretty new to programming. I made this calculator in python and I was wondering how can I make it more efficient because it seems a bit inefficient to me. I'm still really unfamiliar with python and some programming concepts so it would be nice to get an idea of different ways I may do this. Perhaps there is a better way for me to set up the functions or maybe a way that they can be put into different classes?
Thanks for any responses
def add():
a = int(raw_input("Enter a number!: \n"))
b = int(raw_input("Enter a number!: \n"))
c = a + b
if a + b == c:
print c
menu()
return c
def sub():
a = int(raw_input("Enter a number!: \n"))
b = int(raw_input("Enter a number!: \n"))
c = a - b
if a - b == c:
print c
menu()
return c
def mul():
a = int(raw_input("Enter a number!: \n"))
b = int(raw_input("Enter a number!: \n"))
c = a * b
if a * b == c:
print c
menu()
return c
def div():
a = float(raw_input("Enter a number!: "))
b = float(raw_input("Enter a number!: "))
c = a / b
if a / b == c:
print c
menu()
return c
def square():
a = int(raw_input("Enter a number!: \n"))
c = a * a
if a * a == c:
print c
menu()
return c
def menu():
print """
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square
6. Exit
"""
choices = [1, 2, 3, 4, 5, 6]
choice = int(raw_input("Enter a number!: \n"))
while True:
if choice == 1:
print add()
elif choice == 2:
print sub()
elif choice == 3:
print mul()
elif choice == 4:
print div()
elif choice == 5:
print square()
elif choice == 6:
exit()
else:
for choose in choices:
if choice != choices:
print "Please enter a number 1 - 6!"
menu()
menu()
First, in the else case where the user entered an invalid menu number, you don't need these lines:
for choose in choices:
if choice != choices:
After all, you already know choice is not valid.
Second, when the user enters 6, rather than exit() you should just return. The program will still end. It's often considered "rude" for a function to call exit() directly--let the caller decide what to do when the function ends.
Third, you don't need to call menu() when your operators succeed. It's strange that you do, since menu() contains its own infinite loop anyway. It's just redundant.
Finally, you can collapse all the two-argument math functions into one, by passing in the actual operation as an argument. The operator module makes this easier.
Putting all these ideas together, here's the new code:
import operator
def dobinaryop(op):
a = float(raw_input("Enter a number!: \n"))
b = float(raw_input("Enter a number!: \n"))
return op(a, b)
def square():
a = float(raw_input("Enter a number!: \n"))
return a * a
def menu():
while True:
print """
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square
6. Exit
"""
choice = int(raw_input("Enter a number!: \n"))
if choice == 1:
print dobinaryop(operator.add)
elif choice == 2:
print dobinaryop(operator.sub)
elif choice == 3:
print dobinaryop(operator.mul)
elif choice == 4:
print dobinaryop(operator.div)
elif choice == 5:
print square()
elif choice == 6:
exit()
else:
print "Please enter a number 1 - 6!"
menu()
You could streamline this even further by putting the various operators into a list and indexing by choice, but that's getting slightly arcane for not much benefit given you only have four such operators, plus two special cases and bounds checking.
There are couple of things which you are repeating in all the functions. Like asking user to input two numbers a & b using raw_input multiples times. They can be put into another method say getTwoNumbers() which will take two inputs from user and return the two numbers. This method (i.e getTwoNumbers())need to be invoked in the function(s) which is/are performing binary operation. Also you are storing the result into another variable c, which can be ommited and hence comparison with binary operation with the variable c is also not required. It is better if you can perform return a+b or return a-b etc, based on the current binary operation you want to perform.
Put functions and related index in a dictionary. Use that dictionary to decide which function to execute.
And get duplicated part of every function out. I think these solutions will get your code better.

Python try except problems

So im having a little trouble with a project im working on. I'm not an expert with Python nor am I an idiot when it comes to coding. This problem may have a very simple answer but I cant seem to get it right. My entire code asks a user to answer questions using a random choice from a list.
import turtle
import random
turtle.speed("fastest")
pi = 3
minNumber = 5
maxNumber = 10
score = 0
listNmbers = []
a = [1,3,5,7,9]
red = random.random()
green = random.random()
blue = random.random()
num1 = random.choice(a)
def drawSquare():
for i in range(4):
turtle.begin_fill()
turtle.pendown()
turtle.forward(50)
turtle.left(90)
turtle.end_fill()
turtle.right(360/userAnswer)
turtle.penup()
turtle.setpos(-700,-200)
turtle.fillcolor("green")
print("Welcome! What is your name??")
name = str(input())
print("Hello", name,"you need to calculate the circumference of a circle when given a diameter. To calculate the circumference, use the equasion; Pi x Diameter (Pi = 3")
num = input("how many questions would you like to answer? (Pick between 5 and 10)")
def getNumbers(numbers):
try:
badInput = False
while not (badInput):
num = input("how many questions would you like to answer? (Pick between 5 and 10)")
numbers = int(num)
badInput = (numbers >= 4) or (numbers >= maxNumber)
if badInput == False:
print ("Please input an integer between 5 and 10 please")
badInput = False
except:
print("Please input an integer between 5 and 10")
numbers= 0;
numbers = getNumbers(numbers)
numbers= 0;
numbers = getNumbers(numbers)
for i in range(int(num)):
red = random.random()
green = random.random()
blue = random.random()
num1 = random.choice(a)
turtle.color(red,green,blue)
correct = num1 * 3
print("What is the cirumference of the circle if", num1,"is the diameter and Pi is 3?")
userAnswer = int(input())
if userAnswer == correct:
print("That's Correct! Well Done")
score = score + 1
for k in range(correct):
turtle.color(red,green,blue)
drawSquare()
turtle.penup()
turtle.forward(150)
else:
print("sorry thats is incorrect")
in this bit of code, it asks the user how many questions they want to ask (as an integer). My code works well when a number within the parameters are given, but as soon as a number such as 19 is given, it continues when it should not. Also if a string is given, it works well and asks again for an integer, but if an integer is given after being asked, it crashes. The error read:
for i in range(int(num)):`ValueError: invalid literal for int() with base 10: 'test'`
All help would appreciated so much. thank you all
And you're hidding too much code within a generic try..except (try to Ctrl+C while input is required... nope!). I would write that function in that way:
def getNumbers():
num = input("how many questions would you like to answer? (Pick between 5 and 10)")
try:
number = int(num)
except:
print("Not a number!")
return getNumbers()
goodInput = minNumber < number < maxNumber
if not goodInput:
print ("Please input an integer between 5 and 10 please")
return getNumbers()
else:
return number
number = getNumbers()
getNumbers() doesn't return any value. Thus, it implicitly returns None, which you assign to numbers, here:
numbers = getNumbers(numbers)
Make sure that wherever you exit the getNumbers() function, you return numbers (probably at the end:
def getNumbers(numbers):
....
return numbers
EDIT: #see xbello answer to have a working answer. My "poisoned" code isn't working as expected ;)
First of all I must say that your code isn't really nice to read... But here are some fixes that should do the trick
maxNumber = 10
print("Hello", name,"you need to calculate the circumference of a circle when given a diameter. To calculate the circumference, use the equasion; Pi x Diameter (Pi = 3")
num = input("how many questions would you like to answer? (Pick between 5 and 10)")
def getNumbers(numbers):
try:
goodInput = False
while not (goodInput):
num = input("how many questions would you like to answer? (Pick between 5 and 10)")
numbers = int(num)
# Here was a bad condition having a look at your comments
goodInput = (numbers > 4) and (numbers <= maxNumber)
if goodInput == False:
print ("Please input an integer between 5 and 10 please")
# goodInput is already False, no need to set it again
# Here is the missing return
return numbers
except:
print("Please input an integer between 5 and 10")
numbers= 0;
numbers = getNumbers(numbers)
numbers= 0;
numbers = getNumbers(numbers)
for i in range(numbers):
#Do stuff
You can see that I added a return value to your function (that returned None by default) and that I take this return value to push it into "numbers" afterwards. That "numbers" value can then be pushed into a range() function to make a nice for loop.

Beginner python - stuck in a loop

I have two begininer programs, both using the 'while' function, one works correctly, and the other gets me stuck in a loop. The first program is this;
num=54
bob = True
print('The guess a number Game!')
while bob == True:
guess = int(input('What is your guess? '))
if guess==num:
print('wow! You\'re awesome!')
print('but don\'t worry, you still suck')
bob = False
elif guess>num:
print('try a lower number')
else:
print('close, but too low')
print('game over')``
and it gives the predictable output of;
The guess a number Game!
What is your guess? 12
close, but too low
What is your guess? 56
try a lower number
What is your guess? 54
wow! You're awesome!
but don't worry, you still suck
game over
However, I also have this program, which doesn't work;
#define vars
a = int(input('Please insert a number: '))
b = int(input('Please insert a second number: '))
#try a function
def func_tim(a,b):
bob = True
while bob == True:
if a == b:
print('nice and equal')
bob = False
elif b > a:
print('b is picking on a!')
else:
print('a is picking on b!')
#call a function
func_tim(a,b)
Which outputs;
Please insert a number: 12
Please insert a second number: 14
b is picking on a!
b is picking on a!
b is picking on a!
...(repeat in a loop)....
Can someone please let me know why these programs are different? Thank you!
In the second example, the user doesn't get a chance to enter a new guess inside the loop, so a and b remain the same.
In the second program you never give the user a chance to pick two new numbers if they're not equal. Put the lines where you get input from the user inside the loop, like this:
#try a function
def func_tim():
bob = True
while bob == True:
#define vars
a = int(input('Please insert a number: '))
b = int(input('Please insert a second number: '))
if a == b:
print('nice and equal')
bob = False
elif b > a:
print('b is picking on a!')
else:
print('a is picking on b!')
#call a function
func_tim()
in your 2nd program, if b > a, you will go back to the loop because bob is still true. You forgot to ask the user to input again.. try it this way
def func_tim():
while 1:
a = int(input('Please insert a number: '))
b = int(input('Please insert a second number: '))
if a == b:
print('nice and equal')
break
elif b > a:
print('b is picking on a!')
else:
print('a is picking on b!')
func_tim()
Your second program doesn't allow the user to reenter his guess if it's not correct. Put the input into the while loop.
Additional hint: Don't make checks like variable == True, just say while variable:.

Categories