我在Python中的函数没有返回我期望它们的值。这是一个MWE:
a = 6
b = 18
c = 0
def random_function(c):
c = b/a
return c
random_function(c)
print(c)
我希望这个功能可以打印3,但是它会打印0.我刚刚从2.7更新到3.6,这在2.7中有用 - 我做错了什么?
答案 0 :(得分:3)
需要存储方法返回的值。
a = 6
b = 18
c = 0
def random_function(c):
c = b/a
return c
c= random_function(c)
print(c)
答案 1 :(得分:2)
正如@Dharmesh所说,当c
出现时,您需要存储random_function()
的值。
即 c = random_function(c)
原因:
范围就是一切。当您在函数中更改c
的值时,它仅影响该函数范围内的c
的值,并且不会在全局上下文中更改其值。
为了保留您在函数中分配给c
的值,您需要为函数返回的值指定c
。
答案 2 :(得分:0)
您正在打印全局分配的c值。
a = 6
b = 18
c = 0
def random_function(c):
c = b/a
return c # -- this variable scope is local
random_function(c)
print(c) #-- prints Global variable
按照您的预期打印,您需要更改下面的函数调用
print (random_function(c))
或
c = random_function(c) # this will re assign global value of 'c' with function return value
print(c)