區域性變數和全域性變數:
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()
統計程式中的變數,返回的是個字典
函式被呼叫後會返回乙個指定的值
函式呼叫後預設返回none
return返回值
返回值可騍任意型別
return執行後,函式終止
return與print區別
def fun():
print 'hello world'
return 'ok'
print 123
print fun()
hello world
123none
#/usr/bin/env python
# -*- coding:utf-8 -*-
# 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
#/usr/bin/python
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 -*-
# 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
python類中的變數和函式
類變數是在類下面直接定義的變數,類變數被類和例項訪問。所有例項在對類變數賦值之前一直共享記憶體,賦值後就各自儲存各自的類變數。成員變數在 init 函式中定義的以self.開頭,可以被例項訪問。區域性變數是在別的函式下定義的可以self.開頭也可以不以此開頭。不能被訪問 普通函式,不能訪問類中的任何...
python的高階函式和函式即變數
1 高階函式 高階函式 定義 把函式作為引數作為另乙個函式的引數 deftest a,b return a b deftest 1 f,c return f c print test 1 test 1,2 5 執行結果 10 2 函式即變數 def foo print in the foo bar ...
python中的偏函式和變數作用域
當乙個函式有大量的引數時,呼叫會變得非常麻煩,我們可以通過偏函式,固定一些引數,簡化函式的呼叫。例如,def addaddminus num1,num2,num3,num4 return num1 num2 num3 num4 print addaddminus 1,2,3,4 執行結果如下,2這個...