一.今天的学习知识
1. 函数
所谓函数,就是把 具有独立功能的代码块 组织为一个小模块,在需要的时候 调用
- 函数的使用包含两个步骤:
- 定义函数 —— 封装 独立的功能
- 调用函数 —— 享受 封装 的成果
- 函数的作用,在开发程序时,使用函数可以提高编写的效率以及代码的 重用
def multiple_taber(): #封装了下面一个自己写的函数
row = 1
while row <= 9:
col = 1
while col <= row:
print("%d * %d = %d" % (row, col, row*col), end=" ")
col += 1
print("")
row += 1
-----------------------
import fation #导入自己写的函数
fation.multiple_taber() #包装了函数,和调用函数
1.2 PyCharm 的调试工具
- F8 Step Over 可以单步执行代码,会把函数调用看作是一行代码直接执行
- F7 Step Into 可以单步执行代码,如果是函数,会进入函数内部
1.3 参数的作用
- 在函数名的后面的小括号内部填写 参数
- 多个参数之间使用
,
分隔
def sum_2(num1, num2):
"""对函数的说明"""
result = num1 + num2
# 可使用返回值,告诉函数一方计算结果
return result
# return 下方代码不会再被自定义函数用到
# 可以使用函数变量,来接收函数返回值
sum_2(2, 3)
函数嵌套
def test1(str1, times):
print(str1 * times)
def test2(str2, times2):
i = 0
while i < 3:
test1(str2, times2)
i += 1
test2("_ ", 8)
1.4 给函数增加注释,点击函数用fn+f1查看
def test1(str1, times):
print(str1 * times)
def test2(str2, times2):
"""
打印多行分割线
@param str2: 分割线使用的字符
@param times2:分割线使用的次数
"""
i = 0
while i < 3:
test1(str2, times2)
i += 1
test2("_ ", 8)
2. 模块
- 每一个以扩展名
.py
结尾的Python
源代码文件都是一个 模块
2.1模块练习
写一个模块
def test1(str1, times):
print(str1 * times)
def test2(str2, times2):
"""
打印多行分割线
@param str2: 分割线使用的字符
@param times2:分割线使用的次数
"""
i = 0
while i < 3:
test1(str2, times2)
i += 1
name = '我是小可爱'
模块的调用
import pl_模块 # 模块名,不能以数字起名
pl_模块.test2("-", 50)
print(pl_模块.name)