python局部变量函数,Python - 如何使一个局部变量(在一个函数内)全局

I'm using functions so that my program won't be a mess but I don't know how to make a local variable into global.

解决方案

Here are two methods to achieve the same thing:

Using parameters and return (recommended)

def other_function(parameter):

return parameter + 5

def main_function():

x = 10

print x

x = other_function(x)

print x

When you run main_function, you'll get the following output

>>> 10

>>> 15

Using globals (never do this)

x = 0 # The initial value of x, with global scope

def other_function():

global x

x = x + 5

def main_function():

print x # Just printing - no need to declare global yet

global x # So we can change the global x

x = 10

print x

other_function()

print x

Now you will get:

>>> 0 # Initial global value

>>> 10 # Now we've set it to 10 in `main_function()`

>>> 15 # Now we've added 5 in `other_function()`

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值