Python HOW A PROGRAM WORKS: values, variables, arithmetic, print: 10 practice problems
PREREQUISITE 0 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.
▶ Practise HOW A PROGRAM WORKS: values, variables, arithmetic, print nowAll topicsTheory: HOW A PROGRAM WORKS: values, variables, arithmetic, print in Python
(Needed before Unit 1. Watch: Mosh 1-hour video, first 20 minutes.)
THEORY
------
* A PROGRAM is a list of instructions the computer runs top to bottom.
Python is INTERPRETED: the interpreter reads your .py file and runs it line by line
(it first compiles it to "bytecode" internally — just like your MiniLang compiler!).
* VALUES & VARIABLES
age = 21 # the name `age` now refers to the value 21
age = age + 1 # read the old value, compute, re-bind the name -> 22
A variable is a LABEL stuck on a value, not a box. No declarations, no types written.
* ARITHMETIC OPERATORS
+ - * add, subtract, multiply
/ TRUE division, ALWAYS gives a float: 7 / 2 -> 3.5, 6 / 2 -> 3.0
// FLOOR division (rounds DOWN): 7 // 2 -> 3, -7 // 2 -> -4
% REMAINDER (modulo): 7 % 2 -> 1 (even test: n % 2 == 0)
** POWER: 2 ** 10 -> 1024, 9 ** 0.5 -> 3.0
The // and % pair splits things into units: 125 seconds -> 125 // 60 = 2 min, 125 % 60 = 5 s
* USEFUL BUILT-IN FUNCTIONS
print(x, y, sep=" ", end="\n") show values input("prompt") -> ALWAYS a str
round(3.14159, 2) -> 3.14 abs(-5) -> 5 min(3, 7) -> 3 max(3, 7) -> 7
int("42") -> 42 float("2.5") -> 2.5 str(99) -> "99" type(3.0) -> <class 'float'>
* F-STRINGS (formatting output)
name, price = "Pen", 5
f"{name} costs Rs.{price:.2f}" -> "Pen costs Rs.5.00"
f"{7:02d}" -> "07" (pad with zeros to width 2)
* RETURN vs PRINT — in these exercises you write FUNCTIONS that RETURN answers.
def double(n):
return n * 2 # the caller receives the value; print would only show it
HOW TO USE THIS FILE: replace each `raise NotImplementedError` with your code, then press ▶
(or run `python practice/00_prereq_basics.py`). The judge shows ✅ / ❌ / 💥 for each problem.
10 HOW A PROGRAM WORKS: values, variables, arithmetic, print practice problems
1. Video Duration Display — // and %
Easy2 ways to solve📤 OUTPUT: return a str (text), e.g. '1:02:05'. Use `return`, not print().
Real world: YouTube shows a video's length as H:MM:SS.
Convert a number of seconds into the string "H:MM:SS" (minutes & seconds always 2 digits).
seconds_to_hms(3725) -> "1:02:05"
seconds_to_hms(59) -> "0:00:59"
Constraints: 0 <= seconds < 360000
Solve “Video Duration Display — // and %” in your browser →2. Restaurant Bill Splitter — arithmetic, round
Easy1 way to solve📤 OUTPUT: return a float, e.g. 275.0. Use `return`, not print().
Real world: Friends split a dinner bill including a tip.
Add tip_percent% to total, divide equally, return each share rounded to 2 decimals.
split_bill(1000, 4, 10) -> 275.0
split_bill(999, 3, 0) -> 333.0
Solve “Restaurant Bill Splitter — arithmetic, round” in your browser →3. Bank Interest — formula translation
Easy1 way to solve📤 OUTPUT: return a float, e.g. 11500.0. Use `return`, not print().
Real world: A bank shows how much interest your FD earns.
SI = P * R * T / 100. Return the TOTAL amount (principal + interest) rounded to 2.
simple_interest(10000, 7.5, 2) -> 11500.0
Solve “Bank Interest — formula translation” in your browser →4. Fitness App BMI — unit conversion, **
Easy2 ways to solve📤 OUTPUT: return a float, e.g. 22.9. Use `return`, not print().
BMI = weight(kg) / height(m)^2. Height is given in CENTIMETRES. Round to 1 decimal.
bmi(70, 175) -> 22.9
Solve “Fitness App BMI — unit conversion, **” in your browser →5. ATM Note Dispenser — // and % chains
Medium2 ways to solve📤 OUTPUT: return a list, e.g. [3, 1, 1]. Use `return`, not print().
Real world: An ATM gives the FEWEST notes possible using 500, 200, 100 notes.
Return a list [count_500, count_200, count_100]. amount is always a multiple of 100.
atm_notes(1800) -> [3, 1, 1]
atm_notes(100) -> [0, 0, 1]
Viva follow-up: why does a greedy approach work for these notes?
Solve “ATM Note Dispenser — // and % chains” in your browser →6. Even or Odd — %
Easy2 ways to solve📤 OUTPUT: return a bool (True / False), e.g. True. Use `return`, not print().
Return True if n is even, else False (a real bool).
is_even(10) -> True is_even(-3) -> False
Solve “Even or Odd — %” in your browser →7. Average Marks — precedence trap!
Easy1 way to solve📤 OUTPUT: return a float, e.g. 81.67. Use `return`, not print().
Return the average rounded to 2 decimals. (a + b + c / 3 is WRONG — why?)
average_of_three(80, 90, 75) -> 81.67
Solve “Average Marks — precedence trap!” in your browser →8. Alarm Clock — modular arithmetic
Medium3 ways to solve📤 OUTPUT: return a str (text), e.g. '00:45'. Use `return`, not print().
Real world: "Remind me in 135 minutes" — what time will it show?
Given a 24-hour time and minutes to add, return the new time as "HH:MM" (wraps past midnight).
time_after(22, 30, 135) -> "00:45"
time_after(9, 5, 0) -> "09:05"
Hint: convert everything to minutes since midnight, then use % (24 * 60).
Solve “Alarm Clock — modular arithmetic” in your browser →9. Food-Delivery Quote Engine — interview at a food-delivery startup
Project1 way to solve📤 OUTPUT: return a dict, e.g. {'fare': 25.0, 'eta_min': 21, 'eta_text': '21 …. Use `return`, not print().
Interviewer: "Before the customer taps Order, the app shows the fare and the ETA. Build that."
Rules:
fare = 25 + 8 per km BEYOND the first 2 km (proportional: 3.5 km -> 25 + 8 * 1.5)
raining -> fare + 20%. Round the fare to 2 decimals.
eta_min = prep_min + ceil(distance_km * 4) (4 min per km; ceiling WITHOUT math.ceil), +10 if raining
eta_text: under 60 -> "44 min"; otherwise -> "1 h 05 min" (minutes always 2 digits)
Return {"fare": float, "eta_min": int, "eta_text": str}
delivery_quote(3.5, 20, True) -> {"fare": 44.4, "eta_min": 44, "eta_text": "44 min"}
Solve “Food-Delivery Quote Engine — interview at a food-delivery startup” in your browser →10. Stage 1 — the Arithmetic Unit (the code that really computes a op b)
Compiler1 way to solve📤 OUTPUT: return the computed number (int or float), e.g. 3 for (7, '//', 2); RAISE the errors described. Use `return`, not print().
op is one of + - * / // % **. Return the result.
Division or modulo by zero -> raise ZeroDivisionError("division by zero")
Unknown op -> raise ValueError(f"unknown operator {op}")
eval_binary(7, "//", 2) -> 3 eval_binary(2, "**", 10) -> 1024
Solve “Stage 1 — the Arithmetic Unit (the code that really computes a op b)” in your browser →