Python Python Basics (2015) Number Game App Number Game Refinement

maxmaltsev
maxmaltsev
3,419 Points

Number Game Issues

Hello,

I am trying to understand what's wrong with below code.

In the terminal it gives error "random_num" is not defined, meaning that It can't find variable random num, but it's been generated in the first function and to make sure I even displayed it by .format(random_num):

Guess a number between 1 and 10: 2 Traceback (most recent call last): File "random_game.py", line 29, in <module> main_body() File "random_game.py", line 21, in main_body if player_input == random_num: NameError: global name 'random_num' is not defined

Below works if number generating process taken out of number_generator() function. But why?

def number_generator():
    import random

# generate a random number betwee 1 and 10
    random_num = random.randint(1, 10)
    print("......")
    print("Random number has been generated.{}".format(random_num))
    print("......")



def main_body():
    #introduction
    print("Hello, this is a Random Number Guessing Game. You will have 10 tries to guess a random number in range from 1 to 10.")
    number_generator()
    number_of_tries = 10
    while number_of_tries > 0:
        # get a number guess from the player
        player_input = int(input("Guest a number between 1 and 10: "))
        # compare guess to secret number
        if player_input == random_num:
            print("You selected {} and computer also selected {} - Congrats!".format(player_input, random_num))
            break
        else:
            number_of_tries = number_of_tries - 1
            print("Wrong! You now have {} tries left.".format(number_of_tries))
    else:
        print("You've lost! No tries left. ")
#calling the function
main_body()

1 Answer

Chris Howell
Chris Howell
Python Web Development Techdegree Graduate 49,484 Points

Hey maxmaltsev

So it looks like the reason it is giving you an error is mainly because of your variable scope. Meaning that the variables you create INSIDE a function are local and only exist INSIDE that function.

So that variable you created inside number_generator() cannot be seen outside of its containing function, this way you can reuse the same variable in multiple functions.

One thing you could do is have number_generator() - return the random_num variable. Then inside main_body you can create a new variable also called random_num set it equal to the number_generator() function call you have inside main_body.

Does that make sense?