我是一名Python編程的初學者,並且遇到了我的代碼問題。循環到用戶提示
當用戶鍵入無效操作時,它通知用戶但退出程序(第33行)。我怎樣才能讓用戶再次進入數學運算?
#This python program calculates the sum, difference, product, or quotient of two numbers defined by users.
#Define add function and return the result of num1 + num2
def add(num1, num2):
return num1 + num2
#Define subract function and return the result of subtracting num1 - num2
def sub(num1, num2):
return num1 - num2
#Define multiplication function and return the result of multiplying num1 * num2
def mul(num1, num2):
return num1 * num2
#Define division function and return the result of dividing num1/num2
def div(num1, num2):
return num1/num2
#Define main purpose/function of the program
def main():
#Ask what math operation to perform
operation = input("What do you want to do? (+, -, *, /): ")
#If the operation is not +, -, *, or /, invalid operation
if(operation != '+' and operation != '-' and operation != '*' and operation != '/'):
print("You must enter a valid operation!")
#If valid, perform specified operation
else:
var1 = int(input("Enter num1: "))
var2 = int(input("Enter num2: "))
if(operation == '+'):
print(add(var1, var2))
elif(operation == '/'):
print(div(var1, var2))
elif(operation == '-'):
print(sub(var1, var2))
else:
print(mul(var1, var2))
main()
你可以把'main'在一個循環如下:'而1:主()' – ozgur
您可能希望在循環使用爲第一個操作輸入而不是'if ... else'。你的操作和var1,var2是按順序的。不像你需要這樣或那樣的。這就是當你選擇無效操作時程序退出的原因。 – Aung
看看[詢問用戶輸入信息,直到他們給出有效回覆](http://stackoverflow.com/q/23294658/4014959),它還會告訴你如何處理輸入的無效數字。 –