user13597630
user13597630

Reputation:

Python, Pycharm IDE user input loop sometimes does not work

I use pycharm IDE. I made a while loop that loops an input. It only accepts the user typing 1 or 2, otherwise it continues looping. When I run it, sometimes it needs me to type 1 or 2 twice before accepting it and concluding the loop.

Welcome to hangman! Please press 1 for English, 2 for Italian and press enter.2

Welcome to hangman! Please press 1 for English, 2 for Italian and press enter.2

Hai scelto italiano. Cominciamo

As seen here, it required 2 inputs to break the loop. It seems to do this 40% of the time.

The loop is as follows:

while True:
if user_input() == '1':
    print('You have selected English. Let us begin')
    break
elif user_input() == '2':
    print('Hai scelto italiano. Proseguiamo')
    break
else:
    user_input()

Sometimes this doesn't happen, sometimes it requires 3 inputs... Is it a problem with the code??

The user_input() function is simply:

def user_input():
    inp_1 = input('Welcome to hangman! Please press 1 for English, 2 for Italian and press enter.')
    return inp_1

Upvotes: 0

Views: 427

Answers (1)

Ted Klein Bergman
Ted Klein Bergman

Reputation: 9736

You're calling user_input() in your conditions, which means it has to call the function each time to check whether the condition is true (which prompts the user for input). Instead, call it once and store the result in a variable.

while True:
    choice = user_input()
    if choice == '1':
        print('You have selected English. Let us begin')
        break
    elif choice == '2':
        print('Hai scelto italiano. Proseguiamo')
        break

Upvotes: 2

Related Questions