在Python中,NameError是什么意思?[已关闭]

hwamh0ep  于 2022-12-28  发布在  Python
关注(0)|答案(2)|浏览(184)

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
28分钟前就关门了。
Improve this question
我找不到代码中的错误位置。
'

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。我不知道错误在哪里/

jqjz2hbq

jqjz2hbq1#

变量num1num2是在函数cauculator的作用域中定义的,但是您正在从全局作用域访问它们,而全局作用域中没有定义它们。您的代码还存在一些其他问题。以下是您的代码的编辑版本:

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

如果需要帮助理解它,请随时询问。

k5hmc34c

k5hmc34c2#

你的代码有几个bug。下面是我认为你正在尝试实现的代码:

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

相关问题