-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4_python_function.py
More file actions
55 lines (46 loc) · 1.93 KB
/
Copy path4_python_function.py
File metadata and controls
55 lines (46 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#如何定义自己的函数
def calculate_sector_1(): #定义函数的时候,代码不会被执行;只有调用函数的时候才会被执行
central_angle_1=160
radius_1=30
sector_area_1=central_angle_1/360*3.1415926*radius_1**2
print(f"此扇形面积为:{sector_area_1}")
calculate_sector_1()
#通过参数来让函数变的更通用
def calculate_sector(central_angle,radius): #这里是参数
sector_area=central_angle/360*3.1415926*radius**2
print(f"此扇形面积为:{sector_area}")
calculate_sector(160,30)
calculate_sector(60,15)
calculate_sector(30,16)
#如何把函数计算出来的结果拿出来使用
def calculate_sector(central_angle,radius): #这里是参数
sector_area=central_angle/360*3.1415926*radius**2
return sector_area
sector_area_1=calculate_sector(160,30)
print(sector_area_1)
#我写的一个计算BMI的函数
def BMI_caculate(weight,height):
BMI=weight/(height**2)
fenlei=""
if BMI<=18.5:
fenlei="偏瘦"
elif BMI<=25:
fenlei="正常"
elif BMI<=30:
fenlei="偏胖"
else:
fenlei="肥胖"
print(f"您的BMI分类为:{fenlei}")
return BMI
weight=float(input("请输入您的体重(kg):"))
height=float(input("请输入您的身高(m):"))
BMI=BMI_caculate(weight,height)
print("您的BMI为",BMI)
#python官方内置函数 https://docs.python.org/zh-cn/3/library/functions.html
#比如 statistics函数可以求中位数等统计相关是函数
#引入模块是方法
import statistics
from statistics import mean,median #这样使用函数的时候不用再带上某块名字
from statistics import* #这样直接全部引入模块中的函数且在使用的时候不用再带上模块名(但是不推荐,会引入很多用不到的,可能会产生命名冲突)
#还可以引入第三方的模块
# pypi.org 这个网站可以对第三方库进行搜索