
定义函数的格式如下:
def 函数名():
函数封装的代码
……def 是英文 define 的缩写调用函数很简单的,通过 函数名() 即可完成对函数的调用
name = "小明"
# 解释器知道这里定义了一个函数
def say_hello():
print("hello 1")
print("hello 2")
print("hello 3")
print(name)
# 只有在调用函数时,之前定义的函数才会被执行
# 函数执行完成之后,会重新回到之前的程序中,继续执行后续的代码
say_hello()
print(name)Python 已经知道函数的存在NameError: name 'say_hello' is not defined (名称错误:say_hello 这个名字没有被定义)注意:因为 函数体相对比较独立,函数定义的上方,应该和其他代码(包括注释)保留 两个空行
def say_hello():
"""
这是一个hello方法
"""
print("hello 1")
print("hello 2")
print("hello 3"), 分隔def sum_2_num(num1, num2):
result = num1 + num2
print("%d + %d = %d" % (num1, num2, result))
sum_2_num(50, 20)return 关键字可以返回结果注意:
return表示返回,后续的代码都不会被执行
def sum_2_num(num1, num2):
"""对两个数字的求和"""
return num1 + num2
# 调用函数,并使用 result 变量接收计算结果
result = sum_2_num(10, 20)
print("计算结果是 %d" % result)test2 中,调用了另外一个函数 test1 test1 函数时,会先把函数 test1 中的任务都执行完test2 中调用函数 test1 的位置,继续执行后续的代码def test1():
print("*" * 50)
print("test 1")
print("*" * 50)
def test2():
print("-" * 50)
print("test 2")
test1()
print("-" * 50)
test2()模块是 Python 程序架构的一个核心概念
py 结尾的 Python 源代码文件都是一个 模块
import 导入这个模块
模块名.变量 / 模块名.函数 的方式,使用这个模块中定义的变量或者函数
模块可以让 曾经编写过的代码 方便的被 复用!
注意:如果在给 Python 文件起名时,以数字开头 是无法在
PyCharm中通过导入这个模块的