Python学习之路day03——010函数(类似Java中的方法)
一、函數
函數是一個表示一定功能的代碼塊,可以在程序中進行應用,書寫的方式:“函數名.()”。
1、定義一個函數
# -*- coding: gb2312 -*-
#隨便定義一個hansh8u
def system_out(): ? ?
? ? ? print("hello world !") ?
system_out()
?結果:hello world !
#加粗部分即是函數體
2、函數的形參
2.1、定義一個帶形參的函數
def greet_user(username):
"""顯示簡單的問候語"""
? ? ? ?print("Hello, " + username.title() + "!")
greet_user('jesse')
結果:Hello, Jesse!
注意:jesse是個實參,username是個形參。
2.2、多個形參的情況,對應多個實參
def describe_pet(animal_type, pet_name):
"""顯示寵物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
?
describe_pet('hamster', 'harry')
describe_pet('harry', 'hamster')?
結果:I have a hamster.
? ? ? ? ? My hamster's name is Harry.
? ?I have a harry.
? ?My hamster's name is hamster.?
注意:此情況下,必須注意形參的填入順序,否則輸出的內容會出現與預期不一樣的情況
2.3、關鍵字實參調用方法
def describe_pet(animal_type, pet_name):
"""顯示寵物的信息"""
? ? ?print("\nI have a " + animal_type + ".")
? ? ?print("My " + animal_type + "'s name is " + pet_name.title() + ".")?
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster')
結果:I have a hamster.
? ? ? ? ? My hamster's name is Harry.?
??I have a hamster.
? My hamster's name is Harry.?
注意:以上兩種情況,函數中實參的調用順序不一樣,但并未影響輸出結果,所以關鍵實參的順序是不會影響結果的輸出的。
2.4、形參的默認值設置
編寫函數時,可給每個形參指定默認值 。
def describe_pet(pet_name, animal_type='dog'):
"""顯示寵物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')
I have a dog.
My dog's name is Willie.
注:若不想用設置的默認參數,可以用關鍵實參方式和位置實參方式兩種方法,申明實參。
3、返回值函數
函數可以輸出一定結果,也可以通過數據處理之后,返回一個值或一組值到代碼中去,返回的值,叫做返回值,調用關鍵字return
3.1、返回簡單值
def get_formatted_name(first_name, last_name):
? ? ?"""返回整潔的姓名"""
? ? full_name = first_name + ' ' + last_name
? ? return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
3.2、可選參數返回值函數
def get_formatted_name(first_name, last_name, middle_name=''):
? ? ? ? """返回整潔的姓名"""
? ? ? if middle_name:
? ? ? ? ? ? full_name = first_name + ' ' + middle_name + ' ' + last_name
? ? ?else:
? ? ? ? ? ?full_name = first_name + ' ' + last_name
? ? return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
3.3返回字典
返回值即是一個字典。
4、傳遞列表
def print_models(unprinted_designs, completed_models):
? ? ?"""
? ? ?模擬打印每個設計,直到沒有未打印的設計為止
? ? ?打印每個設計后,都將其移到列表completed_models中
? ? ?"""
? ? ?while unprinted_designs:
? ? ?current_design = unprinted_designs.pop()
? ? ? # 模擬根據設計制作3D打印模型的過程
? ? ?print("Printing model: " + current_design)
? ? ?completed_models.append(current_design)
def show_completed_models(completed_models):
? ? ?"""顯示打印好的所有模型"""
? ? ?print("\nThe following models have been printed:")
? ? for completed_model in completed_models:
? ? print(completed_model)
? ? unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
? ? completed_models = []
?print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
結果:
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
?5、禁止函數修改列表的表示方法
?只需要將列表的表示用切片來表示即可,因為這樣切片是作為列表的一個副本,在函數操作過程中,實際修改的是副本
不會影響到列表本身的值。切片的表示方法:unprinted_designs[:]?因此上面的print_models(unprinted_designs, completed_models)中,
如果不想修改unprinted_designs列表,可以寫成unprinted_designs[:],就可以避免修改列表的問題了。
?6、傳遞任意數量的實參
6.1、基本使用方法
有時候,你預先不知道函數需要接受多少個實參 ,在python中允許函數從調用語句中手機任意數量的實參。
下面的函數只有一個形參*toppings,但不管調用語句提供了多少實參,這個形參都將它們統統收入囊中:
def make_pizza(*toppings):
"""打印顧客點的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
注:*toppings讓python創建一個空的名字叫做toppings的元組
6.2、接受任意實參的形參必須放置到函數括號的最后
def make_pizza(size, *toppings):
"""概述要制作的比薩"""
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
注:接納任意數量實參的形參必須放在,函數括號里面的最后位置上
6.3、使用任意數量的“鍵—值”對實參
def build_profile(first, last, **user_info):
? ? ? ?"""創建一個字典,其中包含我們知道的有關用戶的一切"""
? ? ? ?profile = {}
? ? ? ?profile['first_name'] = first
? ? ? ?profile['last_name'] = last
? ? ? for key, value in user_info.items():
? ? ? ?profile[key] = value? ? ? ?
? ? ? return profile? ? ?
?user_profile = build_profile('albert', 'einstein',? ? ?
?location='princeton',field='physics')
print(user_profile)
注:形參**user_info中的兩個*讓Python創建一個名為user_info的空字典
7、函數的模塊化儲存
7.1、導入函數的整個模塊
要讓函數是可導入的,得先創建模塊。 模塊是擴展名為.py的文件,包含要導入到程序中的代碼。下面來創建一個包含函數make_pizza()的模塊:
首先在編程軟件里面創建pizza.py的模塊(或者可以稱為文件)?
然后在pizza.py中寫入如下函數:
def make_pizza(size, *toppings):
"""概述要制作的比薩"""
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
接下來我們創建一個make_pizzas.py的文件,在里面調用兩次make_pizza()函數:
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')?
解釋:當python讀取代碼的時候,讀取到import pizza的時候,python就會打開pizza.py文件,并且隱形的將pizza.py中的
所有代碼都復制到當前make_pizzas程序中來,當我們要調用pizza.py中的某個函數時,就可以用pizza.make_pizza(實參1,實參2)的形式調用對應函數。
7.2、導入制定的函數
當我們導入整個模塊(或者叫做程序文件)的時候,可以用“
轉載于:https://www.cnblogs.com/jokerwang/p/9259525.html
總結
以上是生活随笔為你收集整理的Python学习之路day03——010函数(类似Java中的方法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JS实现全选、反选、不选
- 下一篇: Python爬虫的开发