How to apply the input() function in Python

The input function in Python can be used to gather input from users.

You may use the following syntax to apply the input function in Python:

value = input()

Next, you’ll see 3 examples of an input function:

  1. For a text/string
  2. Numeric values
  3. Summing numeric values

3 Examples of an Input Function in Python

Example 1: input function for a text/string

You can utilize the input function in order to gather text from users.

For example, the following syntax can be used to gather the name of an individual user:

print('What is your name?')
value = input()
print('Your name is: ' + value)

Run the code, and you’ll see this question:

What is your name?

Enter your name (for example, enter ‘Jon’), and then press ENTER:

What is your name?
Jon

You’ll then see the name that you entered:

What is your name?
Jon
Your name is: Jon

Example 2: input function for numeric values

Similarly, you can gather numeric values from users.

Here is the code to gather the age of an individual:

print('What is your age?')
value = input()
print('Your age is: ' + value)

Once you run the code, you’ll see the following question:

What is your age?

Enter an age (for instance, enter the age of 27), and then press ENTER:

What is your age?
27

You’ll then see the age that you entered:

What is your age?
27
Your age is: 27

Example 3: summing numeric values

What if you want to perform some arithmetic calculations once you gathered a numeric value from a user?

For example, what if you want to add 5 years to the original age entered by the user?

In that case, make sure to apply an int() around the input function for integers values:

value = int(input())

This will allow you to work with integers, and thus avoid the following error (when summing values for example):

TypeError: can only concatenate str (not “int”) to str

Also, when printing the results, make sure that everything is set to strings (i.e., by applying str() when printing):

print('What is your age?')
value = int(input())
value_in_five_years = value + 5
print('In 5 years from now you will be: ' + str(value_in_five_years))

Run the code and you’ll see this question:

What is your age?

Type an age (for example type 27), and then press ENTER:

What is your age?
27

You’ll then get the age 5 years from now:

What is your age?
27
In 5 years from now you will be: 32