1.3 Input, Output (print), f-Strings & Type Casting
Make your Python programs interactive! Master print() formatting, modern f-strings, reading user input safely with type casting, and writing clear comments.
1. Talking to the User: Mastering print()
Every program needs two things: a way to receive data (Input) and a way to show results (Output). Think of print() as your program's speaker and input() as its microphone.
Most beginners only know print("Hello"), but print() has two super useful hidden controls:
sep— what goes between multiple items (default is a single space" ").end— what goes at the end of the line (default is a newline"\n").
# Default behavior: space between items, newline at the end
print("2026", "11", "20")
# Output: 2026 11 20
# Custom separator (sep)
print("2026", "11", "20", sep="-")
# Output: 2026-11-20
# Custom line ending (end) — keeps the next print on the SAME line!
print("Loading", end="...")
print("Done!")
# Output: Loading...Done!
2. Modern String Formatting: f-Strings (Python 3.6+)
Never glue variables and text together with messy + signs and str(...) calls. Modern Python gives you f-strings (formatted string literals) — just put an f right before the opening quote and drop any variable or expression inside { }:
name = "Riya"
price = 49.5
qty = 3
# Clean, fast, and readable!
print(f"Hi {name}, your total is ${price * qty:.2f}")
# Output: Hi Riya, your total is $148.50
# Bonus: Debugging trick with = (Python 3.8+)
print(f"{price=}, {qty=}")
# Output: price=49.5, qty=3
| Format Specifier | Example (x = 1234.5678) | Output | Meaning |
|---|---|---|---|
{x:.2f} | f"{x:.2f}" | 1234.57 | Fixed 2 decimal places (rounded) |
{x:,.2f} | f"{x:,.2f}" | 1,234.57 | Adds thousand-separator commas |
{n:04d} | f"{7:04d}" | 0007 | Zero-pads integer to 4 digits |
{p:.1%} | f"{0.856:.1%}" | 85.6% | Converts decimal to percentage |
3. Reading Keyboard Input & The #1 Fresher Trap
The input("prompt") function pauses your program, waits for the user to type something and press Enter, and returns what they typed.
Here is the #1 bug almost every Python fresher hits on Day 1:
input()ALWAYS returns a string (str) — even if the user types25!
Type Casting Functions (int(), float(), str(), bool())
To do math on user input, explicitly convert (cast) the text into a number:
# Step 1: Read text from keyboard
raw_age = input("Enter your age: ") # e.g. user types 25 -> "25" (str)
# Step 2: Convert text to integer
age = int(raw_age) # 25 (int)
# Step 3: Now math works!
print(f"In 5 years, you will be {age + 5} years old.")
You can also combine Steps 1 & 2 into a single clean line:
price = float(input("Enter item price: "))
tax = price * 0.18
print(f"Total with 18% tax: {price + tax:.2f}")
Watch Out for ValueError: If a user types "abc" into int("abc"), Python cannot turn letters into a number and raises a ValueError. (In Module 6, you will learn how to catch that gracefully with try / except!)
4. Interactive Trace: Input, Casting & f-String Output
Click Next to trace how a mini Bill-Splitter program converts raw text input into numbers and formats the final output:
5. Comments & Docstrings (Notes for Future You)
Comments are ignored by Python — they exist for humans reading your code 6 months later.
- Single-line comment: Start with
#. Explain why, not the obvious what. - Docstring: Triple quotes
"""..."""placed at the top of a file or function to document its purpose.
"""Calculates discounted order total for checkout."""
# Apply 10% loyalty discount only for orders above $50 (business rule #42)
discount_rate = 0.10
Quick Quiz: Module 1.3 — Input, Output & Type Casting
print("A", "B", "C", sep="-", end="!")Keep Exploring: Related Lessons & Tools
All Courses →Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.