Hullo hullo! 我正在研究一个计算输入分数并输出成绩百分比和字母等级的程序。虽然字母评分部分非常简单,但我无法正确完成while循环。 目前,我试图通过使用户只输入0到10之间的整数来添加输入陷阱。问题是,每当用户输入必要的输入时,它最终循环并返回输出“请输入完整的号码。”连续
print ( "Enter the homework scores one at a time. Type \"done\" when finished." )
hwCount = 1
strScore = input ( "HW#" + str ( hwCount ) + " score: " )
while ( strScore != int and strScore != "done" ) or\
( strScore == int and ( strScore < 0 or strScore >10 )):
if strScore == int:
input = int ( input ( "Please enter a number between 0 and 10." ))
else:
print ( "Please enter only whole numbers." )
#End if
strScore = float ( input ( "enter HW#" + str( hwCount ) + " score:
所以,一旦我弄清楚这一点,我可能会感到非常愚蠢,但我很难过。算法解决方案说明 循环while(strScore不是整数,strScore!=“完成”)或 (strScore是整数且(strScore <0或strScore> 10)))
提前致谢!
答案 0 :(得分:1)
strScore != int
不测试该值是否为整数;它检查值是否等于int
类型。在这种情况下,您需要not isinstance(strScore, int)
。
但是,您应该尽量避免进行直接类型检查。重要的是值的行为就像浮动一样。
print("Enter the homework scores one at a time. Type \"done\" when finished.")
hwCount = 1
while True:
strScore = input("HW#{} score: ".format(hwCount))
if strScore == "done":
break
try:
score = float(strScore)
except ValueError:
print("{} is not a valid score, please try again".format(strScore))
continue
if not (0 <= score <= 10):
print("Please enter a value between 1 and 10")
continue
# Work with the validated value of score
# ...
hwCount += 1