如何从python函数返回

时间:2018-03-10 22:01:37

标签: python python-3.x

这是我的第一个编程实践。我有一个像这样的python函数:

sum = 0
def summation(a,b):
    sum = a+b
    return sum

当我将函数称为

summation(3,4)

它不返回任何东西。为什么呢?

2 个答案:

答案 0 :(得分:1)

def summation(a,b):
    sum = a+b
    return sum


sum1 = summation(3,4)
print(sum1)
>> 7


sum2 = summation(10,10)
print(sum2)
>> 20

答案 1 :(得分:0)

sum = 10               # this is a variable called sum 
print(id(sum))         # prints a unique ID for the sum object

def summation(a,b): # this is a function with its own scope 
    sum = a+b          # this is a different variable also called sum
    print(id(sum))     # prints unique ID for the inner sum object
    return sum

sum = summation(1,3)  # now your 1st sum object is overwritten and holds the result of 3+4

print(sum)

输出:

139971258264288 # unique id of the 1st sum variable
139971258264096 # thats the id of the other sum variable inside    def summation(a,b): ...
4   # and thats the result of the addition stored into the 1st sum variable

在这里阅读有关范围的更多信息:Scope or resolution-of-names它是早期的pyhon初学者错误之一。当你在这里时,也阅读并遵循:How to debug small programs (#2)