目录
1.第一个函数
# 注意:定义好函数之后,只表示这个函数封装了一段代码而已
# 如果不主动调用函数,函数是不会主动执行的
def say_hello():
print("hello 1")
print("hello 2")
print("hello 3")
print("hello 4")
say_hello()
2.第一个函数改造
name = "小明"
# Python 解释器知道下方定义了一个函数
def say_hello():
"""打招呼 给python函数定义注释 """
print("hello 1")
print("hello 2")
print(name)
print("hello 3")
print("hello 4")
print(name)
# 只有在程序中,主动调用函数,才会让函数执行
say_hello()
print(name)
3.函数的参数
def sum2_num(num1,num2):
"""对两个数字的求和"""
result = num1 + num2
print("%d + %d = %d" %(num1,num2,result))
sum2_num(100,20)
4.函数的返回值
def sum_2_num(num1,num2):
"""对两个数字的求和"""
result = num1 + num2
# 可以使用返回值,告诉调用函数一方计算的结果
return result
# 注意:return 就表示返回,下方的代码不会被执行到!
# 可以使用变量,来接收函数执行的返回结果
sms_result = sum_2_num(10,20)
print("计算结果:%d" % sms_result)
5.函数的嵌套调用
def test1():
print("*" * 50)
def test2():
print("-" * 50)
# 函数的嵌套调用
test1()
print("-" * 50)
test2()
6.打印分割线
#def print_line(char):
# print(char * 50)
# print_line("*")
def print_line(char,times):
print(char * times)
print_line("hr", 60)
7.打印多条分割线
def print_line(char, times):
"""
添加注释
:param char:
:param times:
"""
print(char * times)
def print_lines(char, times):
"""
打印多行分割线
:param char:
:param times: """
row = 0
while row < 5:
print_line(char, times)
row += 1
print_lines("-", 20)
8.分割线模块
def print_line(char, times):
"""
添加注释
:param char:
:param times:
"""
print(char * times)
def print_lines(char, times):
"""
打印多行分割线
:param char:
:param times: """
row = 0
while row < 5:
print_line(char, times)
row += 1
name = "黑马程序员"
9.分割线体验模块
import 分割线模块
分割线模块.print_line("-", 50)
print(分割线模块.name)
name_list = ["zhangsan", "lisi", "wangwu"]
print(name_list)
print(name_list[0])
print(name_list[1])
print(name_list[2])