Home »
Python
How do you read from stdin in Python?
Last Updated : April 27, 2025
Python provides different methods to read from standard input, such as using sys.stdin
for more control over the input process or the input()
method for a more straightforward approach.
Read from stdin using sys.stdin
The sys.stdin is a file-like object on which we can call functions read() or readlines(), for reading everything or read everything and split by newline automatically.
Example
from sys import stdin
input = stdin.read(1)
user_input = stdin.readline()
amount = int(user_input)
print("input = {}".format(input))
print("user_input = {}".format(user_input))
print("amount = {}".format(amount))
The output of the above example is:
123
input = 1
user_input = 23
amount = 23
In this example, we also used the int() method to convert the string to int and the .format() method to format the string.
Read from stdin using input() method
If the prompt argument is present, it is written to standard output without a trailing newline. The input() method then reads a line from input, converts it to string (stripping a trailing newline), and returns that.
Example
test = input('Input any text here --> ')
print("Input value is: ", test)
The output of the above example is:
Input any text here --> Hello Readers!
Input value is: Hello Readers!
Exercise
Select the correct option to complete each statement about reading from standard input (stdin) in Python.
- In Python, you can read a line from standard input using the ___ function.
- The
sys.stdin
object provides methods like ___ to read input directly from the standard input stream.
- Before using
sys.stdin
, you must ___ the sys module.
Advertisement
Advertisement