Python错误:变量undefined

时间:2016-10-07 20:41:19

标签: python list

我收到此错误代码:

Traceback (most recent call last):
File "C:/Users/PC/AppData/Local/Programs/Python/Python35-32/numbersum.py",
line 21, in <module> print(largest)
NameError: name 'largest' is not defined

这是我的代码:

def main(Numbers):
    smallest = Numbers[0]
    for i in range(0,len(Numbers ),1):
        if (Numbers[i] < smallest):
            smallest = Numbers[i]
            return(smallest)

def main1(Numbers):
largest=Numbers[0]
for large in Numbers:
    if large > largest:
        largest=large
return(largest)



Numbers= [3,5,3,6,3,7,5,8,1]

main(Numbers)
main1(Numbers)


final_ans = largest - smallest 
print(final_ans)

请帮帮我

2 个答案:

答案 0 :(得分:1)

def main(Numbers):
    smallest = Numbers[0]
    for i in range(0,len(Numbers ),1):
        if (Numbers[i] < smallest):
            smallest = Numbers[i]
    return(smallest)  # error 1: correct indentation

def main1(Numbers):
    largest=Numbers[0]
    for large in Numbers:
        if large > largest:
            largest=large
    return(largest)

Numbers= [3,5,3,6,3,7,5,8,1]

smallest = main(Numbers)  # error 2: capture returned values from function
largest = main1(Numbers)


final_ans = largest - smallest 
print(final_ans)

答案 1 :(得分:1)

最大和最小只存在于函数的上下文中。

smallest = main(Numbers)
largest = main1(Numbers)

如果您更改代码,则可以访问最大和最小的