How do you read from stdin in Python?

Reading from stdin in Python: In this tutorial, we will learn how do you read from stdin in Python programming language. By Sapna Deraje Radhakrishna Last updated : January 03, 2024

Python supports following ways to read an input from stdin (standard input),

1. 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 to read from stdin using sys.stdin

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

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.

2. 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 to read from stdin using input() method

test = input('Input any text here --> ')
print("Input value is: ", test)

Output

The output of the above example is:

Input any text here --> Hello Readers!
Input value is:  Hello Readers!

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.