How to Use the Python input() Function

09/08/2021

Contents

In this article, you will learn how to use the Python input() function.

Python input() Function

The input() function in Python is used to read input from the user. It can be used to receive text input as a string from the user.

Here’s an example:

name = input("What's your name?")
print("Hello, " + name + "!")

This will prompt the user with the message “What’s your name?” and the user can enter their name. The entered value is then stored in the “name” variable and used in the next line to print a personalized greeting.

Note that the input from the user is always read as a string, even if the user enters a number. To use it as a different data type (e.g. integer), you will need to cast it.

For example:

age = int(input("How old are you? "))
print("You will be " + str(age + 1) + " next year.")
 

Here are some additional points and tips about the input() function in Python:

Default String

The prompt message passed as an argument to the input() function is optional. If not provided, the function will wait for the user to enter input without any prompt.

For example:

name = input()
print("You entered: " + name)
Multi-line Input

If you need to read multiple lines of input from the user, you can use a loop with input().

For example:

lines = []
while True:
    line = input()
    if line:
        lines.append(line)
    else:
        break
text = '\n'.join(lines)
print("You entered: " + text)
Input Validation

You can validate the input received from the user to make sure it meets certain criteria.

For example:

while True:
    num = input("Enter an even number: ")
    if num.isdigit() and int(num) % 2 == 0:
        break
    print("Invalid input, try again.")
Reading Input as a List

To read input as a list of values, you can use the split() function.

For example:

values = input("Enter values separated by a comma: ").split(',')
print("Values: " + str(values))

These are just a few examples of what you can do with the input() function in Python. With it, you can interact with the user and receive input from them to use in your code.