Skip to content
  • Input & Output · Python

Input & Output

LearnViaNotes @learnvianotes· 4 min read

Talking to the console: everything print() can do, reading typed input with input(), and the fast sys.stdin patterns used in coding rounds.

print() in full

Signature: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False). Each object is converted with str(), joined by sep, followed by end.

Python
print("a", "b", "c")                      # a b c
print("a", "b", "c", sep="-")             # a-b-c
print(2026, 9, 29, sep="/")               # 2026/9/29
print("Loading", end=""); print("...done")   # Loading...done
print(*[1, 2, 3], sep=", ")               # 1, 2, 3
print("tab\tseparated", repr("hi"))      # tab	separated 'hi'
ParameterDefaultUse it for
sep' 'What goes between the objects
end'\n'What goes after the last object — end='' keeps the cursor on the line
filesys.stdoutAny object with .write(): sys.stderr, an open file, an io.StringIO
flushFalseForce the output out immediately (progress bars, logs piped to another program)
Python
import io
buf = io.StringIO()
# file= sends the text to buf instead of the screen:
print("to a buffer", 42, file=buf)
print(repr(buf.getvalue()))           # 'to a buffer 42\n'
result = print("shown", end=" ")
print(result)                         # shown None

input() — reading a line

input(prompt) shows the prompt, waits for the user to press Enter and returns the line as a str, without the newline. Convert it yourself.

greet.py
name = input("Your name? ")
age = int(input("Your age? "))
print(f"Hi {name}, next year you'll be {age + 1}")

$ python3 greet.py
Your name? Asha
Your age? 24
Hi Asha, next year you'll be 25

Below, sys.stdin is swapped for an in-memory stream so the example runs without a keyboard — exactly how tests feed input to a program.

Python
import io, sys
fake = io.StringIO("Asha\n3 1 4 1 5\n42\n")
old, sys.stdin = sys.stdin, fake          # pretend the user typed three lines
try:
    name = input()                        # 'Asha' — always a str
    nums = list(map(int, input().split()))
    n = int(input())
    try:
        input()                           # nothing left to read
    except EOFError:
        eof = True
finally:
    sys.stdin = old                       # always restore the real stdin
print(name, nums, n + 1, eof)             # Asha [3, 1, 4, 1, 5] 43 True

Parsing patterns

Input shapeCode
One integern = int(input())
Two integers on a linea, b = map(int, input().split())
A list of integersnums = list(map(int, input().split()))
n lines of textlines = [input() for _ in range(n)]
A grid of charactersgrid = [list(input()) for _ in range(rows)]
Comma-separatedparts = input().split(',')
Everything at oncetokens = sys.stdin.read().split()

Fast input for coding rounds

input() is slow for 10⁵+ lines. sys.stdin.readline is much faster, but it keeps the trailing \n — strip it (or let int() / split() ignore it).

Python
import io
data = io.StringIO("3\n10 20\n30 40\n50 60\n")
readline = data.readline                  # real code: import sys; readline = sys.stdin.readline
n = int(readline())                       # int() ignores the trailing newline
pairs = [tuple(map(int, readline().split())) for _ in range(n)]
print(pairs)                              # [(10, 20), (30, 40), (50, 60)]
print(repr(io.StringIO("hi\n").readline()))   # 'hi\n'

tokens = iter(io.StringIO("2\n5 7\n").read().split())   # read everything, walk token by token
count = int(next(tokens))
print(sum(int(next(tokens)) for _ in range(count)))    # 12

Fast output

Python
import sys
written = sys.stdout.write("written ")    # no automatic newline; returns chars written
print(written)                            # written 8

results = [3, 1, 4]
print(" ".join(map(str, results)))        # 3 1 4

Pretty-printing nested data

Python
from pprint import pprint
data = {"name": "Asha", "skills": ["python", "sql", "dsa"],
        "address": {"city": "Pune", "pin": 411001}}
pprint(data, width=40)
Output
{'address': {'city': 'Pune',
             'pin': 411001},
 'name': 'Asha',
 'skills': ['python', 'sql', 'dsa']}

Formatting output

Python
price, qty, item = 49.5, 3, "pen"
print(f"{item:<6}|{qty:>3}|{price * qty:8.2f}|")   # pen   |  3|  148.50|
print(f"{0.4567:.1%}  {1234567:,}  {7:03d}")       # 45.7%  1,234,567  007

f-strings and the format-spec mini-language (:<6, .2f, ,, %) are covered in depth in String Formatting under Strings & Numbers.

What type does input() return?

Why use sys.stdin.readline instead of input()?

What is the difference between print and sys.stdout.write?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report