简体   繁体   中英

What does NameError mean in python?

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/

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.

Your code contains several bugs. Here is the code that I think you are trying to implement:

    #num_1 is the first number to be cauculated, when num_2 is the second.
    return_str = "%d %d\t%d\t\t%d %d\t\t%d\t%d %d\t\t%d\t%d %d\t\t%d" % \
                    (num_1, num_2, num_1+num_2, num_1, num_2, num_1-num_2, 
                    num_1, num_2, num_1*num_2, num_1, num_2, num_1//num_2)
    return return_str

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"

# sep is the keyword for seperator to add between comma seperated vales
print (a, add, b, sub, c, mul, d, div, sep = "\t") 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM