1.全局变量global
def function():
global x
print('x is', x)
x = 2
print('Changed local x is', x)
x = 50
function()
print('Value of x is', x)
输出:
root@0f0a1d129745:~/ymy# python py.py
x is 50
Changed local x is 2
Value of x is 2
root@0f0a1d129745:~/ymy#
2.DocString文档字符串
def printMax(x,y):
''' Print the maximum of the tow numbers.
The two values must be integers.'''
if x > y:
print(x,'is the maximum')
else:
print(y,'is the maximum')
printMax(3,4)
print(printMax.__doc__)
输出:
root@0f0a1d129745:~/ymy# python py.py
4 is the maximum
Print the maximum of the tow numbers.
The two values must be integers.
root@0f0a1d129745:~/ymy#
3.sys模块
import sys
for i in sys.argv:
print(i)
print('\n The pythonPath is', sys.path, '\n')
输出:
root@0f0a1d129745:~/ymy# python py.py I love you
py.py
I
love
you
The pythonPath is ['/root/ymy', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/root/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
4.__name__
if __name__ == "__main__":
print('Hello')
else:
print('World')
输出:
root@0f0a1d129745:~/ymy# python py.py
Hello
root@0f0a1d129745:~/ymy# python
>>> import py
World
5.创建模块
# filename:py.py
def myMoudle():
print('Hello')
version = '0.1'
# filename:py_demo.py
import py
py.myMoudle()
print('Version',py.version)
输出:
root@0f0a1d129745:~/ymy# python py_demo.py
Hello
Version 0.1
root@0f0a1d129745:~/ymy#
6.dir( ) 函数
:列出模块定义的标识符(包括函数、类和变量)