2018-11-27

2018-11-27  本文已影响0人  Karl_2c80

函数的变量

  1. 局部变量:函数中定义的变量
  2. 全局变量:代码顶部定义的变量
In [1]: x = "global"

In [2]: def fun():
   ...:     x = 100
   ...:     print x
   ...:

In [3]: fun()
100

In [4]: x
Out[4]: 'global'
# 在函数内使用关键字 global 将变量声明为全局变量,以便在函数外继续使用

In [5]: x = 30

In [6]: def fun():
   ...:     global x
   ...:     x += 1
   ...:     print x
   ...:

In [7]: fun()
31

In [8]: x
Out[8]: 31
# locals(): 已字典形式返回当前位置的全部局部变量

In [9]: x = 80

In [10]: def fun():
    ...:     x = 1
    ...:     y = 2
    ...:     print locals()
    ...:

In [11]: fun()
{'y': 2, 'x': 1}

函数的返回值

#!/usr/bin/python
# -*- coding:utf-8 -*-

## 打印/proc目录下的所有pid

import sys
import os


def isNum(s):
    if s.isdigit():
        return True
    return False

for i in os.listdir('/proc'):
    if isNum(i):
        print i
上一篇下一篇

猜你喜欢

热点阅读