Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何用一个单词摆脱循环_Python - Fatal编程技术网

Python 如何用一个单词摆脱循环

Python 如何用一个单词摆脱循环,python,Python,我必须使用制作一个程序,而必须: 将要求用户输入2个整数 并返回加法和乘法 在这两个人当中 将检查数字是否为整数 如果用户使用单词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":

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

  • 将要求用户输入2个整数 并返回加法和乘法 在这两个人当中

  • 将检查数字是否为整数

  • 如果用户使用单词
    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)
    

    您的代码不起作用,因为您首先将
    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)
    

    只需稍作更改(并且可以在
    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)
    

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

    您的
    if
    将始终为false(如果
    x
    stop
    ,当您尝试将其转换为
    int
    时,会出现异常).我已经做了1和2,但是被3卡住了。这个程序有什么问题吗?除了那样,不要使用裸的,请参见。你真的不需要
    其他的
    (尽管使用它没有错)“
    else
    有什么帮助?@ScottHunter这没什么大不了的,但是除了
    块之外,
    块中不再需要有一个
    continue
    语句,它会更清楚地显示在没有异常时要执行的备用代码。最后。”。