Python Forum

Full Version: Functions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So I just started Python a few days ago and I'm stuck on functions. The exercise is to build a basic calculator: add, sub, multiply, and divide.

when you run the program it props you to input one of the options but its not reading the input and keeps going on a loop. At the moment I'm stuck

loop = 1
choice = 0

while (loop == 1):
print ("Option 1 - Add")
print ("Option 2 - Subtract")
print ("Option 3 - Multiply")
print ("Option 4 - Divide")
print ("Option 5 - Quit Program")

choice = input("\nPlease select a option: ")
if (choice == 1):
add1 = input("Your input: ")
add2 = input("plus this one: ")
print ("= " , add1+add2,)
elif (choice == 2):
sub1 = input("Your input: ")
sub2 = input("subtracted by this one: ")
print ("= ", sub1 - sub2)
elif (choice == 3):
mult1 = input("Your input: ")
mult2 = input("multipy by this one: ")
print ("= ", mult1 * mult2)
elif (choice == 4):
div1 = input("Your input: ")
div2 = input("divided by this one: ")
print ("= ", div1 / div2)
elif (choice == 5):
loop = 0
Your topic is a bit off.

Your problem is you are comparing a string (choice) against integers (1, 2, 3, 4, or 5). A str will not be equal to an int so none of your "if" conditions are True. That is why it keeps asking you to select an option
Thank you for the advice! I fixed it by changing this:
choice = int(input("\nPlease select a option: "))

but could I have done this problem simpler?

Update: I ran the program to check the other options and fixed the issues. Thank you again
I don't know if simpler, but you could use '1', '2', '3' instead of 1, 2, 3.

Our you could do something really crazy and let your user enter equations in a more natural format like:

3 + 9
5 - 4
8 / 2