如何用一个单词摆脱循环

2024-06-06 14:57:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须使用while制作一个程序,该程序:

  1. 将要求用户输入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)

Tags: 用户程序anforinput数字整数integer
2条回答

只需要做一点小小的更改(并且可以在try块中使用else稍微结构化一些

您需要将第一个值作为字符串输入,以便您可以首先测试它的“停止”,然后才尝试将其转换为整数:

while True:
    try:
        inp = input("Give an integer for x: ")
        if inp == "stop":
            break
        x = int(inp)
        c = int(input("Give an integer for  c: "))
    except:
        print("Try again and use an integer please!")
    else:
        t = x + c
        f = x * c
        print("the results are", t, f)

我还解决了一些间距问题(即字符串中的多余空格和缺少空格)

您的代码无法工作,因为您首先将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)

相关问题 更多 >