How would I allow the user to do math with their own input? [duplicate]
Solution 1:
Based on the code above, you are never actually running main()
. Right now, you have said that the definition of main
is to prompt the user, check if the input was correct, and then do the math. The main()
at the end causes the program to repeat after doing all this (not sure if you want the loop or not).
If you don't want the loop, and just want to run the calculator once, just remove the indent of the last main()
, because right now the indentation means it is inside of def main()
. Just move it to the left to be at the same indentation level as the def main():
and your program should run fine.
Solution 2:
I think you are missing:
if __name__ == "__main__":
main()
Your call to main()
inside main
itself won't execute and that's probably why you aren't getting any input.
Other than that your code should work as expected (make sure you don't divide by zero ;) ).
Edit: to make my answer more obvious, you should have done:
def main():
operation = input("What do you want to do?(+, -, *, or /):")
if (operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("Your input is invalid. Please enter a valid input.")
else:
num1 = float(input("Enter value for num1: "))
num2 = float(input("Enter value for num2: "))
if (operation == "+"):
print(add(num1, num2))
elif (operation == "-"):
print(subtract(num1, num2))
elif (operation == "*"):
print(multi(num1,num2))
elif (operation == "/"):
print(div(num1,num2))
if __name__ == "__main__":
main()
Solution 3:
num1=float(input("enter the first number :"))
op = input("sellect the operation :")
num2 = float(input("enter the second number :"))
if op== "+" :
print(num1+num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1*num2)
elif op == "/":
print(num1 / num2)
else:
print("please enter a real operation ")
#this one is more simple