標籤:coding port 內部使用 one tin pid cts file auth
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 -*-
# @time :2018/1/2 21:06
# @Author :FengXiaoqing
# @file :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 -*-
# @time :2018/1/2 21:06
# @Author :FengXiaoqing
# @file :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
習題
1. 設計一個程式,從終端接收10個數字,並使用自己編寫的排序函數,對10個數字排序後輸出.
2. 設計一個函數,接收一個英文單詞,從檔案中查詢該單詞的漢語意思並返回.
Python函數中的變數和函數傳回值