简体   繁体   English

函数没有运行

[英]Functions aren't running

My functions in Python aren't returning values that I expect them to.我在 Python 中的函数没有返回我期望的值。 Here is a MWE:这是一个 MWE:

a = 6
b = 18
c = 0
def random_function(c):
    c = b/a
    return c

random_function(c)
print(c)

I expect this function to print 3, but instead it prints 0. I have just updated from 2.7 to 3.6 and this would have worked in 2.7 - what am I doing wrong?我希望这个函数打印 3,但它打印 0。我刚刚从 2.7 更新到 3.6,这在 2.7 中可以工作 - 我做错了什么?

Need to store returned value from method.需要存储方法的返回值。

a = 6
b = 18
c = 0
def random_function(c):
    c = b/a
    return c

c= random_function(c)
print(c)

As @Dharmesh said, you need to store the value of c when it comes out of random_function() .正如@Dharmesh 所说,当crandom_function()出来时,您需要存储它的值。

ie c = random_function(c)c = random_function(c)

The Reason:原因:

Scope is everything.范围就是一切。 When you change the value of c from within the function, it only affects the value of c within the scope of that function and doesn't change its value in the global context.当您从函数内部更改c的值时,它只会影响该函数范围内的c值,而不会更改其在全局上下文中的值。

In order for the value you assigned to c from within the function to be preserved, you need to assign c the value returned by the function.为了让您分配到值c从被保存在函数中,你需要分配c函数返回值。

you are printing c value which was assigned globally.您正在打印全局分配的 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

to print as you expected, you need to change your function call like below要按预期打印,您需要更改函数调用,如下所示

print (random_function(c))

or或者

c = random_function(c)  # this will re assign global value of 'c' with function return value 
print(c)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM