如何用一个单词退出循环

问题描述 投票:-1回答:1

我必须使用while编写一个程序:

  1. 会要求用户输入2个整数并返回加法和乘法那些2。

  2. 将检查数字是否为整数。

  3. 如果用户使用单词stop,将关闭。

我赚了1和2,但被卡在3上。这是我写的:

while True:
    try:
        x = int(input("Give an integer for  x"))
        c = int(input("Give an integer for  c"))
        if  x=="stop":
            break


    except:
        print(" Try again and use an integer please ")
        continue

    t = x + c
    f = x * c
    print("the result  is:", t, f)
python while-loop exit
1个回答
1
投票

您的代码不起作用,因为您首先将x定义为整数,并且等于“ stop”,它必须是字符串。

因此,您想要做的是允许将x输入为字符串,如果不是stop,则将其转换为整数:

while True:
    try:
        x = input("Give an integer for  x")
        if  x=="stop":
            break
        else:
            x = int(x)
        c = int(input("Give an integer for  c"))



    except:
        print(" Try again and use an integer please ")
        continue

    t = x + c
    f = x * c
    print("the result  is:", t, f)
© www.soinside.com 2019 - 2024. All rights reserved.