如何在Python中调用函数内部的变量到外部?

问题描述 投票:0回答:1

我是Python新手,我面临着一个看似很容易解决的问题,但我已经找不到答案一天了。有人可以给我一些建议吗?

这是我的代码:

import sys
x=0
y=0
z=0
def Total(a,b,c):
  a=1
  b=2
  c=a+b
  return c
Total(x,y,z)
print(z)

我最初预期结果为 3,但不幸的是,结果仍然是 0。您能否为我提供解决此问题的解决方案?谢谢您的协助。

python python-3.x function global-variables local-variables
1个回答
0
投票

需要将Total的返回值赋给z。现在您没有对 Total(x,y,z) 的返回值执行任何操作。

x=0
y=0
z=0

def Total(a,b,c):
    a=1
    b=2
    c=a+b
    return c

Total(x,y,z) # Total returns 3, but the value is not assigned to anything
print(z) # Z is still 0

您需要的是:

x=0
y=0
z=0

def Total(a,b,c):
    a=1
    b=2
    c=a+b
    return c

z = Total(x,y,z) # Assign the returned value of Total (which is 3) to z
print(z) # Print z (which is 3) out
© www.soinside.com 2019 - 2024. All rights reserved.