Skip to content
Advertisement

What does NameError mean in python? [closed]

I cannot get where my error is in my code.

def cauculator (num_1,num_2):
    #num_1 is the first number to be cauculated, when num_2 is the second.
    return (a+add+b+sub+c+mul+d+div)

div = num_1/num_2
mul = num_1*num_2
add = num_1+num_2
sub = num_1-num_2

#the reason I did this is because I will use these "subsitute" names to print the result out.

a= "Added"
b= "Subtracted"
c= "Multiplied"
d= "Divided"

print (a+add+str('n')+b+sub+str('n')+c+mul+str('n')+d+div)

print (cauculator) (3,8)
print (cauculator) (5,2)
print (cauculator) (9,5)

When I try to run this, the NameError happens. I do not know where my error is.

Advertisement

Answer

variables num1 and num2 are defined within the scope of function cauculator but you are accessing them from the global scope where they are not defined. Your code also has some other issues too. here is an edited version of your code:

def cauculator (num_1,num_2):
    #num_1 is the first number to be cauculated, when num_2 is the second.
    div = num_1 / num_2
    mul = num_1 * num_2
    add = num_1 + num_2
    sub = num_1 - num_2
    output_string = f'Added = {add}, Subtracted = {sub}, Multiplied = {mul}, Divided = {div}'
    return output_string


print(cauculator(3, 8))
print(cauculator(5, 2))
print(cauculator(9, 5))

feel free to ask if need help understanding it.

Advertisement