/    Sign up×
Bounties /Pin to ProfileBookmark

How do I gather numbers and not a string of a number from the user in Python?

When I have the below code:

age = input("Insert your age: ")

age ends up being a string and not an int. How do I take an int as an input?

to post a answer
Python

3 Replies

Copy linkTweet thisAlerts:
@lukeSep 08.2022 — As the input is a string you would need to cast the input string to an int.

You can do this directly when the input has been submitted with:

age = int(input("Insert your age: "))

However I would recommend validating the input before doing this to prevent throwing an exception with a null/empty check + an 'is numeric' check using:

age.isnumeric()
which returns a boolean

age = input("Insert your age: ")
if (age == None or age == '') return
if (!age.isnumeric()) return
ageInt = int(age)
Copy linkTweet thisAlerts:
@PhysBoomAug 31.2022 — You can very simply use


age = int(input("Insert your age: "))


And age will be converted into an integer.

If you want to prevent invalid stuff from being typed (i.e. do something if the input is not an integer), you can use errors as control flow:


try:
age = int(input("Insert your age: "))
except ValueError:
print("Improper age!")
Copy linkTweet thisAlerts:
@delta1512Aug 17.2022 — The 'input' built-in will always return a string from the user input. Create a new integer by wrapping it with the int built-in:

age = int(input("Insert your age: "))


However, you may want to do input sanitisation, otherwise you will get a ValueError if the user doesn't input a number. This can be handled like so (although you may want to use something like regex in the long-run):
try:
age = int(input("Insert your age: "))
except ValueError:
print('Incorrect age, please try again!')
...
×

Success!

Help @MichaelDelgado spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 3.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 10 SATS,
)...