Python-自定义函数

自定义函数及调用

创建一个专门存放自定义函数的文件夹 D:\python\customize

构建一个简单的函数

def greet_user():          # 关键词 def 开头,后接定义的函数名,括号必不可少,最后以冒号结尾 
    '''显示简单的问候语'''    # 注释用三个引号括起
    print('Hello!')        # 单引号双引号都可以

将函数保存到 customize 文件夹中,命名为greet.py

image-20211114002034335

调用自定义的函数

import sys
sys.path.append(r"D:\python\customize") # 设置自定义的路径
import greet                            # 调用自定义函数greet.py的文件名
greet.greet_user()                      # 调用函数方式
image-20211114002711631

参数的位置

函数调用要根据定义时参数变量的位置

def difference(x,y):
    diff = x - y
    print(diff)  # diff作为一个变量不用加双引号,加了双引号就会打印diff而不会打印计算的结果
    
difference(3,5)
difference(5,3)
image-20211115230334912

根据关键词调用可不按照位置来

def difference(x,y):
    diff = x - y
    print(diff)
    
difference(y=3,x=5)
image-20211115230716208

默认值

使用默认值时,先列出没有默认值的参数。再列出有默认值的参数

def difference(x,y=2):
    diff = x-y
    print(diff)
    
difference(5)
difference(5,3)
image-20211115231831534

参数可选

def difference(x,y,z=''):
    if z:                 # z 存在的时候
        diff = x-y+z
    else:
        diff = x+y
    print(diff)
    
difference(5,3)
difference(5,3,1)
image-20211117233949080

返回值

在函数中,可使用 return 语句将值返回到调用函数的代码行。返回值让你能够将程序的大部分繁重工作移到函数中去完成,从而简化主程序

def difference(x,y):
    diff = x-y
    return diff
    
z = difference(3,5)
print(z)
image-20211125170042675

函数与列表

传递列表

def greet_users(names):
    for name in names:
        msg = "Hello, " + name.title() + "!" # title返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写
        print(msg)

usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
image-20211124130856413

修改列表

def print_objects(unprinted_objects, completed_objects):                 
    while unprinted_objects:                     # 当unprinted_objects列表有值的时候执行下列指令
        current = unprinted_objects.pop()        # 删除unprinted_objects的最后一个元素并将该元素赋值给current
        print("Printing object: " + current)     #打印删除的元素
        completed_objects.append(current)        # 在completed_objects列表末尾添加current
def show_completed(completed_objects):
    print("\nThe following objects have been printed:")
    for completed_object in completed_objects:
        print(completed_object)
        
unprinted_objects = ["A","b","C"]
completed_objects = []

print_objects(unprinted_objects, completed_objects)
show_completed(completed_objects)
image-20211124142415746

禁止修改列表

上述修改是在unprinted_objects列表里面直接删除,执行完函数之后,该列表没有元素变为空列表,向函数传递列表的副本可避免这个问题。unprinted_objects[:]即为unprinted_objects的副本

调用上述函数时可以用

print_objects(unprinted_objects[:], completed_objects)

任意数量的实参

传递任意数量的实参

当不知道函数需要传递多少个实参的时候,可以用*加形参来表示

如下,*words表示创建一个名为words的空元组

def print_words(*words):
    print(words)
    
print_words('a')
print_words('apple','grape')
image-20211125144031631

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

def print_words(type,*examples):
    print('type: '+type)
    for example in examples:
        print(example)
        
print_words('n','noun','group')
print_words('v','ask','do','can')   
image-20211125145850915

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

**加形参创建一个字典以使函数接受任意的键值对

def user_profile(name,nation,**user_info):
    profile = {}
    profile['name'] = name
    profile['nationality'] = nation
    for key,value in user_info.items():
        profile[key] = value
    return profile
    
user = user_profile('Jenny','America',gender='woman',age=25)
print(user)
image-20211125154628391

将函数存储在模块中

模块是扩展名为.py的文件,包含要导入到程序中的代码。

D:\python_test目录下创建一个存放长方形周长和面积计算公式的py文件,内容如下,记为rectangle_functions.py,该文件即为一个模块

def rectangle_C(a,b):
    c=(a+b)*2
    return c
    
def rectangle_S(a,b):
    s=a*b
    return s

导入整个模块

rectangle_functions.py所在的目录中创建另一个名为rectangle.py的文件,内容如下

import rectangle_functions

C=rectangle_functions.rectangle_C(4,5)
S=rectangle_functions.rectangle_S(4,5)
print('长度为4,宽度为5的长方形')
print('周长为'+str(C)+',面积为'+str(S))
image-20211125164432732

调用rectangle

import sys
sys.path.append(r"D:\python_test") 
import rectangle                           
image-20211125171040461
# 导入特定的的函数
from rectangle_functions import rectangle_C

# 导入全部函数
from rectangle_functions import *

使用 as 指定别名

如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定简短而独一无二的别名

# 使用 as 给模块指定别名
import rectangle_functions as rf
# 调用方式
C=rf.rectangle_C(4,5)

# 使用 as 给函数指定别名
from rectangle_functions import rectangle_C as c
# 调用方式
C=c(4,5)

参考书目:Python编程从入门到实践 - Eric Matthes 著,袁国忠 译

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 本文为《爬着学Python》系列第十篇文章。 在实际操作中,可能函数是我们几乎唯一的实现操作的方式,这是因为函数能...
    SyPy阅读 10,923评论 0 8
  • 3.5 传递任意数量的实参 当不知道函数需要接受多少个实参时,可以通过星号加一个空元组名来实现。 实例:一个制作比...
    妞妞她爸阅读 3,878评论 0 0
  • 3.3 返回值 函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。在函数中,可使用retur...
    妞妞她爸阅读 3,122评论 0 0
  • 3. 函数 函数是带名字的代码块,用于完成具体的工作。需要在程序中多次执行同一项任务时,你无需反复编写完成该任务的...
    妞妞她爸阅读 2,817评论 0 0
  • 函数 定义函数 使用关键字def来告诉Python你要定义一个 函数。这是函数定义,向Python指出了函数名,还...
    yushui1995阅读 3,567评论 0 0

友情链接更多精彩内容