Python - my While loop does not detect integer in variable

Viewed 83

While writing an assignment for Python training, I encountered something strange. The code:

number = 0
while number is not int:
    try:
        number = int(input("Give a number to start counting with: "))
        break
    except ValueError:
        print('Please enter a valid number!')

print("the computer starts counting at number: ", number)

No matter what I fill in as value for number, the while loop runs. Filling in a 0 or 6 or even a letter, the while loop runs. If I add:

print(type(number))

to it, than it even says it is an integer. So why does the while loop not detect that? For now the program does what I want, but I find it strange behaviour that I don't understand.

1 Answers

to check the type of number you have to do if type(number) is not int,
but to correctly build your loop you have to do like this:

while True:
    try:
        number = int(input("Give a number to start counting with: "))
        break
    except ValueError:
        print('Please enter a valid number!')

print("the computer starts counting at number: ", number)

in fact you fon't need to check number's type in order to stop the loop, the break inside the try: ... except: statement will do your work

Related