Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with name error
#1
import random

def add(): # defines sub program
    num1 = random.randint(5,20) # creates random number between 5 and 20
    num2 = random.randint(5,20) # creates random number between 5 and 20
    correct = num1 + num2 # defines correct answer
    print('What is ', num1, ' + ', num2, '?') # ask user to input their answer
    answer = int(input('Please enter your answer')) 
    answers = (correct, answer)
    return answers # return the answers

def sub():
    num3 = random.randint(25,50) # creates random number between 25 and 50
    num4 = random.randint(5,20) # creates random number between 5 and 20
    correct = num3 - num4
    print('What is ', num3, ' - ', num4, '?') # asks user to input their answer
    answer = int(input('Please enter your answer'))
    answers = (correct, answer)
    return answers # return the answers

print('1) Addition') # Prints menu then asks user to choose option 1 or 2 
print('2) Subtraction')
num = int(input('Enter 1 or 2:'))

if num == 1: # runs add() program if 1 is selected 
    add()
elif num == 2: # runs sub() program if 2 is selected
    sub()
else:
    print('Error! You did not enter a 1 or a 2') # or prints this error message

def check(correct,answer): # defines subprogram called check using previously returned variables
    if answer == correct: # gives this message if the correct answer was given
        print('Correct')
    else: # gives this message if an incorrect answer was given
        print("Incorrect, the correct answer is ", correct)

check(correct,answer) # runs the check subprogram
Hi the above code gives me the following error message:

Error:
check(correct,answer) # runs the check subprogram NameError: name 'correct' is not defined
However I think that I have defined the variable correct in my code can anyone help?

Thanks
Reply
#2
Yes, "correct" is in the code, but only in the def ..().
Looks like a scoping problem.

Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply
#3
Hi,

All credit to DPaul, i would not figure it out, i mean rather later than sooner.

Simply, ,,correct,, is a variable of local scope, that means it is visible to the code within the function definition. The code outside the function definition does not see it.

And by the way, once you sort out ,,correct,, the ,,answer,, will be next but you'll be on a correct path to sort it out too.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020