# ~ 函數(shù)?
使用關(guān)鍵字 def? 可以有返回值 直接用return 返回
def print_hello(name):
????print('hello '+name)
print_hello('python')
def sum (x,y,z):
? ? return x+y+z
# ~python 中的參數(shù)和其他語言有些許不同
# ~ 位置實(shí)參
sum(1,2,3)
# ~ 關(guān)鍵字實(shí)參?
sum(x= 1,y=2,z=3) 順序可以調(diào)換
sum(2,y=2,z=3)
# ~ 任意數(shù)量實(shí)參
def sum_2(x,z,y=4):
????print(x+y+z)
sum_2(2,3)
參數(shù)y 存在默認(rèn)值的時(shí)候,可以不傳入,如果調(diào)用的時(shí)候傳入,將使用傳入的新值
在參數(shù)前+* 表示可變參數(shù)刀森,可傳入0到多個(gè)參數(shù)
def sum_4(*nums):
????result = 0
????for n in nums:
????????result +=n
????return result
print(sum_4(2,3))
print(sum_4(3,4,3))
print(sum_4(32,222,33,333))
** 表示傳入可變數(shù)量的鍵值對(duì)
def create_user(name,age,**params):
????user ={}
????user['name']= name
????user['age']= age
????for key,value in params.items():
????????user[key]=value
????return user
user1 = create_user('sunny','15',size='big',color='red')
print(user1)
print(create_user('justin','10',size='small',color='black',weight='100'))
# ~ 返回值
def sum_3(x,y,z):
????result = x*y*z
????return result
r = sum_3(1,2,3)
print(r)
# ~ 如果列表names作為參數(shù)
# ~ names 改變?cè)斜?/b>
# ~ names[:] 不改變?cè)斜?/b>
# ~? 模塊
# ~ 導(dǎo)入 import 模塊名? 導(dǎo)入整個(gè)模塊
# ~ 調(diào)用 模塊名.函數(shù)名
module1.py
def foo():
? ? print('窗前明月光')
module2.py
def foo():
? ? print("地上鞋兩雙")
test.py
import?module1
import?module2
module1.foo()
module2.foo()
# ~ 設(shè)置別名 as
test.py
import?module1 as m1
import?module2 as m2
m1.foo()
m2.foo()
# ~ from 模塊名 import 函數(shù)名 導(dǎo)入一個(gè)函數(shù)
# ~ 調(diào)用 直接調(diào)函數(shù)名即可
test.py
from?module1 import?foo
foo()
# ~ from 模塊名 import * 導(dǎo)入整個(gè)模塊
# ~ 調(diào)用 直接調(diào)函數(shù)名即可
test.py
from?module1 import *
foo()