简体   繁体   中英

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

在此处输入图片说明

I've edited my code to the following:

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))

And I get the following error codes: 在此处输入图片说明

You should be taking the input inside the loop, otherwise it is an endless loop or if you did write quit then it would just run once. Also there is no need for the == 0 condition to break from the loop according to the problem you have presented.

The problem is that you just take the first input, just get the inputs inside the loop insted.

Also the else should be idented with the if statement and you don't need the number == 0 condition, so the resulting code should be somehting like:

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))

Here is how I would write. :)

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))   

It looks like you edited the code since these answers, this should work

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))

Your problem was that you're calling input twice every loop. So, noun was set to 'apples 5' and number was set to 'shoes 2' which cannot be converted to an integer. You can split the input to get your noun and number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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