samedi 4 juillet 2020

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

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.




Aucun commentaire:

Enregistrer un commentaire