Comparing a variable to an `int` is not working

  • A+

My program needs an integer from the user, so I'm trying to create a loop that will occur if they enter a non-integer and doesn't end until they enter an integer. I've tried:

PlayerCount = input("How many players?") while PlayerCount != int:     try:         PlayerCount = int(PlayerCount)     except ValueError:         print("Please enter a number between 3 and 5")         PlayerCount = input("How many players?") 

However, when a valid input is entered the loop doesn't continue, or end and allow the rest of the program to run. I simply see a line break in IDLE and a blinking cursor. Is there something else I need to do to properly end the while loop? I expected the loop to end automatically once the try block succeeds.


The error is in the line while PlayerCount != int:.

PlayerCount != int will always be true. What you probably want to do is check if PlayerCount is of an integer type. But you're actually checking if it is equivalent to the class int itself. Note that an actual integer is different from the int class.

To check whether PlayerCount is an instance of the int class, replace the condition with while not isinstance(PlayerCount, int):.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: