我在下面粘贴了这个代码,基本上我试图让它循环如果用户输入无效的测试分数(因为让我们面对它你不能有一个负面的测试分数或分数超过100%) . 所以基本上我试图让程序循环,如果他们确实输入了无效的分数,直到他们输入一个在0到100(含)范围内的分数 .
码:
A='A'
B="B"
C="C"
D="D"
F="F"
score=float(input("Enter a test score: "))
def determine_grade(score):
while score >= 0 and score < 100:
if score >=90 and score <=100:
print(A)
elif score >=80 and score <=89:
print(B)
elif score >=70 and score <=79:
print(C)
elif score >=60 and score <=69:
print(D)
elif score < 60:
print(F)
return score
score = float(input("Invalid score range, please input it again: "))
determine_grade(score)
到目前为止我的输出看起来像这样:
输入测试分数:-2无效分数范围,请再次输入:-2
然后它停在那里,我需要它继续循环,直到我得到一个介于0和100(含)之间的值
2 回答
你在while循环中有详细的测试 . 然后while循环应用于获得有效分数:
Edit:
让我们四处移动(又名refactoring)
让我们将主程序语句一起移动:
但是
determine_grade
函数是它的错误名称 .该程序应首先获得有效分数,然后根据该分数打印分数:
这给我们留下了
validate_score
和print_grade
还要注意最后的
else:
所以最后整个程序是:
使用
raw_input()
Python 2.x或input()
Python 3.x从用户获取值 .如果用户输入非数值,请对
ValueError
执行 exception 处理 .从
string
到float
执行 Type casting .验证用户输入介于
0
和100
之间 .如果2和4为True,则不要断开循环,再次询问输入有效数字 .
break statement 将退出
while
循环,即代码来自相应的循环 .使用
if
和elif
循环根据用户输入打印类 .码:
输出: