根据用户请求取消输入命令

Cancelling input command upon user's request

提问人:Prabhaan Goyal 提问时间:9/25/2023 最后编辑:Janez KuharPrabhaan Goyal 更新时间:9/25/2023 访问量:36

问:

我是初学者。我正在创建一个非常基本的计算器。

当用户将命令作为“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: ")
    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 变量。它要么再次要求计算更多,要么应该在用户请求时终止。如何进行更改?

python while-loop 中断

评论

1赞 Codist 9/25/2023
在测试 a 是否为“STOP”之前,您无条件地要求输入 ab

答:

0赞 B. Pantalone 9/25/2023 #1

欢迎使用 Stack Exchange。你对你的代码非常接近。在呼叫这两个号码之前,您需要测试“STOP”命令。如果你像这样重新排列你的代码input()

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)

你应该得到你期望的行为。

评论

0赞 Prabhaan Goyal 9/25/2023
感谢您的帮助!!效果很好!!