How do I stop redefining a variable after every loop of a function?

Viewed 106

I am relatively new to Python, but I tried making random number generator guessing game where you just guess the number and if it's right you win and if you lose the attempt counter decreases, like this:

import random

a = random.randint (1, 20)
c = input('Select difficulty (1, 2, 3, 4) : ')
d = int(c)

def main():
         
    if d == 1:
        tries = e = 15
    elif d == 2:
        tries = e = 10
    elif d == 3:
        tries = e = 5
    elif d == 4:
        tries = e = 3
    else:
        tries = e = 1
        

            
    for tries in range(tries, -1, -1):
        tries -= 1

        b = int(input('Pick a number from 1-20 :  '))
                
        if a == b:
            print('Congratulations!')
            print('# of tries : ', e - tries)
            exit()
        elif tries == 0:
            print('No more attempts left, game over')
            exit()
        else:
            print('Incorrect')
            print('Attempts left : ', tries) 
           
        restart = input("Play again? (y/n)")
        if restart == "y":
            main()
        else:
            exit()
main()

So this program doesn't make sense unless you guess correctly on the first try because the attempt counter always stays the same. I think it's because everytime it goes back to the main() it redefines 'tries' as 15, 10, etc. The problem is if I put the 'if d == 1' section before def main() then it will say that 'tries' was referenced before assignment. There's probably a simple solution that I'm not seeing here and it's going way over my head, so hopefully what I'm asking makes sense. Feedback on the code irrelevant to the issue also appreciated.

Thanks.

3 Answers

The other answers will work just fine, but as a side note, you're calling main() inside main() which creates a recursive function. Unless you have a particular reason to do this, it should be avoided. Every previous attempt at the game will be held in memory until the user opts not to retry, and if you go far enough you'll run into a RecursionError. Try wrapping the whole program in a while loop, something like this:

import random


def main():    
    retry = True

    while retry:
        answer = random.randint(1, 20)
        tries = 5  # Insert your own logic for num of tries
        while tries > 0:
            guess = int(input('Pick a number between 1 and 20: '))
            if guess == answer:
                print('Correct!')
                break
            else:                
                print('Incorrect')
                tries -= 1
                
        retry = input("Play again? (y/n)") == 'y'


main()

It's a little confusing to me why you're doing tries = e = num

A much cleaner way to do it would be to have a while loop that runs while the number of tries hasn't run out. You could set that number of tries to a variable based on the selected difficulty

One way to do it could be like this:

import random

# set number of tries based on difficulty chosen first, then all this

number = random.randint(1,50)
number_of_guesses = 0

while number_of_guesses < tries: 
    guess = input("Take a guess ")
    guess = int(guess)

    number_of_guesses = number_of_guesses + 1;
    guesses_left = tries - number_of_guesses;

    if guess < number:
        print("Your guess is too low! You have " + str(guesses_left) + " guesses left")

    if guess > number:
        print("Your guess is too high! You have " + str(guesses_left) + " guesses left")

    if guess == number:
        break

if guess == number:
    print("Good job! You guessed the number in " + str(number_of_guesses) + " tries :)")

if guess != number:
    print("Sorry. The number I was thinking of was " + str(number) + " :)")

I changed the for loop to a while loop, removed the "tries = e = 15" and moved the "tries -= 1"

import random

a = random.randint (1, 20)
c = input('Select difficulty (1, 2, 3, 4) : ')
d = int(c)

def main():
     
    if d == 1:
        tries = 15
    elif d == 2:
        tries = 10
    elif d == 3:
        tries = 5
    elif d == 4:
        tries = 3
    else:
        tries = 1
        
    while tries > 0:

        b = int(input('Pick a number from 1-20 :  '))
            
        if a == b:
            print('Congratulations!')
            print('# of tries : ', tries)
            exit()
        else:
            print('Incorrect')
            tries -= 1
        
            print('Attempts left : ', tries)
        
       
    restart = input("Play again? (y/n)")
    if restart == "y":
        main()
    else:
        exit()
main()
Related