变量不是整数时循环

2024-05-13 20:34:10 发布

您现在位置:Python中文网/ 问答频道 /正文

你好啊! 我正在做一个程序,计算输入分数,输出分数百分比和字母分数。虽然字母分级部分非常简单,但我很难把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)))

提前谢谢!在


Tags: and用户input字母整数分数intscore
1条回答
网友
1楼 · 发布于 2024-05-13 20:34:10

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

相关问题 更多 >