Stuck in while loop and it doesnt work how I thought it would work

Viewed 34

I'm trying to do a number guessing game where the computer selects a random number and you have to guess it and get an output that's either: Your number is too high, too low or correct number + needed attempts. However with this code:

import numbers
from random import randint
#set x to a random number between 1 and 50
randomnummer = randint(1,51)
print (randomnummer)
#counter = 0
#ask to input a number between 1 and 50 and check if input is valid
def nummer_eingabe():
    usernummer = (input("Please enter a number between 1 and 50: "))
    usernummer = int(usernummer)
    #counter = counter + 1
    if usernummer >= 1 and usernummer <= 50:
        return usernummer
    else:
        print("Pleae enter a valid number.")
        return nummer_eingabe()

#declare number from function
checked_user_nummer = nummer_eingabe()

#define counter
counter = 0

while checked_user_nummer != randomnummer:
    counter += 1
    if checked_user_nummer > randomnummer:
        print("You need to guess lower. Try again :)")
        nummer_eingabe()
        continue
    elif checked_user_nummer < randomnummer:
        print("You need to guess higher. Try again :)")
        nummer_eingabe()
        continue
    elif checked_user_nummer == randomnummer:
        strcounter = str(counter)
        print("Nice! You needed " + strcounter + " tries to find the right number")
        break
#dont allow console to close right away
input()

it goes well until it gets stuck giving the same feedback (either too high or too low) How do I get out of the While loop? I tried changing up the continue statement with a break but that just causes the code to stop after the second time the input was given. Also please dont mind the print(randomnummer) on line 5; that's just for debugging purposes.

2 Answers

You never reassign the variable. You call nummer_eingabe() but you discard the result.

You're now in a stage where you no longer want to debug your code using print() statements but learn how to debug small programs.

Make sure you don't write code in Notepad and use a decent IDE like Pycharm instead. Set a breakpoint wherever your code gets stuck (just click left of the code and right of the line number)

Breakpoint

and hit the little bug icon to debug it. You will be able to see the variables on the go. After each single line of code, check if they match your expectation

Variables

After entering a value of 10, you'll see that the variable is still 50 - a clear indicator that the value did not get updated because you didn't make use of the return value of the function.

After user input

Don't call the function again on the while, instead do a while to check for a "trigger" and then use your while checked_user_number != randomnummer:

Then instead of break use the trigger = False and end the while.

Related