当前位置:   article > 正文

封装python函数判断成绩等级_python判断成绩等级思路与实现

python封装错误信息:定义函数,从键盘上获取成绩(1--100),如果输入有误,请重新输入

方法一:使用正则表达式

import re

while True:

score = (input("请输入成绩:"))

if score.isdigit():

score = int(score)

elif (re.match('^\d+\.\d+$',score)):

score = float(score)

else:

if score.lower()=='q':

break

else:

print("请输入0到100数字")

continue

if 0<=score<=100:

if 90<=score<=100:

print("A")

elif 80<=score<90:

print("B")

elif 60<=score<80:

print("C")

elif 0<=score<60:

print("D")

else:

print("输入有误")

continue

二、使用isdigit()判断是否为整数实现

while True:

score = (input("请输入成绩:"))

if len(str(score))<=5:

if score.lower() == 'q':

break

elif score=='':

continue

_score=score.replace('.','',1)

if _score.isdigit():

if _score == score:

score = int(score)

else:

score = float(score)

if 90<=score<=100:

print("A")

elif 80<=score<90:

print("B")

elif 60<=score<80:

print("C")

elif 0<=score<60:

print("D")

else:

print("输入有误")

continue

else:

print("请输入0到100数字,小数点最多2位")

continue

方式三:使用异常处理

def Score():

while True:

score = (input("请输入成绩:"))

if score.lower() == 'q':

break

try:

score = float(score)

if 90<=score<=100:

print("A")

elif 80<=score<90:

print("B")

elif 60<=score<80:

print("C")

elif 0<=score<60:

print("D")

else:

print('请输入0到100之间')

except ValueError as e:

print('输入有误,错误信息为:%s'%e)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/496388
推荐阅读
相关标签
  

闽ICP备14008679号