Python Input and Output — print(), input(), and File I/O Guide

Sanjeev SharmaSanjeev Sharma
4 min read

Advertisement

Introduction

Why This Matters

Input and Output (I/O) are how programs communicate with the outside world — reading user input, displaying results, reading configuration files, writing logs, and exchanging data with APIs. Every useful Python program performs I/O of some kind, whether it's a CLI tool, web API, data pipeline, or automation script.

Python's I/O system is built around standard streams (stdin, stdout, stderr), file objects, and powerful string formatting tools like f-strings. Understanding how to format output clearly, handle user input safely, and interact with the file system is fundamental to professional Python development.

This guide covers print(), input(), f-strings, format(), and standard stream manipulation.

# Basic print
print("Hello, World!")
 
# Multiple values separated by space (default sep)
print("Name:", "Alice", "Age:", 30)
# Name: Alice Age: 30
 
# Custom separator
print("2026", "03", "19", sep="-")
# 2026-03-19
 
# Custom end (default is newline)
print("Loading", end="")
print("...", end="\n")
# Loading...
 
# Print to stderr
import sys
print("Error occurred", file=sys.stderr)

String Formatting

name = "Alice"
age = 30
score = 95.5
 
print(f"Name: {name}, Age: {age}")
print(f"Score: {score:.2f}")      # 2 decimal places: 95.50
print(f"Pi: {3.14159:.4f}")       # 3.1416
print(f"{1000000:,}")             # 1,000,000 (thousands separator)
print(f"{'hello':>10}")           # right-align in 10 chars: '     hello'
print(f"{'hello':<10}|")         # left-align: 'hello     |'
print(f"{'hello':^10}")           # center: '  hello   '
print(f"Hex: {255:#x}")          # Hex: 0xff
print(f"Binary: {10:#b}")         # Binary: 0b1010

format() Method

template = "Hello, {}! You are {} years old."
print(template.format("Bob", 25))
 
# Named placeholders
print("{name} scored {score:.1f}%".format(name="Alice", score=95.567))

input() — Reading User Input

# Basic input (always returns a string)
name = input("Enter your name: ")
print(f"Hello, {name}!")
 
# Convert to appropriate type
age = int(input("Enter your age: "))
price = float(input("Enter price: "))
 
# Safe input with validation
def get_positive_int(prompt: str) -> int:
    while True:
        try:
            value = int(input(prompt))
            if value > 0:
                return value
            print("Please enter a positive number.")
        except ValueError:
            print("Invalid input. Please enter an integer.")
 
count = get_positive_int("How many items? ")

Standard Streams

import sys
 
# stdout: normal output
sys.stdout.write("Hello\n")   # same as print("Hello")
 
# stderr: error output (not captured by default pipe)
sys.stderr.write("Error: something went wrong\n")
 
# stdin: read from pipe or keyboard
for line in sys.stdin:
    print(f"Got: {line.strip()}")
 
# Redirect stdout to a file
with open("output.txt", "w") as f:
    sys.stdout = f
    print("This goes to the file")
    sys.stdout = sys.__stdout__  # restore

Reading from Files

# Read entire file
with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)
 
# Read line by line (memory efficient)
with open("data.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

Writing to Files

# Write
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("Line 1\n")
    f.write("Line 2\n")
    print("Line 3", file=f)   # print() can write to any file object
 
# Append
with open("log.txt", "a", encoding="utf-8") as f:
    import datetime
    timestamp = datetime.datetime.now().isoformat()
    f.write(f"[{timestamp}] Application started\n")

Pretty Printing Complex Data

import json
import pprint
 
data = {"users": [{"name": "Alice", "scores": [95, 87, 92]}, {"name": "Bob", "scores": [78, 85, 90]}]}
 
# pprint for human-readable dicts/lists
pprint.pprint(data, width=60)
 
# JSON-formatted output
print(json.dumps(data, indent=2))

Common Mistakes

  • Forgetting that input() always returns a string — causes TypeError when comparing to int
  • Using print() for debugging in production — use the logging module instead
  • Not specifying encoding="utf-8" when writing files — causes platform-specific issues
  • Comparing input() to integers: if input("Age: ") == 18 always fails
  • Mixing \n and print() end parameter leading to extra blank lines

Best Practices

  • Use f-strings for all string formatting — they are fastest and most readable
  • Validate and convert input() immediately, wrapping in try/except
  • Use logging instead of print() for diagnostic output in scripts and services
  • Specify encoding="utf-8" explicitly on every file open
  • Use pprint.pprint() or json.dumps(..., indent=2) when debugging nested structures

Key Takeaways

  • print() accepts sep and end parameters; it can write to any file-like object via file=
  • input() always returns a string — convert with int(), float(), etc.
  • f-strings support format specs: :.2f, :,, :>10, :#x, :#b
  • sys.stdout, sys.stderr, and sys.stdin are the three standard streams
  • Writing to sys.stderr keeps errors separate from normal output in pipelines
  • For large files, always read line by line in a for loop, not with .read()
  • json.dumps(data, indent=2) is the cleanest way to display nested Python structures

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro

Related reading