我无法让我的Python 3创建的程序停止运行我的循环。我究竟做错了什么?输出每个功能后,我需要能够返回主菜单。
帮助!
# define functions
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
# take input from the user
loop = 1
while loop ==1:
print ("Hi Prof. Shah! Welcome to my Project 3 calculator!")
print("Please select an operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.Remainder")
print("6.Exit")
choice = input("Enter choice(1/2/3/4/5/6):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
elif choice == '5':
print(num1,"%",num2,"=", remainder(num1,num2))
elif choice == '6':
print("Goodbye, Prof. Shah!")
提前感谢您的帮助。
答案 0 :(得分:1)
您只需使用表达式loop
设置loop = 1
的值。稍后,您需要将其更改为1以外的值才能退出循环,因为条件为loop == 1
。
在循环中的适当位置将loop
的值设置为1以外的值。
答案 1 :(得分:0)
您需要在每次“打印”后添加“break”,以便打印信息后while循环可能会中断。例如:
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
break
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
break
答案 2 :(得分:0)
您没有更改loop
的值,而是导致无限循环。
这是一个建议:
flag = True
while flag:
print ("Hi Prof. Shah! Welcome to my Project 3 calculator!")
print("Please select an operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.Remainder")
print("6.Exit")
choice = int(input("Enter choice(1/2/3/4/5/6):")) #dangeeer!!
if choice >= 1 and choice < 6: #here you keep inside the loop.
x = float(input("First value:")) #dangeeer!!
y = float(input("Second value:")) #dangeeer!!
if choice == 1 : print(add(x, y))
elif choice == 2: print(subtract(x, y))
elif choice == 3: print(multiply(x, y))
elif choice == 4: print(divide(x, y))
elif choice == 5: print(remainder(x, y))
elif choice == 6: #here you get out of the loop
print("Goodbye, Prof. Shah!")
flag = False
else:
print("Choose a number between 1 and 6")