python函数解释
生活随笔
收集整理的這篇文章主要介紹了
python函数解释
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
實現某個功能的一些代碼
提高代碼的復用性
函數必須被調用才會執行
函數里面定義的變量都叫局部變量,只要一出了函數就不能用了
函數里面如果調用時需要拿到結果但是最后沒寫return(不必須寫,如讀取文件時就需要),則返回None
函數得先定義后使用,使用時注意先后順序
1、把函數處理的結果返回
2、結束函數,函數里面遇到return,函數立即結束
詳情:http://www.runoob.com/python3/python3-function.html # 1. 定義一個可輸出hello world的函數 def hello(): # 定義函數用defprint('hello world')#調用函數1 hello() #調用函數,輸出hello world# 2. 定義一個將content寫入file的函數 def write_file(file_name,content): #入參,不必須寫,根據需求# 形參:形式參數with open(file_name,'a+',encoding="utf-8") as fw:fw.write(content)# print(file_name,content) #以上代碼為函數體#調用函數2,將'123\n'寫入'a.txt'里 write_file('a.txt','123\n') #實參:實際參數 # write_file('b.txt','456') # write_file('c.txt','789')# 3. 定義一個可讀取并輸出file里的content的函數 def read_file(file_name):with open(file_name, 'a+', encoding="utf-8") as fw:fw.seek(0)content = fw.read()return content#調用函數3 res = read_file('a.txt') print(res) #輸出a.txt里面的內容
?
#return返回的結果可用,print不行 def func(a,b):res=a+bprint(res)#只能看結果,但不能用def func2(a,b):res=a+breturn res #可以用def get_user():s='abc,123'username,password=s.split(',')return username,password #可被其他函數調用,可return多個值用逗號分開,可用一個變量來接收 res=get_user() print(res)# 可用一個變量來接收 ('abc', '123')def login():for i in range(3):username,password=get_user()user=input('username:')pwd=input('password:')if username==user and password==pwd:print("登錄成功")returnelse:print("賬號密碼錯誤")?
轉載于:https://www.cnblogs.com/denise1108/p/10021933.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的python函数解释的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 给定2个字符串,如何计算变化(插入、删除
- 下一篇: 考公务员的本科学历可以考吗