Input & Output Functions in Python

Module 1 β€’ Session 07 β€’ Allocation: 1 Contact Hr

print() Arguments f-strings input() Conversions sys.stdout Stream

Input and Output (I/O) handling forms the backbone of interactive command-line interface (CLI) applications. Python provides standard built-in mechanismsβ€”primarily input() and print()β€”that connect user inputs via Standard Input (sys.stdin) to Standard Output (sys.stdout).

1. Standard Output with `print()` and Keyword Arguments

The print() function evaluates one or more positional expressions, converts each object to its string representation using str(), and outputs them to a stream buffer.

Parameter Default Value Description / Purpose
*objects None Zero or more positional arguments converted to text output.
sep ' ' (single space) Delimiter string inserted between positional arguments.
end '\n' (newline) Delimiter string appended after printing all positional arguments.
file sys.stdout File-like object destination stream (e.g., standard output or open file pointer).
flush False Forces immediate flushing of the output stream buffer when True.
# Custom Delimiters with 'sep' print("2026", "08", "12", sep="-") # Output: 2026-08-12 # Suppressing Newlines with 'end' print("Processing data...", end=" ") print("Done!") # Output: Processing data... Done! # Directing Output to Standard Error Buffer import sys print("Critical Error Encountered!", file=sys.stderr) # Immediate Buffer Flushing import time for i in range(3, 0, -1): print(f"\rCountdown: {i}", end="", flush=True) time.sleep(0.2) print("\nLaunch!")

2. Capturing User Input with `input()`

The input(prompt) function prints an optional prompt string to sys.stdout without a terminating newline, then pauses execution to read line input from standard input (sys.stdin).

Important Rule: input() always returns data as a string (str), regardless of what the user types. Numeric inputs require explicit conversion via type casting (e.g., int(), float()).
# String Input Capture & Conversion raw_age = input("Enter your age: ") # e.g. user enters 25 print(f"Data type before conversion: {type(raw_age)}") # # Direct Conversion Pattern user_age = int(raw_age) print(f"Years until retirement (65): {65 - user_age}") # Multiple Space-Separated Inputs using split() # Example Input: 10 20 30 x, y, z = map(int, input("Enter 3 numbers space-separated: ").split()) print(f"Sum of inputs: {x + y + z}")

3. Modern String Interpolation: Formatted String Literals (f-strings)

Introduced in Python 3.6 (PEP 498), **f-strings** evaluate embedded Python expressions inside curly braces {} at runtime, making them faster and clearer than legacy options.

Specifier Syntaxes Description / Purpose Example Output
{val:.2f} Fixed-point float rounding (2 decimal places) 3.14159 βž” 3.14
{val:,} Thousands separator grouping 1000000 βž” 1,000,000
{val:>10} Right-align with total width of 10 characters "py" βž” " py"
{val:<10} Left-align with total width of 10 characters "py" βž” "py "
{val:^10} Center-align with total width of 10 characters "py" βž” " py "
{val=}% Percentage formatting / Self-documenting debugging specifier a = 5; f"{a=}" βž” "a=5"
# Advanced f-string Formatting Examples item_name = "Server Rack" price = 1499.986 stock = 42 # Column Alignment, Float Precision, and Thousands Grouping print(f"Item : {item_name:>15}") print(f"Price : ${price:>14,.2f}") print(f"Stock : {stock:08d}") # Self-Documenting Debugging Syntax (Python 3.8+) x, y = 10, 25 print(f"Debug evaluation: {x + y = }") # Output: Debug evaluation: x + y = 35

4. Legacy String Formatting Comparison

Understanding legacy formatting methods helps when maintaining older codebases or constructing system logs.

# Method 1: %-Formatting (C-style Printf) name = "Alice" score = 94.5 print("User %s scored %.1f points." % (name, score)) # Method 2: str.format() Method print("User {} scored {:.1f} points.".format(name, score)) print("User {1} scored {0} points.".format(score, name)) # Positional Indexing

πŸ‹οΈ Try It Yourself: Practice Challenges

Challenge 1: Formatted Invoice Table Generator

Write a script using f-strings to print a structured invoice receipt table with items, quantity, unit price, tax, and aligned total amounts.

Challenge 2: Robust Space-Separated Array Reader

Use input().split() with list comprehension to convert a space-separated sequence of numbers into floats and output their average rounded to 2 decimal places.

Challenge 3: Terminal Progress Animation Stream

Create a single-line terminal progress bar using print() with end="\r" and flush=True to update progress without starting a new line.

⚑ Interactive Sandbox (I/O Stream Engine)
Console Output:
Click "Run Code" above to execute interactive input scripts...

πŸ“ Knowledge Check Quiz

1. What is the default return type of the `input()` function in Python?
2. Which `print()` parameter prevents printing a new line at the end of output?
3. What does expression `f"{1234567:,.2f}"` output?
Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)