1

I've recently being self teaching python and I'm making my first attempt at a game. The idea is the user must guess what the answer is (integer) My code is not yet complete but the first half won't work.

My code:

highest = 10
answer = 7
guess = int(input("What is your guess?"))
def guessingGame():
    print("try again please")
    guess = int(input("what is your guess?"))

while (int(guess) != answer):

    if (int(guess) < answer):
        print ("Answer is higher!")
        guessingGame();

    elif (int(guess) > answer):
        print ("Answer is lower!")
        guessingGame();

No matter whether I enter a value less then the answer(which is 7) or higher, It will always say ;"The answer is higher!" What am I doing wrong? Thanks!

EDIT: I'm also aware my code might be incredibly buggy/poorly written and would love any criticism/improvements.

Damhan Richardson
  • 419
  • 1
  • 5
  • 16

1 Answers1

0

The guess variable that you edit in guessingGame is not the same one you are comparing in the while loop.

Adding global guess to the top of the guessingGamefunction should solve it.

For future reference, if something is not behaving, it's often useful to print the variables at various stages to see what things are. (for larger programs a debugger is more useful but on stuff like this, printing is fine).

Edit: with respect to the criticism/improvements comment:

  • functions should be named after what they do. guessingGame should be named something like updateUserGuess. Rather than rely on globals I think I'd make that function return the guess and assign the value to the guess variable outside the function.

  • the elif condition is not needed. If the guess isn't < answer and not equal it must be higher

  • you call guessingGame whether the guess is higher or lower so it can be moved out of the if/else statements

  • you are casting the guess to an int every time you use it (in the guessingGame function and then again in each of the conditions). Nothing really wrong with that but it's not necessary. If it's stored as an int, use it as one.

Holloway
  • 6,412
  • 1
  • 26
  • 33