复习python从入门到实践——函数function

发布时间:2024年01月09日

复习python从入门到实践——函数function

函数是特别难的,大家一定要好好学、好好复习、反复巩固。函数没学好,会为后面造成很大困扰。
教科书中函数举例会稍微有点复杂。在此章复习中,我将整理出容易疏漏和混淆的知识点,并用最简单的代码辅助大家理解。
本章涉及:定义函数、实参与形参、return返回值、传递列表与切片、将函数导入模块。

1. 定义 def函数

Syntax:

def 函数():
	函数的具体表现(函数体)
函数() #调用

区分函数和变量

  1. 函数 add_numbers():
    接受输入的参数(a,b),并且要有返回值return。后面会介绍。
def add_numbers(a, b):# 定义一个函数
    return a + b
    
result = add_numbers(3, 5)#使用函数
print("结果:", result)

2.变量x,y
依靠=储存各种数据。

# 定义两个变量
x = 10
y = 20

sum_of_variables = x + y # 使用变量
print("变量之和:", sum_of_variables)

2.实参与形参:

形参类似于中文里概括性质的类别,比如“同学”
实参是具体的例子,比如“小明”属于”同学“,”小明“是实参。

def great_user(username):
    """显示问候语:""" #文本注释,三引号,描述函数做什么。
    print(f"Hello {username.title()}!") #函数的工作
great_user('Ashley') 

username 形参
Ashley 实参

传递实参的方法:

(1)对应位置

def animal_lists(category,name):
    print(f"My {category}'s name is {name.title()}.")
animal_lists('pig','feifei')

(2)关键词,用’='连接

def animal_lists(category,name):
    print(f"My {category}'s name is {name.title()}.")
animal_lists(name='feifei',category='pig')

(3)最后一项是默认值

def animal_lists(name, category='dog',):#把默认值放到最后。
    print(f"My {category}'s name is {name.title()}.")
animal_lists(name='feifei')

可选实参:

把可选可不选的参数放到最后一个
middle_name=’ ’

def formatted_name(first_name,last_name,middle_name=' '):
    if middle_name:
        formatted_name = f'{first_name} {middle_name} {last_name}'
    else:
        formatted_name = f'{first_name} {last_name}'
    return formatted_name.title()
students = formatted_name('Haifei',"Wang")
print(students)
students = formatted_name('Haifei','Wang','Pig')#最后一个是中间名
print(students)

通过*传递任意数量实参

def feifei_behaviors(*behavior):#通过加星号调用多个实参
    print(f'飞飞正在:{behavior}')
feifei_behaviors('拉粑粑')
feifei_behaviors('吃粑粑','吃屎','被茵茵看着拉屎')

涉及字典 **可变关键字参数

def build_profile(first,last,**user_info):#**可变关键字参数,除了First和last
    """创建一个字典,其中包含我们知道的有关用户的一切"""
    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)

3.return返回

Syntax:

def function_name():
    具体的statement
    return statement中的函数

Principle:

== a. The statements after the return() statement are not executed. 在return()语句之后的语句不会被执行。
b. return() statement can not be used outside the function. return()语句不能在函数外部使用。
c. If the return() statement is without any expression, then the NONE value is returned. 如果return()语句没有任何表达式,则返回NONE值。==

举例:

def formatted_name(first_name,last_name):
    formatted_name = first_name+' '+ last_name
    return formatted_name()
students = formatted_name('Haifei',"Wang")
print(students)

结果: Haifei Wang

如果没有return语句

def formatted_name(first_name,last_name):
    formatted_name = first_name+' '+ last_name
students = formatted_name('Haifei',"Wang")
print(students)

结果是None

注意:

调用你定义的函数,而不是变量

def city_country(city, country):
    full_name = f'{city},{country}'
    return full_name

while True:
    print("Please inter the city and country:")
    city = input('city:')
    country = input('country:')
    new_name = city_country(city, country)#调用定义变量
    print(new_name)	

4. 传递列表

普通方法:
def+循环+发送列表+调用列表

def greating_lists(names):#建立函数 # 问候 
    '''给列表中的用户打招呼'''
    for name in names:
        print(f'Hello! {name.title()}.')
usernames=['feifei','ashley','tony']# 发送列表
greating_lists(usernames)#调用列表-实参

[:]切片含义:

基本:
[start:stop:step]
用数学集合可以表示为:[ )
举例:
[1:4] 从索引1(包含)到索引4(不包含)也就是索引1 2 3 这几个元素。

重要的容易忽略:
表示列表序列
创建副本

original_list = [10, 20, 30, 40, 50]

# 使用切片创建副本
copied_list = original_list[:]

# 修改副本
copied_list[0] = 100

print("Original List:", original_list)
print("Copied List:", copied_list)

原始列表 original_list 并没有被修改。这是因为切片创建了一个新的列表对象,而不是直接引用原始列表。

5.将函数导入模块

Syntax:
from 文件 import 要导入的东西
import 原来的东西名字 as 你想改的名字
from 文件 import *(所有函数)

文章来源:https://blog.csdn.net/2301_80205209/article/details/135471462
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。