简体   繁体   中英

User input and stuck in while loop

I want my code to take a user input, then prompt the user to continue, if they answer 'y' then it asks for another input, if they answer 'n' the program stops and if they type any other characters it simply continues to prompt them until they enter a 'y' or 'n'.

As the code shows I'm trying to use a while loop to continuously prompt the user until they enter a 'y' or 'n'. However when I reach the while loop it does not stop when a 'y' or 'n' is entered.

def test():

    number = input('Input a number then press enter:')    
    print(number)
    prompt = input('Continue (y/n)? ')

    if prompt == 'y':
        number = input('Input a number then press enter:')
        print(number)
        prompt = input('Continue (y/n)? ')
    elif prompt == 'n':
        pass

    else:
        while prompt != 'y' or 'n':
        prompt = input('Continue (y/n)? ')

This is not how or works:

while prompt != 'y' or 'n':

You probably meant:

while prompt != 'y' or prompt != 'n':

Your version or s prompt != 'y' and 'n' , which always yields at least the last truth-y value ( 'n' ).

The full code:

def test():

    number = input('Input a number then press enter:')    
    print(number)
    prompt = input('Continue (y/n)? ')

    if prompt == 'y':
        number = input('Input a number then press enter:')
        print(number)
        prompt = input('Continue (y/n)? ')
    elif prompt == 'n':
        pass

    else:
        while prompt != 'y' or prompt != 'n':
            prompt = input('Continue (y/n)? ')

To do these kind of input loops I normally use while True with break :

def test():

    prompt = 'y'
    while True:
        if prompt == 'y':
            number = input('Input a number then press enter:')
            print(number)
        elif prompt == 'n':
            break
        prompt = input('Continue (y/n)? ')

您必须使用raw_input()才能将非数字变量用作输入。

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