当变量不是整数时循环

问题描述 投票:0回答:1

哈喽哈喽! 我正在开发一个程序,该程序计算输入分数并输出成绩百分比和字母成绩。虽然字母分级部分非常简单,但我在正确完成 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 !="done") 或 ( strScore 是一个整数并且 (strScore < 0 or strScore > 10)))

提前致谢!

python while-loop int
1个回答
2
投票

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(f"HW#{hwCount} score: ")
    if strScore == "done":
        break
    try:
        score = float(strScore)
    except ValueError:
        print(f"\"{strScore}\" is not a valid score, please try again.")
        continue

    if not (0 <= score <= 10):
        print("Please enter a value between 0 and 10.")
        continue

    # Work with the validated value of score
    # ...
    hwCount += 1
© www.soinside.com 2019 - 2024. All rights reserved.