1. 程式人生 > >學習Pytbon第九天,函式1 過程和引數

學習Pytbon第九天,函式1 過程和引數

函式
def func1():定義函式
'''testing1'''#函式的說明
print("in the func1")#定義過程
return 0 #得到函式的執行結果。還是程式的結束
過程就是沒有返回值的'函式'

def func2():
'''testing2'''
print('in the func2')
x=func1()
y=func2()

print('from func1 return is %s'%x)
print('from func2 return is %s'%y)

import time
def logger():
time_format='%Y-%m-%d %X'# 定義時間格式年 月 日 時秒
time_current=time.strftime(time_format)#引用上面時間格式
with open('a.txt','a+') as f:#開啟一個檔案,以二進位制追加的方式獲取檔案描述符f
f.write('%s end action\n' %time_current) #給檔案裡寫一段字串

def test1():
print('in the test1')

logger()

def test2():
print('in the test2')

logger()

def test3():
print('in the test3')

logger()
test1()
test2()
test3()

'''函式的好處1、重複利用,減少重複程式碼
2、保持一致性
3、可擴充套件性'''

# def test1():
print('in the test1')

def test2():
print('in the test2')
return 0 #return 0返回值得意義要根據返回值的結果做出不同的操作
def test4():
print('in the test4')
return 1
def test3():
print('in the test3')
return 1,'hello',['電腦','印表機'],{'天氣':'晴天'}#可以返回任何東西
def test5():
print('in the test5')
return test2

x=test1()
y=test2()
z=test3()
o=test4()
p=test5()
print(x)#返回的是none
print(y)#返回的是0
print(z)#返回的是元祖
print(o)#返回的是1
print(p)#返回的是test2函式的記憶體地址

def test(x,y):#x,y是實參
print(x)
print(y)
test(1,7)# 位置呼叫
# =test(x=1,y=7)#與實參對應1、2是形參 定義兩個值1傳給x,2傳給y


#預設引數
def test(x,y=1)
print(x)
print(y)
test(1,3)#預設引數特點:呼叫函式時,預設引數非必須傳遞
#用途1 預設安裝至
# 2、連線資料庫預設埠號

 

#引數組
def test(*args):#*args接受N個位置引數,把他轉換成元祖的形式
print(args)
test(1,2,3,4,5,6)
test(*[1,2,4,6,8,])#args=tuple([1,2,4,6,8])

def test1(x,*args):
print(x)
print(args)

test1(1,2,3,4,5,6,7)

#**kwargs:接收關鍵字引數,把N個關鍵字引數,轉換成字典的方式
def test2(**kwargs):
print(kwargs)
test2(name='dream',age=18,)
test2(**{'name':'dream','age':18})

def test2(name,age,**kwargs):#引數組一定要放在**kwargs之前
print(name)
print(age)
print(kwargs)
test2(name='dream',age=18,)
test2(**{'name':'dream','age':18})


def test4(name,age=18,**kwargs):#引數組一定要放在**kwargs之前
print(name)
print(age)
print(kwargs)
test4('dream',33,hobby='tesla',gender='m')

#作用域,字串,數字不能區域性該全域性

school='oldboy edu.'#變數用於全域性
def change_name(name):
#global school #複雜程式不能使用
school='Mage.linux'#
print('before change',name,school)
name='Dream zhao'#變數僅用於這個函式
age=28
print("after change",name,school)
print('school',school)
name="alex"
change_name(name)
print(name,school)


name=['Tom','Jack','Rain']#列表、字典、集合變數用於全域性
def change_name():
name[0]='Jim'#列表、字典、集合可以在區域性改全域性
name.append("dream")#列表、字典、集合可以追加
print('inside func',name)

change_name()
print(name)