0

I am a beginner at python and currently working on a project. When I try to run this code, it keeps telling me that random_Number and users_Guess is not defined.

#Impots the random module
import random


#Calls all functions
def main():
    generateNumber()
    inputUsersGuess()
    displayAnswer()

#Generates the random number
def generateNumber():
    random_Number=random.randint(1,100)
    return random_Number


#Takes the users guess
def inputUsersGuess():
    users_Guess=int(input('I am thinking of a number. What is the number? '))
    return users_Guess

#Compares the users guess with the number generated
def displayAnswer():
    if random_Number==users_Guess:
        print('You guessed correctly!')
    else:
        print('Sorry, your guess is incorrect. I was thinking of',random_Number)

#Calls the main function
main()
  • Does this answer your question? [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – sorosh_sabz Oct 06 '21 at 19:43

2 Answers2

1

Don't try to make a local variable available in other functions. The whole purpose of dividing your program into different functions is to isolate one function from the internals of another function.

Instead, pass the values between the functions that need them. First, have main() actually pick up the numbers the functions are returning. As your code stands it is throwing the returned values away.

def main():
    random_number = generateNumber()
    guess = inputUsersGuess()
    displayAnswer(random_number, guess)

Here I have changed the signature of the function displayAnswer() to accept the two returned values passed in from main(). So that needs to be reflected in the function definition:

def displayAnswer(random_Number,users_Guess):
    if random_Number==users_Guess:
        print('You guessed correctly!')
    else:
        print('Sorry, your guess is incorrect. I was thinking of',random_Number)
BoarGules
  • 16,440
  • 2
  • 27
  • 44
0

You shouldn't use global variables if you can help it. Return values from your functions and then pass them to the other functions that need them

import random


def main():
    number = generate_number()
    users_guess = input_users_guess()
    display_answer(number, users_guess)


def generate_number():
    return random.randint(1,100)


def input_users_guess():
    return int(input('I am thinking of a number. What is the number? '))


def display_answer(number, users_guess):
    if number == users_guess:
        print('You guessed correctly!')
    else:
        print('Sorry, your guess is incorrect. I was thinking of', number)

main()
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50