Search code examples
pythonif-statementwhile-loopint

Check python var if int


I am trying to get python to check if a certain variable is an int

    numbergames = input("Number of Games to Analyze: ")
valuenumber = True
while valuenumber == True:
    if numbergames == int:
        valuenumber = False
    if numbergames != int:
        numbergames = input("Please type a valid number: ")
print("Thanks")

The code is getting stuck and is not getting out of the loop even thought the number typed is an int.


Solution

  • In general, it is discouraged to use type() as identifying if an input is int, float, etc. This is because it does not register a subclass of int as an int.

    Instead, use isinstance('var', (int, long)) which will give the right result expected. So your code will take the form of:

    numberGames = input("Number of Games to Analyze: ")
    
    while True:
        if isinstance( numberGames, (int, long) ):
            break
        else:
            numberGames = input("Please type a valid number: ")
    print("Thanks")
    

    You don't need the valueNumber variable because its only use is as a flag for the while loop. Instead, it could continue running indefinitely with True until it reaches break because the statement tells the program to exit the loop.