Python小白入门:关于函数的超详解知识点总结(定义、传递参数、返回值、模块等)

一、定义函数

使用def关键字定义函数。

def 函数名():

def great_user(username):
    print(f"{
      
      username.title()},hello!")

great_user("jessi")

在这里插入图片描述

实参和形参

  • 实参(argument):在代码greet_user(‘jesse’) 中,值’jesse’ 是一个实参 ,即调用函数时传递给函数的信息。
  • 形参(parameter):在函数greet_user() 的定义中,变量username 是一个形参 ,即函数完成工作所需的信息。

调用函数时,将要让函数使用的信息放在圆括号内。在greet_user(‘jesse’) 中,将实参’jesse’ 传递给了函数greet_user() ,这个值被赋给了形参username。

二、传递实参

2.1 位置实参

调用函数时,Python必须将函数调用中的每个实参都关联到函数定义中的一个形参。为此,最简单的关联方式是基于实参的顺序。这种关联方式称为位置实参

def describie_pet(animal_type,pet_name):
    print(f"I have a {
      
      animal_type}.")
    print(f"My {
      
      animal_type}'s name is {
      
      pet_name.title()}")

describie_pet('hamster','harry')
describie_pet('dog','willie')

在这里插入图片描述

使用位置实参来调用函数时,实参的顺序必须正确。

2.2 关键字参数

关键字实参是传递给函数的名称值对,此时无需关注顺序。

  • 使用关键字参数时必须要准确指定函数定义中的形参名。
def describie_pet(animal_type,pet_name):
    print(f"I have a {
      
      animal_type}.")
    print(f"My {
      
      animal_type}'s name is {
      
      pet_name.title()}")

describie_pet(animal_type='hamster',pet_name='harry')
describie_pet(pet_name='willie',animal_type='dog')

在这里插入图片描述

2.3 默认值

编写函数时,可给每个形参指定默认值。

  • 在调用函数中给形参提供了实参时,Python将使用指定的实参值;
  • 否则,将使用形参的默认值。
def describie_pet(animal_type,pet_name='winnie'):
    print(f"I have a {
      
      animal_type}.")
    print(f"My {
      
      animal_type}'s name is {
      
      pet_name.title()}")

describie_pet(animal_type='hamster',pet_name='harry')
describie_pet('dog')

在这里插入图片描述

练习题

在这里插入图片描述

代码

def make_shirt(size,text):
    print(f"The shirt's size is {
      
      size} and the text will be printed on it is {
      
      text.title()}")

def make_shirt_default(size='XL',text = 'I love Python'):
    print(f"The shirt's size is {
      
      size} and the text will be printed on it is {
      
      text.title()}")

    
print('8-3')
make_shirt('M','make everyday counts')
make_shirt(size='L',text='time is money')

print('8-4')
make_shirt_default()
make_shirt_default(size='M')
make_shirt_default(text='I am the best')

输出

在这里插入图片描述

三、返回值

3.1 返回简单值

在定义函数时使用return关键字返回函数结果,在使用函数时使用一个变量接收函数的返回结果。

def get_name(first_name,last_name):
    full_name = f"{
      
      first_name} {
      
      last_name}"
    return full_name.title()

musician = get_name('jimi','ma')
print(musician)

在这里插入图片描述

3.2 可选实参

给形参一个默认的空值,然后再函数中使用条件语句,让当用户使用该形参和不适用该形参时函数都可以使用。

  • 可选值让函数能够处理各种不同的情形,同时确保函数调用尽可能简单。
def get_formatted_name(first_name,last_name,middle_name=""):
    if middle_name:
        full_name = f"{
      
      first_name} {
      
      middle_name} {
      
      last_name}"
    else:
        full_name = f"{
      
      first_name} {
      
      last_name}"
    return full_name.title()

musician = get_formatted_name('jimi','ma')
print(musician)
musician_1 = get_formatted_name('will','hooker','lee')
print(musician_1)

在这里插入图片描述

3.3 返回字典

函数可以返回列表、字典等复杂数据类型。

def build_person(first_name,last_name,age=None):
    person = {
    
    'first_name':first_name,'last_name':last_name}
    if age:
        person['age'] = age
    return person

musician = build_person('jimi','hendrix',27)
print(musician)
  • 代码中age为一个可选的形参,设置值为None,为占位符。

在这里插入图片描述

None值用法none值详解

  • 在条件测试中,None值相当于False
  • None是一个空值,空值是Python里的一个特殊值,用None表示。可以将None赋值给任何变量
  • None是一个特殊的空对象,可以用来占位
  • None不等于空字符串、空列表、0,也不等同于False

3.4 在函数中使用while循环

def get_formatted_name(first_name, last_name):
    full_name = f"{
      
      first_name} {
      
      last_name}"
    return full_name.title()

while True:
    print("\nPlease tell me your name")
    print("(enter 'q' at any time to quit)")

    f_name = input("First name: ")
    if f_name == 'q':
        break
    l_name = input("Last name: ")
    if l_name == 'q':
        break

    format_name = get_formatted_name(f_name,l_name)
    print(f"Hello, {
      
      format_name}!")

在这里插入图片描述

练习题

代码

在这里插入图片描述

def city_country(city,country):
    return f"{
      
      city.title()},{
      
      country.title()}"


def make_album(name,singer,num_songs = None):
    album = {
    
    'name':name,'singer':singer}
    if num_songs:
        album['number of songs'] = num_songs
    return album

print('8-6')
print(city_country('zibo','china'))
print(city_country('florence','italy'))
print(city_country('madrid','spain'))

print('8-7')
print(make_album('love and peace','jack',5))
print(make_album('nature','diane'))

print('8-8')
while True:
    print("Enter the singer and album's name(enter q to exit)")
    singer = input("Enter the singer: ")
    if singer == 'q':
        break
    name = input("Enter the album name: ")
    if name == 'q':
        break
    album = make_album(name,singer)
    print(f"The album's name is {
      
      album['name'].title()} and the singer is {
      
      album['singer'].title()}")

输出

在这里插入图片描述

四、传递列表

将列表作为参数在函数中进行传递。

def greet_users(names):
    for name in names:
        print(f"Hello,{
      
      name.title()}!")

username = ['hannah','will','grace']
greet_users(username)

4.1 在函数中修改列表

在函数中完成列表的修改,并且专门定义一个函数完成列表元素的输出。

def print_models(unprinted_models, completed_models):
    while unprinted_models:
        current_design = unprinted_models.pop()
        print(f"Printing model: {
      
      current_design}")
        completed_models.append(current_design)

def show(completed_models):
    print('The following models have been printed:')
    for completed_model in completed_models:
        print(completed_model)

unprinted_models = ['phone case','robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_models,completed_models)
show(completed_models)

在这里插入图片描述

4.2 禁止函数修改列表

如果不想让函数修改列表中的内容,可以向函数中传递列表的副本,这样做可以只对列表副本进行修改,但是原列表内容不会受影响。

创建列表副本:

如何拷贝列表

  1. 切片法:list1 = list0 [ : ]
  2. 使用copy函数:list1 = list0.copy()
  3. 使用list函数:list1 = list(list0)
def print_models(unprinted_models, completed_models):
    while unprinted_models:
        current_design = unprinted_models.pop()
        print(f"Printing model: {
      
      current_design}")
        completed_models.append(current_design)

def show(completed_models):
    print('The following models have been printed:')
    if completed_models==[]:
        print("This list is empty")
    else:
        for completed_model in completed_models:
            print(completed_model)

unprinted_models = ['phone case','robot pendant','dodecahedron']
completed_models = []
print_models(unprinted_models[:],completed_models)
show(unprinted_models)
show(completed_models)

可以看到由于使用了unprinted_models列表的副本,所以其元素没有被改变。

在这里插入图片描述

练习题

在这里插入图片描述

代码

def show_message(text):
    for t in text:
        print(f"{
      
      t.title()}")

def send_message(text1,text2):
    while text1:
        t = text1.pop()
        print(f"{
      
      t.title()}")
        text2.append(t)

def print_list(list1):
    if list1 == []:
        print("This is an empty list.")
    else:
        for l in list1:
            print(f"{
      
      l.title()}")

print('8-9')
text = ['hello','good morning','goodbye','thank you']
show_message(text)

print('8-10')
text1 = ['hello','good morning','goodbye','thank you']
text2=[]
send_message(text1,text2)
print_list(text1)
print_list(text2)

print('8-11')
text1 = ['hello','good morning','goodbye','thank you']
text2=[]
send_message(text1[:],text2)
print_list(text1)
print_list(text2)

输出

在这里插入图片描述

五、传递任意数量的实参

  • 适用情况:当函数不知道要接收多少个实参值时

形参前面加一个星号*代表让Python创建一个名为该形参的空元组,并将函数收到的所有值都封装进该元组中。

此时可以让函数收集任意数量个实参。

def method(*value)

下面的代码将打印不同类型的披萨,因为不知道有几种披萨需要制作,因此将不同的topping设置为未知量,在调用函数时可以添加未知个数的披萨toppings,这些toppings会被存储在一个元组中。

def make_pizza(*toppings):
    print("\nMaking a pizza with the following toppings:")
    for topping in toppings:
        print(f"{
      
      topping.title()}")

make_pizza('pepperroni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

在这里插入图片描述

5.1 位置实参和任意数量实参的结合使用

  1. 如果要让函数接受不同类型的实参,需要将接纳任意数量实参的形参放在最后
  2. Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参元组中

存储格式如下所示:

在这里插入图片描述

def make_pizza(size,*toppings):
    print(f"\nMaking a {
      
      size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f"{
      
      topping.title()}")

make_pizza(12,'pepperroni')
make_pizza(16,'mushrooms', 'green peppers', 'extra cheese')

在这里插入图片描述

5.2 使用任意数量的关键字实参

让函数接收任意键值对:使用双星号**形参名代表让Python创建一个名为该形参名的空字典,并将收到的所有键值对放进该字典中。

def method ( arg1, arg2, **info )

在这里插入图片描述

Python将为函数创建一个名为info的字典,并将所有的键值对都存储进去。

def build_profile(first_name,last_name,**user_info):
    user_info['first_name'] = first_name
    user_info['last_name'] = last_name
    return  user_info
user_profile = build_profile('amy','ma',city = 'zibo',age = 28,major='computer and science')
print(user_profile)

对上述代码进行debug,可以看到创建的字典中包含了5个键值对,可以看到字典中的键值对顺序是先定义函数中自己输入的键值对,然后才是函数中定义的形参。

在这里插入图片描述

输出如下所示。

在这里插入图片描述

练习题

在这里插入图片描述

代码

def make_pizza(*toppings):
    for topping in toppings:
        print(f"The pizza is made of {
      
      topping.title()}")

def build_profile(f_name,l_name,**info):
    info['first name'] = f_name
    info['last name'] = l_name
    return info

def make_car(maker,type,**info):
    info['maker'] = maker
    info['type'] = y=type
    return info


print('8-12')
make_pizza('1')
make_pizza('2','3')
make_pizza('34')

print('8-13')
my_profile = build_profile('weiyi','ma',city = 'zibo',major = 'cs', university = 'SHU')
for k,v in my_profile.items():
    print(f"My {
      
      k.title()} is {
      
      v.title()}")

print('8-14')
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)

输出

在这里插入图片描述

六、将函数存储在模块中

可以将函数存储在称为模块的独立文件中,再将模块导入(import)到主程序中。

  • import 语句允许在当前运行的程序文件中使用模块中的代码。

6.1 导入整个模块文件

语法: import 模块名

1. 创建模块:pizza.py为一个包含make_pizza函数的文件。

在这里插入图片描述

2. 调用该模块:在main.py中调用make_pizza模块。

语法:module_name.function_name()

  • Python读取这个文件时,使用import pizza 让Python打开文件pizza.py。
  • 要调用被导入模块中的函数,使用导入模块的名称pizza.函数名make_pizza() 的形式进行调用

在这里插入图片描述

6.2 导入模块中的特定函数

语法: from module_name import function_name

用逗号分隔函数名:从模块中导入任意数量的函数:

语法:from module_name import function_0, function_1, function_2

from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

6.3 使用as给函数指定别名

函数名太长时可以使用as关键字为其起一个别名。

语法:from module_name import function_name as fn

from pizza import make_pizza as mp

mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')

6.4 使用as给模块指定别名

语法:import module_name as mn

import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

6.5 导入模块中的所有函数

语法:from module_name import *

from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

猜你喜欢

转载自blog.csdn.net/weixin_45662399/article/details/132143990