Logo OnlineCBT
PYTHON Tutorial
PYTHON · LESSON 9

Input, Output and f-Strings

Accept console input, validate its expected shape, and present readable results with modern formatted string literals.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive
Updated: 26 Jul 2026

Lesson 9: Input, Output and f-Strings

1. The Fundamentals of Program Input and Output (I/O)

Every interactive software application relies on the Input-Process-Output (IPO) model. A program captures data from an external source (such as terminal user keyboard entry), processes that data in memory, and produces formatted results sent to an output destination (such as the standard terminal console).

In Python, standard console input is managed using the built-in input() function, while standard console output is handled using print(). To bridge input and output seamlessly, Python provides modern dynamic formatting features known as f-Strings (Formatted String Literals).


2. Deep Dive: Terminal Input with `input()`

1. Mechanics of the `input()` Function

When Python encounters the input([prompt]) function, execution pauses and waits for the user to type text into the terminal console. When the user presses Enter, input() reads all characters typed, discards the trailing newline character, and returns the entered value.

The Golden Rule of `input()`: The input() function ALWAYS returns user input as a String (str) data type. Even if the user types numeric digits (e.g., "25" or "99.99"), Python receives it as text.

2. Type Casting User Input

Because input arrives as a string, attempting arithmetic directly on user input triggers a TypeError. You must wrap input() inside explicit type-casting functions like int() or float() before executing math.

INPUT_CASTING_DEMO.PY
# Simulating console inputs
user_age_str = "24"
hourly_rate_str = "35.50"

# Explicit conversion to numerical types
age = int(user_age_str)
hourly_rate = float(hourly_rate_str)

# Performing calculations on converted values
age_in_five_years = age + 5
weekly_pay = hourly_rate * 40

print("Age in 5 Years:", age_in_five_years)
print("Weekly Pay:", weekly_pay)
OUTPUT
Age in 5 Years: 29
Weekly Pay: 1420.0

3. Multi-Value Input Parsing (`.split()`)

To capture multiple user inputs in a single line (e.g., entering two numbers separated by spaces), combine input() with the string .split() method:

MULTI_INPUT.PY
# Simulating input string "10 20"
raw_input_line = "10 20"

# Splitting string into list of strings and unpacking
str_a, str_b = raw_input_line.split()
a, b = int(str_a), int(str_b)

print(f"a = {a}, b = {b}, Sum = {a + b}")
OUTPUT            
a = 10, b = 20, Sum = 30
        

3. Advanced Console Output Control with `print()`

The built-in print() function writes output to standard system output (usually the terminal). Understanding its full parameter signature enables precise console formatting.

Signature of `print()`

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Parameters Breakdown:

  • `*objects`: Zero or more comma-separated values to print. Objects are converted to strings automatically.
  • `sep` (Separator): Specifies the string placed between comma-separated objects. Defaults to a single space (' ').
  • `end` (Line Termination): Specifies the string appended at the end of output. Defaults to a newline ('\n').
  • `flush` (Buffer Control): Forces Python to flush its stdout buffer immediately when set to True (useful for progress bars and real-time terminal output).
PRINT_PARAMETERS.PY
# Custom Separators
print("2026", "07", "26", sep="-")
print("user", "domain.com", sep="@")

# Custom End Characters (preventing line breaks)
print("Loading system", end="... ")
print("100% Complete!")
OUTPUT
2026-07-26
user@domain.com
Loading system... 100% Complete!

4. Evolution of String Formatting in Python

To construct dynamic strings containing variable data, Python has supported three generations of string formatting techniques:

1. Legacy `%` Formatting (C-style Printf)

Uses conversion specifiers like %s (string) and %d (integer). Considered outdated in modern Python:

name = "Alice"; age = 25
print("Hello %s, you are %d years old." % (name, age))

2. `str.format()` Method (Python 2.7+ / 3.0+)

Uses curly braces {} as replacement fields:

print("Hello {}, you are {} years old.".format(name, age))

3. f-Strings (Formatted String Literals - Python 3.6+)

Introduced in Python 3.6 via PEP 498, f-Strings are prefixed with an f or F before the opening quote. Variables and expressions enclosed in curly braces {expression} are evaluated dynamically at runtime.

Why f-Strings Win: f-Strings are cleaner, easier to read, and significantly faster than % formatting or .format() because they are parsed at bytecode compilation time rather than interpreted purely at runtime.

5. Mastering f-Strings: Expressions and Inline Logic

f-Strings do not just substitute variables—they can evaluate arbitrary Python expressions, function calls, arithmetic operations, and method calls directly inside the replacement fields {}.

FSTRING_EXPRESSIONS.PY
product = "wireless keyboard"
price = 45.00
quantity = 3

# Inline arithmetic and method calls inside f-Strings
print(f"Product: {product.title()}")
print(f"Total Cost: ${price * quantity}")
print(f"Is Bulk Order? {quantity >= 5}")
OUTPUT
Product: Wireless Keyboard
Total Cost: $135.0
Is Bulk Order? False

The Self-Documenting Debug Specifier (`=`)

Introduced in Python 3.8, adding an equal sign (=) inside a replacement field prints both the expression text and its evaluated value. This is extremely useful for debugging!

FSTRING_DEBUG.PY
x = 10
y = 25

# Quick debugging with =
print(f"{x=}")
print(f"{y=}")
print(f"{x + y=}")
OUTPUT
x=10
y=25
x + y=35

6. Complete Reference: Format Specifiers in f-Strings

Format specifiers control precision, alignment, field width, thousand separators, and numeric padding. A format specifier is added after a colon : inside the curly braces: {expression:format_specifier}.

1. Floating-Point Precision Rounding

Use :.nf to round floating-point numbers to $n$ decimal places:

pi = 3.1415926535
print(f"Pi (2 decimals): {pi:.2f}")  # Outputs: 3.14
print(f"Pi (4 decimals): {pi:.4f}")  # Outputs: 3.1416
    

2. Thousand Separators and Currency Formatting

Use a comma :, or underscore :_ to format large numbers with readable thousand separators:

FORMAT_NUMBERS.PY
revenue = 1250000.758

# Comma separator combined with 2 decimal place rounding
print(f"Formatted Revenue: ${revenue:,.2f}")

# Percentage formatting (.2%)
pass_rate = 0.8745
print(f"Pass Rate: {pass_rate:.1%}")
OUTPUT
Formatted Revenue: $1,250,000.76
Pass Rate: 87.5%

3. Field Padding and Alignment Options

Format specifiers allow aligning text within a fixed field width:

  • :<10
  • Left-aligned (Default for strings)
  • f'{"Py":<10}'
  • 'Py '
  • :>10
  • Right-aligned (Default for numbers)
  • f'{"Py":>10}'
  • ' Py'
  • :^10
  • Center-aligned
  • f'{"Py":^10}'
  • ' Py '
  • :*^10
  • Center-aligned with custom fill char (*)
  • f'{"Py":*^10}'
  • '***Py*****'
Specifier Alignment Meaning Example Expression Result (Width 10)

4. Table Formatting Code Demonstration

TABLE_FORMATTING.PY
# Formatted Console Table Output
print(f"{'ITEM':<15} | {'QTY':^5} | {'PRICE':>10}")
print("-" * 36)
print(f"{'Monitor':<15} | {2:^5} | ${299.99:>9.2f}")
print(f"{'USB Cable':<15} | {10:^5} | ${12.50:>9.2f}")
print(f"{'Gaming Mouse':<15} | {1:^5} | ${79.00:>9.2f}")
OUTPUT
ITEM            |  QTY  |      PRICE
------------------------------------
Monitor         |   2   | $   299.99
USB Cable       |  10   | $    12.50
Gaming Mouse    |   1   | $    79.00

7. Escaping Curly Braces in f-Strings

If you need to print a literal curly brace { or } inside an f-String (such as generating JSON data or CSS rules), double the curly braces: {{ and }}.

ESCAPE_BRACES.PY
user_id = 101
# Doubled braces output literal { }
json_output = f'{{"status": 200, "user_id": {user_id}}}'
print(json_output)
OUTPUT
{"status": 200, "user_id": 101}

8. Frequently Asked Interview Questions with Answers

Q1: Why does `input()` always return a string, and how do you handle numeric inputs safely?
Answer: input() captures raw keystrokes from standard input (stdin) as a stream of text characters. To handle numeric values, wrap input() in explicit type-casting functions (e.g., int(input()) or float(input())) and handle conversion errors using try-except blocks.
Q2: What are the performance and readability advantages of f-Strings over `%` formatting and `.format()`?
Answer: f-Strings are evaluated at bytecode compilation time rather than runtime, making them substantially faster than .format() or % formatting. They improve readability by placing expressions directly inside replacement fields near the text context.
Q3: How does the debug specifier `{var=}` work in f-Strings?
Answer: Introduced in Python 3.8, appending an equal sign (=) inside an f-String replacement field prints both the literal expression text and its evaluated value (e.g., f"{x=}" outputs "x=10").
Q4: How do you format a float as currency with commas and 2 decimal places in an f-String?
Answer: Use the format specifier :,.2f (e.g., f"${amount:,.2f}" converts 1250000.5 into "$1,250,000.50").
Q5: How do you include literal curly braces `{}` inside an f-String output?
Answer: Double the curly braces: {{ produces a literal {, and }} produces a literal } in the output string.

9. Homework & Practical Assignment

Task 1: Console Receipt Generator

Create a script named receipt_generator.py inside your lesson_09 directory:

  • Prompt the user to enter a store name, item name, price (float), and quantity (int).
  • Calculate subtotal, tax (8%), and final total.
  • Print a cleanly formatted console receipt using field padding alignments (:<15, :>10) and currency format specifiers (:,.2f).

Task 2: Temperature Converter with Formatted Output

Create a script named temp_converter.py:

  • Prompt the user for a temperature in Celsius (float).
  • Convert to Fahrenheit ($F = C \times \frac{9}{5} + 32$) and Kelvin ($K = C + 273.15$).
  • Print results using f-Strings rounded to 1 decimal place.

Task 3: Debug Log Formatter

Write a script named debug_formatter.py that defines three system state variables (status_code = 200, latency_ms = 45.289, user_count = 1450) and prints a formatted log string using the {var=} debug feature and comma separators.


10. File & Workspace Directory Structure

Standard Course Workspace Layout:

Ensure all exercise files are stored inside their corresponding lesson directories:

python_mastery_course/
│
├── lesson_01/
├── lesson_02/
├── lesson_03/
├── lesson_04/
├── lesson_05/
├── lesson_06/
├── lesson_07/
├── lesson_08/
│
└── lesson_09/
    ├── input_casting_demo.py
    ├── multi_input.py
    ├── print_parameters.py
    ├── fstring_expressions.py
    ├── fstring_debug.py
    ├── format_numbers.py
    ├── table_formatting.py
    ├── escape_braces.py
    ├── receipt_generator.py
    ├── temp_converter.py
    └── debug_formatter.py
        

11. What We Will Learn Next

Next Up: Lesson 10 — Booleans, Comparisons and Logical Operators

Now that you master user terminal input and advanced output formatting, we will transition into conditional logic and program decision-making.

In the next lesson, we will cover:

  • The Boolean Data Type (bool) and underlying integer subclassing.
  • Comparison Operators (==, !=, >, <, >=, <=).
  • Logical Operators (and, 0or, not) and Short-Circuit Evaluation behavior.
  • Truth Value Testing (Truthy vs Falsy objects in Python).
  • Identity Operators (is, is not) vs Equality Operators (==, !=).

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat