第22天:python函数基础

2 阅读2分钟
  • 学习目标

    • 理解函数的作用:代码复用、模块化
    • 掌握 def 定义函数、函数名、函数体、缩进
    • 学会调用函数(无参数、无返回值)
    • 了解文档字符串 """docstring""" 的写法与查看方式(help()
  • 实践任务

    1. 编写一个打印欢迎信息的函数 greet(),调用两次。
    2. 编写一个输出当前时间的函数 show_time()(使用 datetime 模块)。
    3. 为每个函数添加文档字符串,并用 help(函数名) 查看。
  • 挑战任务
    尝试定义一个函数,打印一个简单的字符画(例如小猫或笑脸)。


函数的简介

函数是组织好的,可重复使用的,用来实现单一的或相关联功能的代码段。 函数可以使应用功能模块化,提高代码的重复利用率。

定义函数

python中函数以def开头,后面是函数标识符名称和圆括号() 语法:

def 函数名(参数列表):
    函数体

圆括号中的是参数列表,任何要传入的参数和自变量必须放在圆括号当中。

调用函数

调用函数需要用到函数的函数名 语法:函数名(实际参数)

文档字符串

文档字符串就是三引号包含的内容,在程序运行时不会执行。通常位于模块,类,函数和方法的开头,用于描述其功能、参数和返回值等。

查看方式

语法:help(函数名) 使用help还可以查看模块、类、方法的使用方法。

实践任务

编写一个打印欢迎信息的函数 greet(),调用两次。

"""
打印欢迎信息
"""
def greet():
    print("welcome to be here")
greet()
greet()

image.png

编写一个输出当前时间的函数 show_time()(使用 datetime 模块)。

from datetime import datetime

"""
查看当前时间
"""
def show_time():
    now=datetime.now()
    print(now)
show_time()

image.png

为每个函数添加文档字符串,并用 help(函数名) 查看。

from datetime import datetime

def show_time():
    """查看当前时间"""
    now=datetime.now()
    print(now)
show_time()
help(show_time)

image.png

挑战任务

尝试定义一个函数,打印一个简单的字符画(例如小猫或笑脸)。

def show_smiley():
    smiley=[
        "  *******  ",
        " *       * ",
        "*  0    0 *",
        "*     ^   *",
        " *       * ",
        "  *******  ",
    ]
    for line in smiley:
        print(line)
show_smiley()

image.png