●4-1 PM2.5空气质量提醒(1)
PM = eval(input("请输入PM2.5数值: "))
if 0<= PM < 35:
print("空气优质,快去户外运动!")
if 35 <= PM <75:
print("空气良好,适度户外活动!")
if 75 <= PM:
print("空气污染,请小心!")
●4-2 PM2.5空气质量提醒(2)
PM = eval(input("请输入PM2.5 数值: "))
if PM >= 75:
print("空气存在污染,请小心!")
else:
print("空气没有污染,可以开展户外运动!")
● 4-3 PM2.5空气质量提醒(3)
PM = eval(input("请输入PM2.5数值: "))
if 0<= PM < 35:
print("空气优质,快去户外运动!")
elif 35 <= PM <75:
print("空气良好,适度户外活动!")
else:
print("空气污染,请小心!")
●4-4 身体质量指数BMI的计算(1)
#e5.1CalBMI.py
height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
bmi = weight / pow(height, 2)
print("BMI 数值为:{:.2f}".format(bmi))
wto, dom = "", ""
if bmi < 18.5: # WTO 标准
wto = "偏瘦"
elif bmi < 25: # 18.5 <= bmi < 25
wto = "正常"
elif bmi < 30: # 25 <= bmi < 30
wto = "偏胖"
else:
wto = "肥胖"
if bmi < 18.5: # 我国卫生部标准
dom = "偏瘦"
elif bmi < 24: # 18.5 <= bmi < 24
dom = "正常"
elif bmi < 28: # 24 <= bmi < 28
dom = "偏胖"
else:
dom = "肥胖"
print("BMI 指标为:国际'{0}', 国内'{1}'".format(wto, dom))
●4-5 身体质量指数BMI的计算(2)
#e5.2CalBMI.py
height, weight = eval(input("请输入身高(米)和体重\(公斤)[逗号隔开]: "))
bmi = weight / pow(height, 2)
print("BMI 数值为:{:.2f}".format(bmi))
wto, dom = "", ""
if bmi < 18.5:
wto, dom = "偏瘦", "偏瘦"
elif 18.5 <= bmi < 24:
wto, dom = "正常", "正常"
elif 24 <= bmi < 25:
wto, dom = "正常", "偏胖"
elif 25 <= bmi < 28:
wto, dom = "偏胖", "偏胖"
elif 28 <= bmi < 30:
wto, dom = "偏胖", "肥胖"
else:
wto, dom = "肥胖", "肥胖"
print("BMI 指标为:国际'{0}', 国内'{1}'".format(wto, dom))
● 4-6 蒙特卡罗方法求解π值
#e6.1CalPi.py
from random import random
from math import sqrt
from time import clock
DARTS = 1000
hits = 0.0
clock()
for i in range(1, DARTS+1):
x, y = random(), random()
dist = sqrt(x ** 2 + y ** 2)
if dist <= 1.0:
hits = hits + 1
pi = 4 * (hits/DARTS)
print("Pi值是{}.".format(pi))
print("运行时间是: {:5.5}s".format(clock()))
●4-7 异常处理的小例子(1)
try:
num = eval(input("请输入一个整数: "))
print(num**2)
except NameError:
print("输入错误,请输入一个整数!")
4-8 异常处理的小例子(2)
try:
alp = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
idx = eval(input("请输入一个整数: "))
print(alp[idx])
except NameError:
print("输入错误,请输入一个整数!")
except:
print("其他错误")
●4-9 异常处理的小例子(3)
try:
alp = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
idx = eval(input("请输入一个整数: "))
print(alp[idx])
except NameError:
print("输入错误,请输入一个整数!")
else:
print("没有发生异常")
finally:
print("程序执行完毕,不知道是否发生了异常")