python(function)

前言

函數

print('hello')
def hello():
    print('hello1')
    print('hello2')
    print('hello3')

hello()

def add():
    num1 = 20
    num2 = 30
    result = num1 + num2
    print('%d + %d = %d' %(num1,num2,result))
add()

def westos():
    print('westos')
    def python():
        print('python')
    python()

westos()

def welcome(a):
    print('hello',a)

welcome('laoli')
welcome('laowang')

參數

參數:形參 實參
形參:位置參數 默認參數 可變參數 關鍵字參數

位置參數

def getInfo(name,age):
    print(name,age)

getInfo('westos',11)
getInfo(11,'westos')
getInfo(age=11,name='westos')

默認參數

def mypow(x,y=2):
    print(x**y)

mypow(4)
mypow(2,3)

可變參數

def mysum(*a):
    sum = 0
    for item in a:
        sum += item
    print(sum)

mysum(1,2,3,4,5)

關鍵字參數

def getInfo(name,age,**kwargs):
    print(name,age)
    print(kwargs)

getInfo('westos',18,gender='female',hobbies=['coding','running'])

返回值

def mypow(x,y=2):
    return x ** y, x + y
    # print(x**y,x+y)
    print('hello python')

a,b = mypow(3)
print(a,b)

變量

局部變量:在函數內部定義的變量,只在函數內部起作用,函數執行結束,變量會自動刪除
全局變量

a = 1
print(‘outside:’,id(a))

def fun():
global a
a = 5
print(‘inside:’,id(a))

fun()
print(a)
print(id(a))

練習

後記

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章