1. 程式人生 > >python-2函數

python-2函數

字符 nbsp 3.3 numbers 方式 http 定義 lse job

http://docs.python.org/3/library/functions.html 或者菜鳥中文資料

1-使用函數

abs(-20)#求絕對值
max(1,4,200,3,2) #求最大的值
int(12.34) #轉成int
float("12.34") #轉成float
str(1.23) #轉成字符串
bool(1) #轉成bool類型
bool(‘‘) 

2-自定義函數

def my_abs(x):
    if not isinstance(x, (int, float)):
        return 222
    if x >= 0:
        return x
    
else: return -x

x,y=(111,222); x值是111,y值是222. 函數可直接返回tuple函數

3-函數的參數

  3.1 默認參數, 定義默認參數要牢記一點:默認參數必須指向不變對象!

def sum(x, n=2): 
    return x+n
sum(5)#相當於調用power(5, 2):

def enroll(name, gender, age=6, city=Beijing):
    print(city:, city)
enroll(Adam, M, city=Tianjin) #可以只傳指定參數

3.2 可變參數

def calc(*numbers): #*表示可變
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum
calc(1,2,3) #參數調用

nums=[1,2,3]
calc(*nums) #第二種方式

3.3 關鍵字參數

def person(name, age, **kw):
    print(name:, name, age:, age, other:, kw)
    
extra = {city: Beijing, job: Engineer
} person(Jack, 24, **extra)

3.4命名關鍵字參數

def person(name, age, *args, city=beijing, job):
    print(name, age, args, city, job)
person(xiaofeng,12,city=shenzhin,job=myjob)    
    
extra = {city: Beijing, job: Engineer}
person(xiaofeng,12,**extra)

3.5參數組合

def f1(a, b, c=0, *args, **kw):
    print(a =, a, b =, b, c =, c, args =, args, kw =, kw)
    
args = (1, 2, 3, 4)
kw = {d: 99, x: #}
f1(*args, **kw) #a = 1 b = 2 c = 3 args = (4,) kw = {‘d‘: 99, ‘x‘: ‘#‘}

python-2函數