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:
input("Your name: ") 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:
input("Enter a number: ") number = |
To convert the captured string into an integer, you can use the int()
method:
int(input("Enter a number: ")) number = |
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:
input() data = |
As observed, the captured data is in string format. To transform these strings into integer values:
int(item) for item in str_list] int_list = [ |
You can use various delimiters with the split()
method, including but not limited to (a,b,c...)
, 1,2,3...
, %
, !
, *
, and space.
input() data = |
Related Course: Complete Python Programming Course & Exercises