繁体   English   中英

如何在 python 中创建一个循环,一旦用户输入退出就会中断?

[英]How do I create a loop in python that will break once user inputs quit?

在此处输入图片说明

我已将代码编辑为以下内容:

while(True):
    #get user to input a noun as a string variable
    noun = input()
    
    #get user to input a positive number for the integer variable
    number = int(input())

    #if the user inputs quit into the string variable stop program
    if noun == 'quit':
        break
    #otherwise print the output
    else:
        print('Eating {} {} a day keeps the doctor away.'.format(number,noun))

我收到以下错误代码: 在此处输入图片说明

你应该在循环内输入输入,否则它是一个无限循环,或者如果你写了退出,那么它只会运行一次。 此外,根据您提出的问题, == 0 条件不需要从循环中中断。

问题是你只需要第一个输入,只需在循环内输入输入即可。

另外 else 应该与 if 语句相同,并且您不需要 number == 0 条件,因此生成的代码应该类似于:

while(True):
    #get user to input a noun as a string variable
    noun = input()
    
    #get user to input a positive number for the integer variable
    number = int(input())

    if noun == 'quit':
        break
    else:
        print('Eating {} {} a day keeps the doctor away.'.format(number,noun))

这是我将如何编写。 :)

while True:
    noun = input("Enter a noun: ")
    if noun == 'quit':
        print("Quitting the program...")
        break

    while True:
        number = input("Enter a number: ")
        try:
           if type(int(number)) == int:
               break
        except ValueError:
            print("Invalid input. Please enter a number.")
 
    if number == '0':
        print("Quitting the program...")
        break
    
    print("Eating {} {} a day keeps the doctor away.".format(number, noun))   

看起来你编辑了代码,因为这些答案,这应该有效

while(True):
    noun, number = input().split()
    number = int(number)

    #if the user inputs quit into the string variable stop program
    if noun == 'quit':
        break
    #otherwise print the output
    else:
        print('Eating {} {} a day keeps the doctor away.'.format(number,noun))

你的问题是你在每个循环中调用 input 两次。 因此,名词设置为'apples 5' ,数字设置为'shoes 2' ,不能转换为整数。 您可以拆分输入以获取名词和数字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM