'How to use two input types like str and int on one variable in Python?
How can I input int or string from the user in Python.
user = input("Enter a number or name of person")
Solution 1:[1]
The input stored in user will always be a string. You can cast the input to an int() or str() as needed.
user = input("Enter a number or name of person: ")
# will always be <class 'str'>
print(type(user))
# convert to int
user = int(user)
# will be <class 'int'>
print(type(user))
# convert to string
user = str(user)
# will be <class 'str'>
print(type(user))
Solution 2:[2]
user = input("Enter a number or name of person: ")
You want to check if it's an int?
user = input("Enter a number or name of person: ")
try:
int(user)
except ValueError:
# The type isn't int
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Captain Caveman |
| Solution 2 | FLAK-ZOSO |
