python函数详细内容

1.函数定义  def 函数名()

函数调用  函数名()

2.函数传参

##向louise say hello
def greet_user(username):
    # print(username,"hello")
    print('hello,'+username.title()) #hello,Louise
greet_user("louise")
例子:编写一个名为display_message()函数,将打印一个句子指出在本章学的是什么。调用函数确认显示的消息正确无误。
def display_message(learning):
    print('今天学了'+learning+"!")
display_message("python")  #今天学了python!
传递实参:函数调用时可包含多个实参,向函数传递参数的方式很多,可使用位置实参(实参形参顺序相同),可使用关键字实参(每个实参由变量名和值组成),还可使用列表和字典
#位置实参:
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('cat','mimi')
#关键字实参是传递给函数的名称值对,无需考虑实参的顺序
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='dog',pet_name='doggy')
#默认值。比如在调用宠物的函数时发现大部分时小狗,可以使用默认值
def describe_pet(pet_name,animal_type='dog'):  ##默认值必须放在后面,因为只调用了pet_name,位置参数
    print("\nI have a" + animal_type + ".")
    print("My" + animal_type + "'s name is" + pet_name.title() + ".")
describe_pet(pet_name='lizi')

3.函数返回值

def get_formatted_name(first_name,last_name):
    full_name=first_name+' '+last_name
    return full_name.title()
musician=get_formatted_name('nini','max')
print(musician)  #Nini Max
##让实参变为可选的
def get_formatted_name(first_name,last_name,middle_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('max','kendy','tony')
print(musician)   #Max Tony Kendy
musician=get_formatted_name('max','tommy')
print(musician)   #Max Tommy
##返回字典
def build_person(first_name,last_name):
    person={'first' : first_name, 'last' : last_name}
    return person
musician=build_person('anna','sweety')
print(musician)  #{'first': 'anna', 'last': 'sweety'}

def build_person(first_name,last_name):
    person={'first' : first_name, 'last' : last_name}
    print(person)
build_person('anna','sweety') #{'first': 'anna', 'last': 'sweety'}
a=build_person('anna','sweety')
print(a)  #None

4.禁止函数修改列表

5.将函数存储在模块中

#创建函数模块,模块是扩展名为.py的文件。
import pizzy
pizzy.make_pizza(16,'potato')
#使用import导入整个模块
def make_pizza(size,*toppings):
    print("Making a"+str(size)+"-inch pizza with the following toppings:")
    for topping in toppings:
        print(topping)
#导入模块中的函数
from pizzy import make_pizza
make_pizza(18,'cheese') #Making a18-inch pizza with the following toppings:
cheese

    #使用as给函数和模块命别名

     #导入模块中所有的函数

from pizzy import *

 6.lamada函数

get_last_name=lambda person: person.last_name
sorted(list_of_people,key=get_last_name)

 



posted @ 2021-01-27 09:48  小仙女学Linux  阅读(122)  评论(0)    收藏  举报