Home »
Python
How do you read from stdin in Python?
Reading from stdin in Python: Here, we are going to learn how do you read from stdin in Python programming language?
Submitted by Sapna Deraje Radhakrishna, on December 22, 2019
Python supports following ways to read an input from stdin (standard input),
1) Using sys.stdin
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))
Output
123
input = 1
user_input = 23
amount = 23
2) Using input()
If the prompt argument is present, it is written to standard output without a trailing newline. The function 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)
Output
Input any text here --> Hello Readers!
Input value is: Hello Readers!
TOP Interview Coding Problems/Challenges