简体   繁体   中英

Loop while variable is not an integer

Hullo hullo! I'm working on a program that calculates the input scores and outputs the grade percentage and a letter grade. While the letter grading part is super simple, I'm having trouble getting the while loop done right. Currently, I'm trying to add an input trap by making the user only input whole numbers between 0 and 10. The problem is, whenever the user DOES enter the necessary input, it ends up looping and returning the output `"Please enter a whole number." continuously

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:

So, I'll probably feel pretty dumb once I figure this out, but I'm stumped. The algorithmic solution states Loop while ( strScore is not an integer and strScore !="done") or ( strScore is an integer and (strScore < 0 or strScore > 10)))

Thanks in advance!

strScore != int doesn't test if the value is an integer; it checks if the value equal to the int type. You want not isinstance(strScore, int) in this case.

However, you should try to avoid making direct type checks. The important thing is that a value behaves like an float.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM