基本语法
def 函数名([形式参数]): #形式参数:函数定义者要求调用者提供的信息(可省略)。
''' 文档字符串 '''
函数体
关于调用函数:
1、函数定义后,不调用不会执行。
2、函数调用结束后,返回到函数调用的位置。
例题:
定义函数,在终端中打印一维列表
def print_list(lists):
for item in lists:
print(item)
list01 = [5,546,6,56,76]
list02 = [7,6,879,9,909]
print_list(list01)
print_list(list02)
返回值
定义:函数定义者告诉调用者的结果。
语法:
def 函数名([形式参数]):
''' 文档字符串 '''
函数体
return [数据]
例题:
计算2个数的和
def add(x,y):
result = x + y
return result
x = float(input("请输入第一个数:"))
y = float(input("请输入第二个数:"))
result = add(x,y)
print("结果为:" + str(result))
练习题:
创建计算治愈比例的函数
def cure_rate(cure_person,ill_person):
result = (cure_person / ill_person) * 100
return result
cure_person = int(input("请输入治愈人数:"))
ill_person = int(input("请输入确诊人数:"))
result = cure_rate(cure_person,ill_person)
print("治愈比例为:" + str(result) + "%")
定义函数,根据总两数,计算几斤零几两:(一斤=十六两 原制)
def sum_number(total_liang):
jin = total_liang // 16
liang = total_liang % 16
return jin,liang
total_liang = int(input("请输入总两数:"))
jin,liang = sum_number(total_liang)
print(str(jin) + "斤零" + str(liang) + "两")