我是初学者。我正在创建一个非常基本的计算器。
我想在用户发出“停止”命令时中断程序。这是我的代码:
while d=="yes" or d=="YES" or d=="Yes":
a=input("Enter: A for additon, B for Subtraction, C for Multiplication, D for Division: ")
b=int(input("Enter the first number: "))
c=int(input("Enter the second number: "))
if a=="A":
print(b+c)
elif a=="B":
print(b-c)
elif a=="C":
print(b*c)
elif a=="D":
print(b/c)
elif a=="STOP":
break
我尝试输入“STOP”,但输出如下:
Do you want to calculate more? YES
Enter: A for additon, B for Subtraction, C for Multiplication, D for Division: B
Enter the first number: 46
Enter the second number: 23
23
Enter: A for additon, B for Subtraction, C for Multiplication, D for Division: STOP
Enter the first number: 1
Enter the second number: 23
收到输入“STOP”后,它再次询问第一个和第二个数字,即 b 和 c 变量。它要么应该再次要求计算更多,要么应该根据用户的请求终止。我怎样才能做出改变??
欢迎来到堆栈交换。你与你的代码非常接近。在为这两个号码拨打
input()
之前,您需要测试“STOP”命令。如果你像这样重新排列你的代码
while d=="yes" or d=="YES" or d=="Yes":
a=input("Enter: A for additon, B for Subtraction, C for Multiplication, D for Division: ")
if a=="STOP":
break
b=int(input("Enter the first number: "))
c=int(input("Enter the second number: "))
if a=="A":
print(b+c)
elif a=="B":
print(b-c)
elif a=="C":
print(b*c)
elif a=="D":
print(b/c)
您应该得到您期望的行为。