I'm trying to make a simple guessing game in Python. I, the user, has three guesses to guess the correct number. I tried to do it by myself and I used the if statement, while in the correct solution, while loop should be used. My solution works quite well but when I guess the correct number in the first or second try, I receive an error that inputs are missing for second/third number, please see code below. I understand that 'break' can only be used in a while loop. Is there a way to make this work using the if statement or is this only solvable by using the while loop? Beginner 'coder' here, please have patience. Thank you!
correct = 3
first_number = int(input('Guess: '))
if first_number == correct:
print('You win!')
elif first_number != correct:
second_number = int(input('Try again: '))
if second_number == correct:
print('You win, second guess!')
elif second_number != correct:
third_number = int(input('Last guess: '))
if third_number == correct:
print('Finally!')
elif third_number != correct:
print('You lose!')
Python 3.8. We use the walrus operator in a while loop.
Before:
correct = 3
first_number = int(input('Guess: '))
if first_number == correct:
print('You win!')
elif first_number != correct:
second_number = int(input('Try again: '))
if second_number == correct:
print('You win, second guess!')
elif second_number != correct:
third_number = int(input('Last guess: '))
if third_number == correct:
print('Finally!')
elif third_number != correct:
print('You lose!')
After:
correct = 3
while (first_number := int(input('Guess: ')) is not correct):
print('Try again!')
else:
print('You win!')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With