1、
假设成年人的体重和身高存在此种关系:
身高(厘米)-100=标准体重(千克)
如果一个人的体重与其标准体重的差值在正负5之间,显示“体重正常”,其他则显示“体重超标”或体重不达标
编写程序,能处理用户输入的异常,并且使用自定义异常类来处理身高小于30cm、大于250cm的异常情况
try:
length=int(input("请输入你的身高(cm):"))
weight=int(input("请输入你的体重(kg):"))
standrd_weight=length-100
diff_weight=weight-standrd_weight
assert diff_weight<=0.05 and diff_weight>=-0.05,"体重不正常!"
except AssertionError as reason:
print(reason)
else:
print("体重正常")
修改后的版本:
class Input_problem(Exception):
"""自定义异常"""
def __init__(self,length,max,min):
self.length=length
self.max=max
self.min=min “”“给类设置属性”“”
try:
length=int(input("请输入你的身高(cm):"))
weight=int(input("请输入你的体重(kg):")) “”“用户输入”“”
standrd_weight=length-100
diff_weight=weight-standrd_weight
if length>=30 and length<=250:
assert diff_weight<=5,"体重超标" """assert语句抛出异常"""
assert diff_weight>=-5,"体重不达标!"
else:
raise Input_problem(length,250,30)
except AssertionError as reason:
print(reason)
except Input_problem:
print("Input_problem_Erroer:输入的身高是:%dcm,不能超过250cm,不能少于30cm"%length) """添加异常描述"""
else:
print("体重正常")
2、
录入一个学生成绩,把该学生的成绩转换为A-优秀,B-良好,C-合格,D-不及格的形式,最后将该学生的成绩打印出来
要求使用assert断言语句处理分数不合理的情况:
while True:
try:
score=int(input("请输入你的成绩:"))
assert score>=0 and score<=100,"输入有误请重新输入!"
if score>=90:
print("成绩为:A")
elif score>=80 and score<=89:
print("成绩为:B")
elif score>=60 and score<=79:
print("成绩为:C")
else:
print("成绩为:D,不及格!!!")
except AssertionError as reason:
print(reason)