Higher or Lower game

I'm trying to build a simple python game where you have to guess whether the next number will be higher or lower. The number range that the computer can pick is 1, 21.

The user inputs higher or lower (H or L) and the computer randomly generates a second number which it then checks against the first to determine whether the user guessed correctly.

The issue I am coming up against is that once the computer generates the second number, I want the loop to then continue with that as the number that the user has to guess against.

For example:

computer number - 11 user inputs higher second number - 15

user is correct. They then have to guess whether the next number will be higher or lower than 15.

I am unable to get the second number to be the number the user guesses against and instead the loop is starting again with the number always at 11 which is the starting point I set.

Anyone know how to get this to work?

Code:

streak = 0 print(artwork.title) print("Welcome to High or Low!\nDo you think the next number will be higher or lower?") print("\nThe game always starts with the number 11, get a streak of 5 to win!") end_of_game = False while not end_of_game: first_number = 11 second_number = random.randint(1, 21) player_input = input("\nHigher or Lower? Type H or L\n").lower() if player_input == "h" and second_number > first_number: streak += 1 print(f"{second_number} Correct!") first_number = second_number print(f"Current Streak is: {streak}") print(f"\n\nThe current number is: {first_number}") if streak == 5: print("Congratulations YOU WIN!") end_of_game = True elif player_input == "l" and second_number > first_number: print(f"{second_number}, Unlucky") print("\nTry again, the number is 11") streak = 0 elif player_input == "h" and second_number < first_number: print(f"{second_number}, Unlucky") print("\nTry again, the number is 11") streak = 0 elif player_input == "l" and second_number < first_number: streak += 1 print(f"{second_number} Correct!") first_number = second_number print(f"Current Streak is: {streak}") print(f"\n\nThe current number is: {first_number}") if streak == 5: print("Congratulations YOU WIN!") end_of_game = True 

I've only been doing this for a week so my code looks like alphabet soup.. Apologies!

3

1 Answer

The problem is you're resetting first_number to 11 at the top of the loop:

while not end_of_game: first_number = 11 ... 

So even though you set first_number = second_number in the loop when the player wins, it's just getting reset to 11 on the next iteration.

To fix it, just move the initialization out of the loop, so it only executes once, before entering the loop:

first_number = 11 while not end_of_game: ... 
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like