美文网首页
Python-自定义函数

Python-自定义函数

作者: 小小白的jotter | 来源:发表于2021-11-26 14:58 被阅读0次

自定义函数及调用

创建一个专门存放自定义函数的文件夹 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 著,袁国忠 译

相关文章

  • Python-自定义函数

    自定义函数及调用 创建一个专门存放自定义函数的文件夹 D:\python\customize 构建一个简单的函数 ...

  • mysql-自定义函数

    创建自定义无参数函数 调用自定义函数 创建有参数的自定义函数 调用有参数的自定义函数 创建具有复合结构的自定义函数...

  • 9.MySQL自定义函数

    自定义函数 自定义函数的两个必要条件 参数 返回值 创建自定义函数 函数体 例子 带有参数的自定义函数 删除函数 ...

  • Python--删除字符串首尾空格函数的实现

    在上一篇文章中Python-批量修改文件名中,有用到strip()函数删除字符串首尾空格。 strip()函数示例...

  • Python-函数

    函数 函数是可重复使用的程序片段:它允许你为 某个代码块 命名,允许通过这一特殊的名字在你程序的任何地方来运行代码...

  • python-函数

    作用域 L local局部作用域 E enclosing嵌套的父级函数的局部作用域,即包含此函数的上级函数的局部作...

  • Python-函数

  • python-函数

    定义函数 函数定义示例: 定义 cylinder_volume 函数后,我们可以如下所示地调用该函数。 cylin...

  • python-函数

    1:介绍 python里的函数: 就是一系列实现某个特定功能的语句的集合, 他可以通过名字进行...

  • Python-函数

    ​ 函数是一种可以复用代码,把大型代码拆分成多段代码,实现功能分离,达到模块化的效果。 ​ 对于函数主要有...

网友评论

      本文标题:Python-自定义函数

      本文链接:https://www.haomeiwen.com/subject/sexxxrtx.html