Python’s input() function allows users to fetch keyboard input directly from the console. This method reads the keyboard input data and instantly returns it in the string data type format.

For those who have worked with earlier Python versions, specifically Python2.x, you might recall the raw_input() method. However, it’s worth noting that this method has been deprecated. In modern Python, input() is the standard method for receiving console input.

Related Course: Complete Python Programming Course & Exercises

How to Use the input() Function in Python

Fetching Strings from the Terminal

By default, the input() function retrieves data as a string. So when you utilize this function, you are essentially obtaining a text object. Here’s a demonstration:

>>> name = input("Your name: ")
Your name: Sida
>>> type(name)
<class 'str'>
>>> print(name)

Reading Integers from the Console

While the input() function by default captures and returns data as strings, there’s a common requirement to read integers. For this, you need to perform type casting:

>>> number = input("Enter a number: ")
Enter a number: 6
>>> number
>>> type(number)
<class 'str'>

To convert the captured string into an integer, you can use the int() method:

>>> number = int(input("Enter a number: "))
Enter a number: 256
>>> type(number)
<class 'int'>

Python input function illustration

Taking Lists as Input in Python

Python’s input() function can also facilitate the input of lists. Initially, you should take the input as a standard string and then break it down using a specified delimiter, like a comma. Here’s a step-by-step process:

>>> data = input()
>>> str_list = data.split(",")
>>> str_list
['1', '2', '3', '4', '5', '6']

As observed, the captured data is in string format. To transform these strings into integer values:

>>> int_list = [int(item) for item in str_list]
>>> int_list
[1, 2, 3, 4, 5, 6]

You can use various delimiters with the split() method, including but not limited to (a,b,c...), 1,2,3..., %, !, *, and space.

>>> data = input()
1 2 3 4
>>> str_list = data.split(" ")
>>> print(str_list)
['1', '2', '3', '4']
>>> int_list = [int(item) for item in str_list]
>>> print(int_list)
[1, 2, 3, 4]

Related Course: Complete Python Programming Course & Exercises