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!





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.