To get user input in console applications, we are using python’s input function. This function gets a question string to be displayed to the user, and it captures all user input until they press enter (line break). See it in action in the following example:

username = input( "Please tell me your name: " )
print( "Hello {0}, how are you?".format( username ) )

This sample outputs:

>>> Please tell me your name: matt
Hello matt, how are you?

Getting Number Inputs in Python

By default, input function returns user input as string. So, if you are willing to use the input in a numeric operation (addition, subtraction etc.), you need to convert that input to a number first.

See how this can be done in the example below:

birthyear = input( "What year were you born in? " )
age = 2018 - int( birthyear )
print( "Wow, you don't show your age {0} at all!".format( age ) )

Outputs:

>>>What year were you born in? 1980
Wow, you don't show your age 38 at all!

Please note; converting user input to a number may not be always possible. So it is best practice to wrap all conversions like this in try-except blocks.

I hope you liked this post. Don’t forget to visit our Python category archives for more tips on Python.