def calculate():
operator = input("What operator do you wanna use(*,/, ,-)? ")
possible_op = ["*", " ", "-", "/"]
if not operator == possible_op:
calculate()
number_1 = float(input("What is your first number? "))
if number_1 != float:
calculate()
number_2 = float(input("What is your second number? "))
if number_2 != float:
calculate()
if operator == " ":
print(number_1 number_2)
elif operator == "-":
print(number_1 - number_2)
elif operator == "*":
print(number_1 * number_2)
elif operator == "/":
print(number_1 / number_2)
else:
print("Wrong Input")
calculate()
again()
def again():
print("Do you wanna calculate again? ")
answer = input("(Y/N) ").lower()
if answer == "y":
calculate()
elif answer == "n":
exit
else:
print("Wrong Input")
again()
calculate()
Does anyone have an idea why my code always asks the operator questions again and again even if there was a right operator? Do i have to change the name of the list and the input getting compared or
CodePudding user response:
There are quite a few things wrong in this code, but you've managed to use what you know and are in the right tracks so rather than giving you a solution I'll just review it for now.
Mostly, I'd recommend to keep your calculate function simple and handle the looping (rather than recursion) somewhere else.
def calculate():
operator = input("What operator do you wanna use(*,/, ,-)? ")
possible_op = ["*", " ", "-", "/"]
if not operator == possible_op: # this will never be true because operator is a string, use `not in`
calculate() # you probably don't want to run calculate again, maybe return early
number_1 = float(input("What is your first number? "))
if number_1 != float: # number_1 is a float it's not the `float` type so always True
calculate() # return
number_2 = float(input("What is your second number? "))
if number_2 != float: # same as number_1 above
calculate() # return
if operator == " ": # this block is good, simple and to the point
print(number_1 number_2)
elif operator == "-":
print(number_1 - number_2)
elif operator == "*":
print(number_1 * number_2)
elif operator == "/":
print(number_1 / number_2)
else:
print("Wrong Input") # here you also want to retry
calculate() # but not by recursing
again() # and definitely not call again
def again():
print("Do you wanna calculate again? ")
answer = input("(Y/N) ").lower()
if answer == "y":
calculate()
elif answer == "n":
exit # what is this exit ?
else:
print("Wrong Input")
again() # also don't recurse this, loop if you want
calculate()