局部变量和全局变量:python
- Python中的任何变量都有特定的做用域git
- 在函数中定义的变量通常只能在该函数内部使用,这些只能在程序的特定部分使用的变量咱们称之为局部变量函数
- 在一个文件顶部定义的变量能够供文件中的任何函数调用,这些能够为整个程序所使用的变量称为全局变量spa
局部变量没有global声明时只能在函数内部使用:进程
#! /usr/bin/python作用域
def fun():字符串
x = 1it
print ximport
fun()变量
print x
在函数外在print x 时,提示变量没有定义
在函数外的全局变量能够在函数内print:
#! /usr/bin/python
x = 100
def fun():
x = 1
print x
fun()
print x
#! /usr/bin/python
x = 100
def fun():
print x
fun()
global 全局变量后能够在函数内执行赋值等操做:
#! /usr/bin/python
x = 100
def fun():
global x
x += 1
print x
fun()
print x
global 局部变量后能够在函数外调用:
#! /usr/bin/python
x = 100
def fun():
global x
x += 1
print x
global y
y = 'ab'
fun()
print x
print y + 'cd'
global语句
- global 变量名
强制声明为全局变量
locals()
统计变量,以字典的形式列出,能够在函数内,也能够统计程序的所有变量
#! /usr/bin/python
x = 1
def fun():
y = 2
print locals()
fun()
#! /usr/bin/python
x = 1
def fun():
y = 2
print locals()
fun()
print locals()
函数返回值:
- 函数被调用后会返回一个指定的值
- 函数调用后默认返回None
- return 返回值
- 返回值能够是任意类型
- return执行后,函数终止
- return与print区别
函数默认返回None:
#! /usr/bin/python
def fun():
print "hello world"
print fun()
return 指定返回值:
#! /usr/bin/python
def fun():
print "hello world"
return True
print fun()
练习:
打印/proc中全部的数字进程方法1:
#! /usr/bin/python
import os
import sys
def isNum(x):
for i in x:
if i not in '0123456789':
return False
return True
for i in os.listdir('/proc'):
if isNum(i):
print i
打印/proc中全部的数字进程方法2:
#! /usr/bin/python
import os
import sys
def isNum(x):
if x.isdigit():
return True
return False
for i in os.listdir('/proc'):
if isNum(i):
print i
字符串的isdigit()方法:
isdigit()用来判断字符串是不是数字;
返回bool值;