Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 02 / Stage 1

Language fundamentals

Goal: Store data in variables, work with numbers, text and booleans, take input, and print clean output with f-strings. Time: ~1 hour

What you will learn

  • Variables and memory: names, objects, id(), is vs ==, mutable vs immutable
  • Numbers: int, float, complex, //, %, **, round(), float precision
  • Strings: indexing, slicing, common methods, immutability
  • Booleans, None and truthiness
  • Operators: arithmetic, comparison, logical, assignment, membership, identity, bitwise, precedence
  • Type casting: int(), float(), str(), bool()
  • input() (it always returns a string)
  • f-strings: decimals, commas, alignment, {x=}
  • Number systems: binary, octal, hex

Topics in this part

Practice

Python workbench — write and run code here

Press Run and Python 3.14 loads right in your browser (a one-time download of about 15 MB; after that it works offline). Your code never leaves this page. input() opens a small prompt window.

Try each one yourself first. Then check the solution. Tip: put your logic in a small function (see the def pattern in README section 7; full lesson in Part 5) and call it with fixed values. Add input() only at the end, if you want. No loops yet (Part 3): when you need several results, just call the function a few times.


Exercise 1: Weather app converter

Scenario: A weather app shows temperature in both °C and °F. What to do: Write c_to_f(celsius) using F = C × 9/5 + 32. Print the result for Delhi (41.5), Shimla (8.0) and Chennai (33.2) with 1 decimal place.

Sample output:

Delhi: 41.5°C = 106.7°F
Shimla: 8.0°C = 46.4°F
Chennai: 33.2°C = 91.8°F

💡 Hint: f"{value:.1f}".


Show the solution to Exercise 1
"""Exercise 1: Weather app temperature converter.

Run: python ex01.py   (macOS/Linux: python3 ex01.py)
"""


def c_to_f(celsius: float) -> float:
    """Convert °C to °F."""
    return celsius * 9 / 5 + 32


print(f"Delhi: {41.5:.1f}°C = {c_to_f(41.5):.1f}°F")
print(f"Shimla: {8.0:.1f}°C = {c_to_f(8.0):.1f}°F")
print(f"Chennai: {33.2:.1f}°C = {c_to_f(33.2):.1f}°F")

# Interactive version:
# print(f"{c_to_f(float(input('Temp in °C: '))):.1f}°F")

Exercise 2: Conference name badge

Scenario: Names come from a sign-up form with extra spaces and mixed case. What to do: Write make_badge(full_name, city) that returns: initials in brackets, first name in CAPS, last name in Title case, and the first 3 letters of the city in CAPS.

Sample output:

make_badge("  ananya iyer ", "chennai")   ->  [AI] ANANYA Iyer · CHE
make_badge("vikram singh", "Hyderabad")   ->  [VS] VIKRAM Singh · HYD

💡 Hint: strip(), title(), then first, last = clean.split() (split gives two words; unpack them like a swap). Then indexing [0], slicing [:3], upper().


Show the solution to Exercise 2
"""Exercise 2: Conference name badge.

Run: python ex02.py   (macOS/Linux: python3 ex02.py)
"""


def make_badge(full_name: str, city: str) -> str:
    """Build a badge like '[AI] ANANYA Iyer · CHE'."""
    clean = full_name.strip().title()
    first, last = clean.split()      # split() gives two words; unpack them
    initials = first[0] + last[0]
    city_code = city.strip()[:3].upper()
    return f"[{initials}] {first.upper()} {last} · {city_code}"


# Show the call on the left, like the sample output
print('make_badge("  ananya iyer ", "chennai")   -> ',
      make_badge("  ananya iyer ", "chennai"))
print('make_badge("vikram singh", "Hyderabad")   -> ',
      make_badge("vikram singh", "Hyderabad"))

Exercise 3: Predict the output

Scenario: Your senior asks you this in an interview. What to do: Without running it, write down what each print shows. Then run it and check.

a = [10, 20]
b = a
c = [10, 20]
b.append(30)
print(a)
print(a == c)
print(a is b)

x = "chai"
y = x
x = x + " latte"
print(y)

p, q = 1, 2
p, q = q, p
print(p, q)

Sample output: (write your answer first, then open this)

Show the output
[10, 20, 30]
False
True
chai
2 1

💡 Hint: [10, 20] is a list (Part 4) and .append(30) adds an item to it. Lists are mutable and b = a does not copy. Strings are immutable.


Show the solution to Exercise 3
"""Exercise 3: Predict the output (== vs is, mutable vs immutable).

Run: python ex03.py   (macOS/Linux: python3 ex03.py)
Note: [...] is a list (Part 4); .append() adds an item to it.
"""

a = [10, 20]
b = a
c = [10, 20]
b.append(30)

print(a)          # [10, 20, 30]  -> b and a are the same list
print(a == c)     # False         -> values differ now ([10, 20, 30] vs [10, 20])
print(a is b)     # True          -> same object

x = "chai"
y = x
x = x + " latte"
print(y)          # chai          -> strings are immutable, y still points to "chai"

p, q = 1, 2
p, q = q, p
print(p, q)       # 2 1

Exercise 4: Movie running time

Scenario: A ticket app stores movie length in minutes but shows it as 3h 44m. What to do: Write format_minutes(total_minutes) that returns a string like 3h 44m. Minutes must always show 2 digits (0h 05m).

Sample output:

format_minutes(224)  ->  3h 44m
format_minutes(170)  ->  2h 50m
format_minutes(45)   ->  0h 45m
format_minutes(5)    ->  0h 05m

💡 Hint: // gives hours, % gives minutes left. Use {minutes:02d}.


Show the solution to Exercise 4
"""Exercise 4: Movie running time formatter.

Run: python ex04.py   (macOS/Linux: python3 ex04.py)
"""


def format_minutes(total_minutes: int) -> str:
    """Turn minutes into text like '3h 44m'."""
    hours = total_minutes // 60
    minutes = total_minutes % 60
    return f"{hours}h {minutes:02d}m"


print("format_minutes(224)  -> ", format_minutes(224))
print("format_minutes(170)  -> ", format_minutes(170))
print("format_minutes(45)   -> ", format_minutes(45))
print("format_minutes(5)    -> ", format_minutes(5))

Exercise 5: Username cleaner

Scenario: A college portal makes usernames from what students type. What to do: Write clean_username(raw): remove spaces at the ends, make it lowercase, replace inner spaces with _. If nothing is left, return "Invalid username".

Sample output:

'  Rohit Kumar '   -> rohit_kumar
'SNEHA'            -> sneha
'   '              -> Invalid username
'dev ops team'     -> dev_ops_team

💡 Hint: An empty string is falsy, so if not name: return "Invalid username" catches it (if is taught fully in Part 3). f"{raw!r}" prints a string with its quotes, so you can see the spaces.


Show the solution to Exercise 5
"""Exercise 5: Username cleaner.

Run: python ex05.py   (macOS/Linux: python3 ex05.py)
Note: `if` is taught fully in Part 3; here it only checks for an empty string.
"""


def clean_username(raw: str) -> str:
    """Make a clean username, or return 'Invalid username'."""
    name = raw.strip().lower().replace(" ", "_")
    if not name:              # empty string is falsy
        return "Invalid username"
    return name


print(f"{'  Rohit Kumar '!r:<18} -> {clean_username('  Rohit Kumar ')}")
print(f"{'SNEHA'!r:<18} -> {clean_username('SNEHA')}")
print(f"{'   '!r:<18} -> {clean_username('   ')}")
print(f"{'dev ops team'!r:<18} -> {clean_username('dev ops team')}")

Exercise 6: Kirana store receipt

Scenario: A local shop wants a printed receipt with neat columns. What to do: The prices are Rice ₹649.00, Dal ₹165.50, Butter ₹56.00. For each item, print name (left, 18 wide), quantity (right, 4 wide) and amount = qty × price (right, 12 wide, 2 decimals, with commas). Then print the total. (The amounts form a right-aligned column, so the ₹ sign goes in the Total (₹) label, not next to each number.)

Sample output:

Item               Qty      Amount
----------------------------------
Basmati Rice 5kg     1      649.00
Toor Dal 1kg         2      331.00
Amul Butter          3      168.00
----------------------------------
Total (₹)                 1,148.00

💡 Hint: One variable per amount (rice_amount = 1 * 649.00 ...), add them for the total, then one print per row: f"{'Toor Dal 1kg':<18}{dal_qty:>4}{dal_amount:>12,.2f}".


Show the solution to Exercise 6
"""Exercise 6: Kirana store receipt with aligned columns.

Run: python ex06.py   (macOS/Linux: python3 ex06.py)
"""

rice_qty, rice_price = 1, 649.00
dal_qty, dal_price = 2, 165.50
butter_qty, butter_price = 3, 56.00

rice_amount = rice_qty * rice_price
dal_amount = dal_qty * dal_price
butter_amount = butter_qty * butter_price
total = rice_amount + dal_amount + butter_amount

print(f"{'Item':<18}{'Qty':>4}{'Amount':>12}")
print("-" * 34)
print(f"{'Basmati Rice 5kg':<18}{rice_qty:>4}{rice_amount:>12,.2f}")
print(f"{'Toor Dal 1kg':<18}{dal_qty:>4}{dal_amount:>12,.2f}")
print(f"{'Amul Butter':<18}{butter_qty:>4}{butter_amount:>12,.2f}")
print("-" * 34)
# Amounts are a right-aligned column, so ₹ goes in the label, not before each number
print(f"{'Total (₹)':<22}{total:>12,.2f}")

Exercise 7: Fair bill splitter (no paisa lost)

Scenario: Three friends eat for ₹1,000. Add 5% GST and 10% tip. The total is ₹1,150.00, which does not split evenly into 3. Nobody should lose or gain a paisa. What to do: Write fair_split(subtotal, tip_percent) for Aman, Bela and Chetan. Convert the total to paise (an int). Use // for each share and % for the leftover paise. Give 1 extra paisa to the first few people until the leftover is used up.

Sample output:

Subtotal: ₹1,000.00 | GST 5% + tip 10%
Total   : ₹1,150.00
  Aman     pays ₹383.34
  Bela     pays ₹383.33
  Chetan   pays ₹383.33

💡 Hint: total_paise = round(total * 100). Then share, extra = total_paise // 3, total_paise % 3. extra is 0, 1 or 2, and True counts as 1, so aman = share + (extra >= 1) and bela = share + (extra >= 2).


Show the solution to Exercise 7
"""Exercise 7: Fair bill splitter (no paisa lost).

Run: python ex07.py   (macOS/Linux: python3 ex07.py)
"""

GST_RATE = 0.05


def fair_split(subtotal: float, tip_percent: float) -> None:
    """Split the bill between Aman, Bela and Chetan, down to the paisa."""
    total = subtotal * (1 + GST_RATE + tip_percent / 100)
    total_paise = round(total * 100)          # whole paise: no float errors
    share, extra = total_paise // 3, total_paise % 3   # extra is 0, 1 or 2

    # A comparison is True (1) or False (0), so it adds 1 paisa only when needed
    aman = share + (extra >= 1)
    bela = share + (extra >= 2)
    chetan = share                             # extra is never 3 or more

    print(f"Subtotal: ₹{subtotal:,.2f} | GST 5% + tip {tip_percent}%")
    print(f"Total   : ₹{total_paise / 100:,.2f}")
    print(f"  {'Aman':<8} pays ₹{aman / 100:,.2f}")
    print(f"  {'Bela':<8} pays ₹{bela / 100:,.2f}")
    print(f"  {'Chetan':<8} pays ₹{chetan / 100:,.2f}")


fair_split(1000, 10)

Exercise 8: Number system table

Scenario: You are learning how computers store numbers and want a cheat sheet. What to do: Print a table of 0, 7, 10, 15 and 255 in decimal, binary, octal and hex (uppercase), right-aligned. Then convert "1111" (binary), "17" (octal) and "F" (hex) back to int.

Sample output:

 Dec      Bin  Oct  Hex
-----------------------
   0        0    0    0
   7      111    7    7
  10     1010   12    A
  15     1111   17    F
 255 11111111  377   FF

int('1111', 2) = 15
int('17', 8)   = 15
int('F', 16)   = 15

💡 Hint: f-string specs b, o, X (e.g. f"{10:>8b}") and int(text, base). One print per row is fine; in Part 3 you will do all rows with a loop.

Show the solution to Exercise 8
"""Exercise 8: Number system table.

Run: python ex08.py   (macOS/Linux: python3 ex08.py)
(In Part 3 you will print all rows 0 to 15 with a loop.)
"""

print(f"{'Dec':>4} {'Bin':>8} {'Oct':>4} {'Hex':>4}")
print("-" * 23)
print(f"{0:>4} {0:>8b} {0:>4o} {0:>4X}")
print(f"{7:>4} {7:>8b} {7:>4o} {7:>4X}")
print(f"{10:>4} {10:>8b} {10:>4o} {10:>4X}")
print(f"{15:>4} {15:>8b} {15:>4o} {15:>4X}")
print(f"{255:>4} {255:>8b} {255:>4o} {255:>4X}")

# And back from text to int
print("\nint('1111', 2) =", int("1111", 2))
print("int('17', 8)   =", int("17", 8))
print("int('F', 16)   =", int("F", 16))

Common mistakes

Mistake Why it is wrong Fix
age = input("Age: ") then age + 1 input() returns str → TypeError age = int(input("Age: "))
"Total: " + 500 Cannot add str and int f"Total: {500}" or "Total: " + str(500)
if x is 5: is checks identity, not value if x == 5: (use is only for None)
0.1 + 0.2 == 0.3 Float precision math.isclose(...) or round(..., 2)
name[0] = "R" Strings are immutable name = "R" + name[1:]
int("3.5") Not a whole-number string → ValueError int(float("3.5"))
b = a for a list, then changing b Both names point to the same list b = a.copy()
true, none Python is case-sensitive True, None

Quick recap

  • Variables are names pointing to objects; == compares values, is compares identity.
  • int, str, tuple are immutable; list, dict, set are mutable.
  • / gives float, // floor-divides, % is remainder, ** is power.
  • Floats are not exact: 0.1 + 0.2 is not 0.3.
  • Strings use indexes and slices [start:end:step]; methods return new strings.
  • Empty values, 0 and None are falsy; most others are truthy.
  • input() always gives a string; cast with int() / float().
  • f-strings: {x:.2f}, {x:,}, {x:>10}, {x=}.

Checklist

  • I can explain the difference between == and is.
  • I know which types are mutable and which are immutable.
  • I can use //, %, ** and round() correctly.
  • I can slice a string and use split, join, strip, replace.
  • I can predict if a value is truthy or falsy.
  • I can cast between int, float, str and bool.
  • I always convert input() before doing maths.
  • I can format money with f-strings like ₹{x:,.2f}.

Search the guide