Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Functions
#1
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
Reply
#2
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
Reply
#3
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
Reply
#4
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
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020