繁体   English   中英

python中的NameError是什么意思?

[英]What does NameError mean in python?

我无法了解我的代码中的错误所在。

`

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)


` 当我尝试运行它时,发生了 NameError。 我不知道我的错误在哪里/

变量num1num2在 function cauculator 的cauculator中定义,但您正在从未定义它们的全局 scope 访问它们。 您的代码也有一些其他问题。 这是您的代码的编辑版本:

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))

随时询问是否需要帮助理解它。

您的代码包含几个错误。 这是我认为您正在尝试实现的代码:

    #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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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