atw12
atw12

Reputation: 11

Total guess count not updating

I am a beginner to coding, I am learning python and decided to make a random number guessing game. Everything went great but I want to add a guess counter and I'm not sure why the total wont update.

def random_num():
    guess = int(input("Guess the number, it is between 1-100: "))
    total = 0
    if guess > random_number:
        print("\nLower")
        total += 1
        random_num()
    elif guess < random_number:
        print("\nHigher")
        total += 1
        random_num()
    elif guess == random_number:
        print("\nYou win")
        print("You took " + str(total) + " guesses to get the correct number.")

The output is 0 for total but that is incorrect.

Upvotes: 0

Views: 102

Answers (2)

Senrab
Senrab

Reputation: 257

import random


num = random.randint(1, 12)

user = int(input('Please enter a number from 1 to 100:  '))

counter = 1
while user != num:
    if user > num:
        print('Too high!')
        counter += 1
    else:
        print('Too low!')
        counter += 1
    user = int(input('Please try again:  '))

print('You got it! The number is ' + str(num) + ' and it took you ' + str(counter) + ' tries.') 

This is a simplistic approach to what you want. Notice how the counter works in the while loop and the if-else statement. We already know that the user will take at least one guess, so counter = 1. Every time the user is wrong, which only occurs in the if-else statement, we use counter += 1. Using a While statement ensures that we only add to the counter if the User is wrong.

Upvotes: 0

alex067
alex067

Reputation: 3301

The problem is that you are always declaring total to equal 0 every time you call random_num.

You need to find a way to save the value of total.

HINT: use it as a global variable. A better solution, pass total as a value, as an argument to the parameter.

Upvotes: 2

Related Questions