Python函式中的變數和函式返回值
阿新 • • 發佈:2018-11-28
1.函式的變數
區域性變數和全域性變數:
Python中的任何變數都有特定的作用域
在函式中定義的變數一般只能在該函式內部使用,這些只能在程式的特定部分使用的變數我們稱之為區域性變數
在一個檔案頂部定義的變數可以供檔案中的任何函式呼叫,這些可以為整個程式所使用的變數稱為全域性變數。
def fun():
x=100
print x
fun()
x = 100
def fun():
global x //宣告
x +=1
print x
fun()
print x
外部變數被改:
x = 100 def fun(): global x //宣告 x +=1 print x fun() print x
內部變數外部也可用:
x = 100 def fun(): global x x +=1 global y y = 1 print x fun() print x print y x = 100 def fun(): x = 1 y = 1 print locals() fun() print locals() {'y': 1, 'x': 1} 統計程式中的變數,返回的是個字典 {'__builtins__': <module '__builtin__' (built-in)>, '__file__': 'D:/PycharmProjects/untitled/python/2018.01.03/bianliang.py', '__package__': None, 'x': 100, 'fun': <function fun at 0x02716830>, '__name__': '__main__', '__doc__': None}
2. 函式的返回值
函式返回值:
函式被呼叫後會返回一個指定的值
函式呼叫後預設返回None
return返回值
返回值可騍任意型別
return執行後,函式終止
return與print區別
def fun(): print 'hello world' return 'ok' print 123 print fun() hello world 123 None #/usr/bin/env python # -*- coding:utf-8 -*- # 2018/11/27 21:06 # FengXiaoqing #printPID.py import sys import os def isNum(s): for i in s: if i not in '0123456789': return False return True for i in os.listdir("/proc"): if isNum(i): print i 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
或:
#/usr/bin/env python
# -*- coding:utf-8 -*-
# 2018/11/27 21:06
# FengXiaoqing
# :printPID.py
import sys
import os
def isNum(s):
if s.isdigit():
return True
else:
return False
for i in os.listdir("/proc"):
if isNum(i):
print i