【python】global

#!/usr/bin/python
# Filename: func_global.py

def func():
    global x

    print ‘x is‘, x
    x = 2
    print ‘Changed local x to‘, x

x = 50
func()
print ‘Value of x is‘, x

>>>>
x is 50
Changed global x to 2
Value of x is 2

 它如何工作

global语句被用来声明x是全局的——因此,当我们在函数内把值赋给x的时候,这个变化也反映在我们在主块中使用x的值的时候。

你可以使用同一个global语句指定多个全局变量。例如global x, y, z。

#!/usr/bin/python
# Filename: func_local.py

def func(x):
    print ‘x is‘, x
    x = 2
    print ‘Changed local x to‘, x

x = 50
func(x)
print ‘x is still‘, x

>>>>>
x is 50
Changed local x to 2
x is still 50

在函数中,我们第一次使用x的 值 的时候,Python使用函数声明的形参的值。
接下来,我们把值2赋给x。x是函数的局部变量。所以,当我们在函数内改变x的值的时候,在主块中定义的x不受影响。

时间: 2024-08-02 01:18:16

【python】global的相关文章

【python】urllib2

urllib2.urlopen(url[, data][, timeout]) Open the URL url, which can be either a string or a Request object. data may be a string specifying additional data to send to the server, or None if no such data is needed. Currently HTTP requests are the only

【Python】SyntaxError: Non-ASCII character '\xe8' in file

遇到的第一个问题: SyntaxError: Non-ASCII character '\xe8' in file D:/PyCharmProject/TempConvert.py on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details 原因:注释里面出现了中文,而 Python 支持的 ASCII 码无中文. 解决方法:在头文件中添加如下代码: # -*- coding:

【python】禁止print输出换行的方法

print后用一个逗号结尾就可以禁止输出换行,例子如下 >>> i=0 >>> while i < 3: print i i+=1 0 1 2 禁止输出换行后效果如下: >>> i=0 >>> while i < 3: print i, i+=1 0 1 2 [python]禁止print输出换行的方法,布布扣,bubuko.com

【python】chr与ord函数的使用

ord()是将已知字母转换成其顺序值: chr()是将已知字母的顺序至转换成其对应的字母 >>> ord("a") 97 >>> ord("A") 65 >>> chr(97) 'a' >>> chr(65) 'A' [python]chr与ord函数的使用,布布扣,bubuko.com

【python】ipython与python的区别

[python]ipython与python的区别 (2014-06-05 12:27:40) 转载▼   分类: Python http://mba.shengwushibie.com/itbook/BookChapter.asp?id=8745 http://www.cnblogs.com/yangze/archive/2011/07/11/2103040.html http://matrix.42qu.com/10735149 http://www.cnblogs.com/weishun/

【python】字符遍历

Python为我们提供了很多便捷的方式去遍历一个字符串中的字符.比如,将一个字符串转换为一个字符数组(列表): theList = list(theString) 同时,我们可以方便的通过for语句进行遍历: for c in theString:        do_something_with(c) map函数用法: 第一个参数接收一个函数名,第二个参数接收一个可迭代对象 lt = [1, 2, 3, 4, 5, 6] def add(num): return num + 1 rs = ma

【Python】用Python的“结巴”模块进行分词

之前都是用计算所的分词工具进行分词,效果不错但是比较麻烦,最近开始用Python的"结巴"模块进行分词,感觉非常方便.这里将我写的一些小程序分享给大家,希望对大家有所帮助. 下面这个程序是对一个文本文件里的内容进行分词的程序:test.py #!/usr/bin/python #-*- encoding:utf-8 -*- import jieba #导入jieba模块 def splitSentence(inputFile, outputFile): fin = open(input

【Python】Python获取命令行参数

有时候需要用同一个Python程序在不同的时间来处理不同的文件,此时如果老是要到Python程序中去修改输入.输出文件名,就太麻烦了.而通过Python获取命令行参数就方便多了.下面是我写得一个小程序,希望对大家有所帮助. 比如下面一个程序test.py是通过接受命令行两个参数,并打印出这两个参数. import sys #需导入sys模块 print sys.argv[1], sys.argv[2] #打印出从命令行接受的两个参数 Linux下运行:python test.py Hello P

【Python】定位一组元素、

前几天生病加懒惰 TAT ========================================================================== 1.getAttribute()方法是一个函数.它只有一个参数--你打算查询的属性的名字: 2.http://www.cnblogs.com/fnng/p/3190966.html 注意路径 3. [Python]定位一组元素.,布布扣,bubuko.com