0

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
5
  • Please fix your indentation. Commented Oct 17, 2020 at 2:11
  • Can you identify what is different about the times it requires 3 inputs? Are there any situations where it requires 1? Commented Oct 17, 2020 at 2:12
  • Sorry, I missed that while copying the code. Nothing is different, it is completely at random. Commented Oct 17, 2020 at 2:18
  • It isn't even close to being random. Commented Oct 17, 2020 at 2:19
  • Well, all i noticed was that sometimes it needed 1, sometimes 2, sometimes 3, all while input was the same. Anyways, It has been solved below, thanks for your input :) Commented Oct 17, 2020 at 2:24

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this has basically fixed it, although there remains something peculiar. If I don't type 1 or 2 the first time, it will again require multiple inputs of 1 or 2 to end the loop (this is after applying your fix).
@Vellutante Did you use the code as I have in the answer? Because the problem you're describing sounds like you still have the else-statement in place
Yep you were right, removed the else statement and it works perfectly. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.