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()
有誰知道為什么我的代碼總是一次又一次地詢問操作員問題,即使有一個正確的操作員?我是否必須更改串列的名稱并比較輸入或
uj5u.com熱心網友回復:
這段代碼有很多問題,但你已經設法使用你所知道的并且處于正確的軌道上,所以我現在只對它進行審查,而不是給你一個解決方案。
大多數情況下,我建議讓您的計算函式保持簡單并在其他地方處理回圈(而不是遞回)。
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478296.html
