Skip to content

Latest commit

 

History

History
497 lines (389 loc) · 12.8 KB

04_input_output.md

File metadata and controls

497 lines (389 loc) · 12.8 KB

04 — Input & Output

"Python gives you five ways to receive data. Know them all."


Table of Contents


print() — Output

print() is Python's primary output function. It's more powerful than it looks.

Basic Usage

print("Hello, World!")
print(42)
print(3.14)
print(True)
print(None)   # prints "None"

Multiple Arguments

name = "Logesh"
age = 22
city = "Chennai"

# Multiple args — separated by space by default
print(name, age, city)          # Logesh 22 Chennai

# Custom separator
print(name, age, city, sep=", ") # Logesh, 22, Chennai
print(name, age, city, sep=" | ")# Logesh | 22 | Chennai
print(name, age, city, sep="")   # Logesh22Chennai

end Parameter

# Default end is '\n' (newline)
print("Hello")   # Hello\n
print("World")   # World\n (on new line)

# Custom end
print("Hello", end=" ")
print("World", end="!")
print()  # → Hello World!

# Progress bar style
import time
for i in range(5):
    print(f"Processing {i+1}/5...", end="\r")  # \r = carriage return
    time.sleep(0.5)
print("Done!               ")

String Formatting Methods

name = "Logesh"
age = 22
pi = 3.14159

# 1️⃣ f-strings (Python 3.6+) — RECOMMENDED
print(f"Name: {name}, Age: {age}")
print(f"Pi = {pi:.2f}")          # Format float to 2 decimal places
print(f"Pi = {pi:.4f}")          # 3.1416
print(f"Padded: {name:<10}|")    # Left-align in 10-char width
print(f"Padded: {name:>10}|")    # Right-align
print(f"Padded: {name:^10}|")    # Center-align
print(f"Int: {1000000:,}")       # Comma separator: 1,000,000
print(f"Hex: {255:#x}")          # 0xff
print(f"Bin: {10:#b}")           # 0b1010
print(f"Percent: {0.875:.1%}")   # 87.5%

# 2️⃣ .format() (Python 3)
print("Name: {}, Age: {}".format(name, age))
print("Name: {0}, Age: {1}, Name again: {0}".format(name, age))
print("Name: {n}, Age: {a}".format(n=name, a=age))

# 3️⃣ % formatting (old-style, still used in logging)
print("Name: %s, Age: %d, Pi: %.2f" % (name, age, pi))
# %s = string, %d = int, %f = float, %r = repr

print() to Files

# Print to a file instead of stdout
with open("output.txt", "w") as f:
    print("Line 1", file=f)
    print("Line 2", file=f)
    print(f"Pi = {3.14}", file=f)

Pretty Printing

import pprint

data = {
    "students": [
        {"name": "Alice", "grade": 90, "subjects": ["Math", "Science"]},
        {"name": "Bob", "grade": 85, "subjects": ["English", "History"]},
    ]
}

print(data)          # Ugly one-liner
pprint.pprint(data)  # Nicely formatted and indented
pprint.pprint(data, indent=4, width=60)

input() — Basic User Input

input() reads a line from the user as a string.

# Basic input
name = input("Enter your name: ")
print(f"Hello, {name}!")

# input() ALWAYS returns a string
value = input("Enter a number: ")
print(type(value))   # <class 'str'>

# You MUST convert to the desired type
number = int(input("Enter a number: "))
print(number + 10)   # Now works as integer

⚠️ Critical: input() always returns str. If you need a number, you MUST cast it.


Type Conversion with Input

This is one of the most common patterns in Python programs.

Single Value Input

# Integer input
age = int(input("Enter your age: "))

# Float input
height = float(input("Enter your height in meters: "))
print(f"Height: {height:.1f}m")

# Boolean input (custom)
answer = input("Are you a developer? (yes/no): ").strip().lower()
is_dev = answer in ("yes", "y", "true", "1")
print(f"Developer: {is_dev}")

Multiple Values on One Line

# Method 1: split() — get multiple values on one line
# User types: 10 20 30
numbers = input("Enter 3 numbers separated by space: ").split()
# numbers = ['10', '20', '30']  ← still strings!

# Convert all to int using map()
a, b, c = map(int, input("Enter 3 numbers: ").split())
print(a + b + c)

# Or as a list
nums = list(map(int, input("Enter numbers: ").split()))
print(nums)        # [1, 2, 3, ...]
print(sum(nums))

# Method 2: split with custom separator
# User types: 10,20,30
parts = input("Enter comma-separated values: ").split(",")
values = [int(p.strip()) for p in parts]

Reading Multiple Lines

# Read N lines
n = int(input("How many values? "))
data = []
for _ in range(n):
    val = int(input())
    data.append(val)
print(f"Sum: {sum(data)}, Average: {sum(data)/len(data):.2f}")

# Competitive programming style (read until empty line)
import sys
lines = []
for line in sys.stdin:
    line = line.strip()
    if not line:
        break
    lines.append(line)

Safe Input with Validation

def get_integer(prompt, min_val=None, max_val=None):
    """Get a validated integer from the user."""
    while True:
        try:
            value = int(input(prompt))
            if min_val is not None and value < min_val:
                print(f"Please enter a value >= {min_val}")
                continue
            if max_val is not None and value > max_val:
                print(f"Please enter a value <= {max_val}")
                continue
            return value
        except ValueError:
            print("Invalid input. Please enter a whole number.")

age = get_integer("Enter your age: ", min_val=0, max_val=150)
print(f"Your age is {age}")

Taking Input from Command Line (sys.argv)

sys.argv is a list of command-line arguments passed to the script.

# Running the script
python script.py arg1 arg2 arg3
# script.py
import sys

# sys.argv[0] is always the script name
print(sys.argv)          # ['script.py', 'arg1', 'arg2', 'arg3']
print(sys.argv[0])       # script.py
print(sys.argv[1])       # arg1

# Practical example
# Run: python calculator.py 10 + 5
if len(sys.argv) != 4:
    print("Usage: python calculator.py <num1> <operator> <num2>")
    sys.exit(1)

num1 = float(sys.argv[1])
operator = sys.argv[2]
num2 = float(sys.argv[3])

if operator == "+":
    print(num1 + num2)
elif operator == "-":
    print(num1 - num2)
elif operator == "*":
    print(num1 * num2)
elif operator == "/":
    print(num1 / num2 if num2 != 0 else "Error: Division by zero")

Using argparse (Professional CLI)

argparse is the standard library for building command-line tools. Much better than raw sys.argv.

# cli_tool.py
import argparse

# Create the parser
parser = argparse.ArgumentParser(
    description="A professional CLI tool example",
    formatter_class=argparse.RawDescriptionHelpFormatter,
    epilog="Example: python cli_tool.py --name Logesh --count 3 --verbose"
)

# Add arguments
parser.add_argument("--name", "-n", type=str, required=True, help="Your name")
parser.add_argument("--count", "-c", type=int, default=1, help="Number of greetings (default: 1)")
parser.add_argument("--verbose", "-v", action="store_true", help="Enable verbose output")
parser.add_argument("input_file", nargs="?", help="Optional input file")

# Parse the arguments
args = parser.parse_args()

# Access arguments
if args.verbose:
    print(f"[DEBUG] Running with name={args.name}, count={args.count}")

for i in range(args.count):
    print(f"Hello, {args.name}! (greeting {i+1})")
# Run it:
python cli_tool.py --name Logesh --count 3 --verbose
python cli_tool.py -n Logesh -c 3
python cli_tool.py --help   # Auto-generated help!

Taking Input from Files

Reading Files (the Right Way — with with statement)

# Method 1: Read entire file as string
with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

# Method 2: Read line by line (memory efficient for large files)
with open("data.txt", "r", encoding="utf-8") as f:
    for line in f:                  # File object is iterable!
        line = line.strip()         # Remove \n
        print(line)

# Method 3: Read all lines into a list
with open("data.txt", "r") as f:
    lines = f.readlines()           # ['line1\n', 'line2\n', ...]
    lines = [l.strip() for l in lines]  # Clean version

# Method 4: Read specific number of characters
with open("data.txt", "r") as f:
    chunk = f.read(100)             # Read first 100 characters

Writing to Files

# Write mode ('w') — creates or overwrites
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("First line\n")
    f.write("Second line\n")

# Append mode ('a') — adds to existing file
with open("output.txt", "a") as f:
    f.write("Third line\n")

# Write multiple lines
lines = ["apple\n", "banana\n", "cherry\n"]
with open("fruits.txt", "w") as f:
    f.writelines(lines)

Reading CSV Files

import csv

# Read CSV
with open("students.csv", "r", newline="") as f:
    reader = csv.DictReader(f)   # Each row is a dict
    for row in reader:
        print(row["name"], row["grade"])

# Write CSV
students = [
    {"name": "Alice", "grade": 90},
    {"name": "Bob", "grade": 85},
]
with open("students.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "grade"])
    writer.writeheader()
    writer.writerows(students)

Reading JSON Files

import json

# Read JSON
with open("config.json", "r") as f:
    config = json.load(f)    # Parses JSON into Python dict
    print(config["database"]["host"])

# Write JSON
data = {"name": "Logesh", "skills": ["Python", "JS"]}
with open("output.json", "w") as f:
    json.dump(data, f, indent=2)

# JSON from/to string (without file)
json_string = json.dumps(data, indent=2)  # dict → string
parsed = json.loads(json_string)           # string → dict

Taking Input from Environment Variables

import os

# Read environment variable
db_host = os.environ.get("DATABASE_HOST", "localhost")     # with default
api_key = os.environ.get("API_KEY")                        # None if missing

if api_key is None:
    raise ValueError("API_KEY environment variable is not set!")

print(f"Connecting to {db_host}")

# Set environment variable (in Python — only for current process)
os.environ["MY_VAR"] = "some_value"

# List all env variables
for key, value in os.environ.items():
    print(f"{key}={value}")

Using .env Files (Best Practice)

pip install python-dotenv
# .env file (never commit to git!)
# DATABASE_URL=postgresql://localhost/mydb
# SECRET_KEY=mysecretkey123
# DEBUG=True

from dotenv import load_dotenv
import os

load_dotenv()  # Load .env file

db_url = os.getenv("DATABASE_URL")
secret = os.getenv("SECRET_KEY")
debug = os.getenv("DEBUG", "False").lower() == "true"

stdin/stdout for Competitive Programming

import sys

# Fast input for competitive programming
input = sys.stdin.readline   # Much faster than built-in input()

n = int(input())
arr = list(map(int, input().split()))

# Fast output
print(*arr)                  # Unpack and print with spaces
sys.stdout.write("output\n") # Even faster output

# Read ALL input at once
data = sys.stdin.read().split()
# Process tokens one at a time
idx = 0
n = int(data[idx]); idx += 1
m = int(data[idx]); idx += 1

Interview Q&A

Q1: What does input() return?

Always a string (str), regardless of what the user types. You must explicitly convert: int(input()), float(input()), etc.

Q2: What is int(input())?

It's a common pattern: input() reads a string from the user, and int() immediately converts it to an integer. If the user types a non-integer, it raises a ValueError. Use try/except to handle this safely.

Q3: How do you take multiple inputs on one line?

# User types: 5 10 15
a, b, c = map(int, input().split())

# As a list
nums = list(map(int, input().split()))

Q4: What is the difference between sys.stdin.readline() and input()?

sys.stdin.readline() is significantly faster, especially for large inputs. It also includes the trailing \n (which input() strips). Used in competitive programming for performance.

Q5: Why use with open(...) instead of just open(...)?

The with statement is a context manager. It guarantees the file is properly closed, even if an exception occurs. Without with, you'd need a try/finally block to ensure f.close() is called.

Q6: What are the different file modes?

Mode Meaning
'r' Read (default)
'w' Write (overwrites)
'a' Append
'x' Exclusive create (fails if exists)
'b' Binary mode (e.g., 'rb', 'wb')
'+' Read + Write (e.g., 'r+', 'w+')

Next: 05 — Operators →