python 全局_全局关键字,带Python示例

python 全局

Python全局关键字 (Python global keyword)

global is a keyword (case-sensitive) in python, it is used to declare a global variable inside a function (from a non-global scope).

global是python中的一个关键字(区分大小写),用于在函数内部声明一个全局变量(来自非全局范围)。

As we know that variables are accessible within the same scope in which they are declared but a global variable can be accessed within a program anywhere. In python, we can define a global variable inside a function or in a non-global using by using global keyword.

众所周知,在声明变量的相同范围内可以访问变量,但是可以在程序中的任何位置访问全局变量 。 在python中,我们可以通过使用global关键字定义函数内部或非全局变量中的全局变量。

Syntax of global keyword

全局关键字的语法

    global variable_name

Note: Before accessing the global variable outside of the function, function in which global variable is declared must be called.

注意:在访问函数外部的全局变量之前,必须先调用声明了全局变量的函数。

Example:

例:

    # function
    def myfunc():
        # global variable
        global a
        # assigning the value to a
        a = 10

    # main code
    # function call 
    myfunc()
    print("outside the function a: ", a)
    
    Output:
    outside the function a:  10 

最终关键字的Python示例 (Python examples of finally keyword)

Example 1: Declare a global variable inside a function, assign the value after the declaration, and print the value inside and outside of the function.

示例1:在函数内部声明一个全局变量,在声明之后分配值,并在函数内部和外部打印该值。

# python code to demonstrate example of 
# gloabl keyword 

# function
def myfunc():
    # global variable
    global a
    # assigning the value to a
    a = 10
    # printing the value
    print("inside myfunc() a: ", a)

# main code
# function call 
myfunc()
print("outside the function a: ", a)

Output

输出量

inside myfunc() a:  10
outside the function a:  10


翻译自: https://www.includehelp.com/python/global-keyword-with-example.aspx

python 全局

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值