2

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
  • 7
    You want not isinstance(number, int). Right now you're checking if number is the literal int. As in, the class int. And it's not - it's an instance of int, but it's not the class itself. Commented Feb 16, 2021 at 14:33

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.