簡體   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