Python · Module 01: Getting Started & How Python ThinksTutorial 3 of 30

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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").
PYTHON
# 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 { }:

Visual: Anatomy of a Modern Python f-String
f"Hi {name}, total is ${price * qty:.2f}"f-prefixTurns on { }Variable Plug-InInserts value of nameLive ExpressionRuns math inside { }!Format Specifier (:.2f)Rounds to 2 decimals → 19.50
PYTHON
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 SpecifierExample (x = 1234.5678)OutputMeaning
{x:.2f}f"{x:.2f}"1234.57Fixed 2 decimal places (rounded)
{x:,.2f}f"{x:,.2f}"1,234.57Adds thousand-separator commas
{n:04d}f"{7:04d}"0007Zero-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 types 25!

Visual: The #1 Fresher Trap — `input()` Always Gives Text (`str`), Never a Number!
✗ Without int(): String Glue BugUser types 25age = "25" (str)→"25" + "5" = "255" !!→And "25" + 5 crashes withTypeError!✓ With int(input()): Real Math WorksRaw keyboard text"25" (str)→int("25")25 (int)→25 + 5 = 30 ✓

Type Casting Functions (int(), float(), str(), bool())

To do math on user input, explicitly convert (cast) the text into a number:

PYTHON
# 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:

PYTHON
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:

Tracing a Mini Bill-Splitter Program
Interactive Line-by-Line Execution Trace · Step 1 of 5
1→raw_bill = "650.50" # simulating input()
2bill = float(raw_bill)
3people = int("4")
4per_person = bill / people
5print(f"Each pays: {per_person:.2f}")
Variables in Memory
raw_bill"650.50"str
Console Output
(nothing printed yet)
What just happened: input() always gives back a string (str). Notice the quotes around "650.50".

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.
PYTHON
"""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

Q1.A user types 10 when asked for `num = input()`. What does `print(num + num)` output?
Q2.What does this code print?
print("A", "B", "C", sep="-", end="!")
Q3.Which f-string formats `pi = 3.14159` as `3.14`?

Keep Exploring: Related Lessons & Tools

All Courses →