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

如何在python中创建一个一旦用户输入退出就会中断的循环?,python,Python,我已将代码编辑为以下内容: 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 s

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

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))
我得到了以下错误代码:

您应该在循环中获取输入,否则它将是一个无止境的循环,或者如果您确实写了quit,那么它将只运行一次。根据您提出的问题,==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, 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))

您的问题是每个循环调用输入两次。因此,名词被设置为
“苹果5”
,数字被设置为
“鞋子2”
,不能转换为整数。您可以拆分输入以获得您的名词和数字。

将输入语句放入while循环,否则它只会询问一次。
else
仅在
while
条件为非真时执行,您移除
else
并且每次都会执行,除非您在它之前中断(这是您想要的)也正确缩进。
else
应与
if
对齐。它现在和
联系在一起,而
。我现在非常爱你。lol拆分输入最终使其工作,以便通过我程序中的所有测试。
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))