
def my_function(parameter):
print(parameter)
return 'parameter is' + parameter
# my_function 函数名
# parameter 输入参数
# return 表示函数需要返回值,返回return后面的变量
2 函数参数设置
2.1 位置参数
调用函数时根据函数定义的参数位置来传递参数。def describe_pet(animal_type,pet_name):#显示宠物的信息
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "’s name is " + pet_name.title() + ".")
describe_pet('dog','harry') #调用describe_pet函数
describe_pet('harry','dog') #位置实参不正确情况
2.2 关键词参数 通过“键-值”形式加以指定。
def describe_pet(animal_type,pet_name): #显示宠物的信息
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "’s name is " + pet_name.title() + ".")
describe_pet(animal_type='dog',pet_name='harry')
describe_pet(pet_name='harrt',animal_type='dog')
2.3 默认参数
用于定义函数,为参数提供默认值,调用函数时可传可不传该默认参数的值(注意:所有位置参数必须出现在默认参数前,包括函数定义和调用)。def describe_pet(pet_name,animal_type='dog'): #显示宠物的信息
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "’s name is " + pet_name.title() + .")
describe_pet(pet_name='harry') #默认animal_type为dog
describe_pet('harry') #pet_name变量接收harry,默认animal_type为dog
describe_pet(pet_name='harry',animal_type='hamster') #animal_type变量为hamster代替默认值dog
2.4 可变参数
主要包括任意数量的可变位置参数和任意数量的关键字可变参数,*args参数传入时存储在元组中,**kwargs参数传入时存储在字典内。
#求和函数
def sum(list):
sum1 = 0
for i in list:
sum1 += i
return sum1
#求平方和函数
def sums(list):
sum2=0
for i in list:
sum2 +=i**2
return sum2
#构建方差函数示例:
def var(list):
return sums(list)/len(list)-(sum(list)/len(list))**2
4 练习:创建BMI函数
4.1 题目
我国成人BMI标准为:体质指数(BMI) <=18.4为偏瘦;18.5~23.9为正常;24~27.9为过重;>28为肥胖。
其中体质指数(BMI)=体重(kg)/身高(m)的平方
1)写一个函数,输入参数为体重(kg)/身高(m),输出体质等级,其中体质等级设定:偏瘦返回-1,正常返回0,过重返回1,肥胖返回2;
2)给定一组体重和身高数据(可使用字典来定义),计算对应的体质等级,并打印结果。
打印形式: 姓名 的体质等级为?
给定的数据:
| 姓名 | 体重 | 身高 |
| Marry | 48 | 1.68 |
| Linda | 56 | 1.66 |
| Susan | 65 | 1.63 |
| Rose | 85 | 1.7 |
| Tony | 83 | 1.82 |
def BMI(i, j):
BMI = float(float(i)/(float(j)**2))
if BMI <= 18.4:
return -1
elif BMI <= 23.9 and BMI >= 18.5:
return 0
elif BMI <= 27.9 and BMI >= 24.0:
return 1
elif BMI > 28.0:
return 2
dict = {"Marry":(48,1.68), "Linda":(56,1.66), "Susan":(65,1.63) ,"Rose":(85,1.7)}
for key,value in dict.items():
i = value[0]
j = value[1]
print(key,"结果为",BMI(i,j))
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)