python判斷成績等級思路與實現


方法一:使用正則表達式

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)
 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM