-3

I am trying to make a simple guess the number program in python. When I run this code,an error generates saying that,"local variable 'chance' referenced before assignment". I looked up for a solution on internet but I could not rectify my error. Please help with this problem. How can I use the variable globally which is declared inside a function? I am beginner in programming, so plese explain in simple words. Here is the code..

Since I am a beginner,I will be pleased if my code can be rectified

import random
def Random():
    chance = 3
    number = random.randint(0,20)
    return chance
    return number


def main():
    while chance > 0:
        UserInput = int(input('Guess the number: '))
        if UserInput == number:
            print('You have guesses the secret number!')
        elif UserInput > 20 and  UserInput < 0:
                    print('Your guess is out of range!\n Try again!')
        else:
                    chance -= 1
                    if chance == 1:
                            print('You are out of chances!')
                    print('Wrong Guess!\nTry again!')
                    print(f'You have {chance} chances left!')



Random()
main()

playAgain = input('Want to play again? ')
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
    Random()
    main()
else:
    print('Thanks for playing!')
  • First off, you have two return statements, one of them will be ignored. Second, you *can* make a variable `global` and be able to reference it elsewhere in your program. It is not good practice though. – matt Apr 02 '20 at 06:09
  • 1
    Does this answer your question? [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – matt Apr 02 '20 at 06:11
  • I don't understand why my posts were downvoted. Did i do something wrong? If yes, then please inform me as I am new to programming and this website. I will be glad if you answer this question. Otherwise thanks for helping me for the question which I posted! – Shivansh Mishra Apr 03 '20 at 05:31
  • I didn't downvote, but some issues: It is a duplicate question, You have some code issues you never address, The accepted answer is not good practice. Otherwise, I don't get the downvotes, it seems ok and searching similar terms doesn't really give a question that answers what your asking concisely. – matt Apr 03 '20 at 08:24

2 Answers2

1

You can return a list or a tuple to the outside word:

import random

def example():
    chance = 3
    number = random.randint(0,20)
    return (chance, number)  # return both numbers as a tuple


chance, randNr = example()  # decomposes the returned tuple
print(chance, randNr)

prints:

3, 17

There are more bugs in your program, f.e.:

if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':

is always True and you'll never be able to leave the game. Better would be

if playAgain.lower() in {'yes', 'yeah'}:

etc.

Here is a working example for your programs purpose:

import random

while True:
    chances = 3

    number = random.randint(0,20)
    while chances > 0:
        guess = int(input("Guess number: "))
        if guess == number:
            print("Correct")
            break
        else:
            chances -= 1
            print("Wrong, ", chances, " more tries to get it right.")

    if chances == 0:
        print ("You failed")
    if not input("Play again? ")[:1].lower() == "y":
        break
print("Bye.")

Read about tuples

Output:

Guess number: 1
Wrong,  2  more tries to get it right.
Guess number: 4
Correct
Play again? y
Guess number: 1
Wrong,  2  more tries to get it right.
Guess number: 2
Wrong,  1  more tries to get it right.
Guess number: 3
Wrong,  0  more tries to get it right.
You failed
Play again? n
Bye.
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • 1
    Sir, can you please elaborate a bit more? I am having trouble understanding the above example because I am beginner. – Shivansh Mishra Apr 02 '20 at 06:21
  • Thanks for answering the question! Your valuable suggestions will help me improve my programming skills. – Shivansh Mishra Apr 02 '20 at 07:02
  • 1
    Nitpick in the answer: `input("Play again? ").lower()[:1] == "y"` is inefficient. It should be `input("Play again? ")[:1].lower() == "y"`. This is a minimal performance gain, but if the user enters some really long text, it will take longer to convert the whole string to lowercase than just the first char. – Legorooj Apr 02 '20 at 07:04
-4
import random
def Random():
    chance = 3
    number = random.randint(0,20)
    main(chance,number)


def main(chance,number):
    while chance > 0:
        UserInput = int(input('Guess the number: '))
        if UserInput == number:
            print('You have guesses the secret number!')
        elif UserInput > 20 and  UserInput < 0:
            print('Your guess is out of range!\n Try again!')
        else:
            chance -= 1
            if chance == 1:
                    print('You are out of chances!')
            print('Wrong Guess!\nTry again!')
            print('You have',chance,'chances left!')
Random()
playAgain = input('Want to play again? ')
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
    Random()
else:
    print('Thanks for playing!')
Dharman
  • 30,962
  • 25
  • 85
  • 135