user8654054
user8654054

Reputation:

Python | Expecting type INT, but if STR entered?

I'm asking the user for an integer type input. But if the user accidentally inputs string type, I want it to tell the use they incorrectly answer the question. Like this:

question1 = int(input("Enter a number: "))
if question1 != int:
    print("Please enter a number.")
else:
     ...

Please note I am a beginner, and therefore do not understand expect style coding.

Thank you for your time.

Upvotes: 0

Views: 2269

Answers (2)

Davo
Davo

Reputation: 566

You can use str.isdigit() method to check if the input contains digits only

question1 = input("Enter a number: ")
if question1.isdigit():
    question1= int(question1)
else:
     print("Not a number")

Upvotes: 0

Shadow
Shadow

Reputation: 9427

Casting a string to an integer will only work if the string looks like an integer.

Anything else will raise a ValueError.

My suggestion is to catch this ValueError and inform the user appropriately.

try:
    question1 = int(input("Enter a number: "))
except ValueError:
    print("That's not a number!")
else:
    print("Congratulations - you followed the instructions")

Upvotes: 1

Related Questions