MrWallace
MrWallace

Reputation: 37

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

Upvotes: 1

Views: 2657

Answers (2)

Reut Sharabani
Reut Sharabani

Reputation: 31339

This is not how or works:

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

You probably meant:

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

Your version ors 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)? ')

Upvotes: 6

caesar getit
caesar getit

Reputation: 225

you have to use raw_input() in order to take non-numerical variables as input.

Upvotes: -2

Related Questions