Reputation: 5
basically im new to python programming and I've just learnt about user input. Im trying to make an if statement that checks if the input is a str or int and then prints a message. If anyone knows how then please comment it, thanks.
print("How old are you?")
dog = input()
final = int(dog) + int(100)
if dog == str:
print("No")
else:
print("\nHeres you name + 100!")
print(f"{final}")
print("Thanks for playing!")
btw the if statement that I put doesn't work, I dont know if I need to put an exception so it responds with not an error message.
Upvotes: 1
Views: 1897
Reputation: 1758
Re how to check types, you can do like this:
my_string = "hello"
if isinstance(my_string, str):
print("I'm a string")
else:
print("I'm not")
# outputs: "I'm a string"
However, as commented the input method is always returning a value of type str. So if you want to ensure that the value is only consisting of numerical characters, you can use the string method isdigit()
my_string = "asd"
my_string.isdigit() # returns False
my_string = "123"
my_string.isdigit() # returns True
Upvotes: 3
Reputation: 471
I would use the type
method to check:
print("How old are you?")
dog = input()
final = int(dog) + int(100)
#use type method to check the type of the variable
if type(dog) == str:
print("No")
else:
print("\nHeres you name + 100!")
print(f"{final}")
print("Thanks for playing!")
Another thing you can do is set prevent the user from entering anything but an int
and force a proper variable, something like:
while True:
dog = input('How old are you? ')
try:
dog = int(dog)
break
except ValueError:
print('No')
final = dog + 100
print("\nHeres you name + 100!")
print(f"{final}")
print("Thanks for playing!")
Also, don't waste processing power by converting an int
to an int
so that means int(100)
is the same as 100
Upvotes: 1