Coding Fundamentals with Python
Start from zero and learn to think like a programmer. You'll write real Python code from your very first lesson — understanding what computers do, how to store data, make decisions, and repeat actions automatically.
2 modules · 8 lessons · free to read
What you'll learn
- ✓Write and run Python programs from scratch, with no prior experience
- ✓Store and manipulate data using variables, numbers, and strings
- ✓Make programs smarter with if/elif/else decisions and boolean logic
- ✓Repeat actions automatically using for loops and while loops
01Why We Program?
Discover what programming really is and why it matters. You will write your first Python code, learn how computers execute instructions, and start building the mental model that every real programmer carries.
1.What Does a Computer Actually Do?
A program is a list of instructions that tells a computer exactly what to do, one step at a time. Computers are fast, but they are not smart — they follow instructions with zero guesswork. When you write code, you are writing those instructions in a language the computer can understand. Python is one of those languages, and it reads your code from the very first line to the last, executing each instruction before moving to the next.
pythonprint("Step 1") print("Step 2") print("Step 3")
Run the block above and you will see three lines appear in order. Python never skips ahead and never goes back unless you tell it to. That sequential, line-by-line execution is the foundation every program is built on.
The print() Function
print() is a built-in Python function that sends output to the screen. You pass it a value inside the parentheses, and Python displays it. A value wrapped in quotes — like "Hello, world!" — is called a string. Strings are how Python represents text.
pythonprint("Hello, world!") print("I am learning Python.") print("One line at a time.")
Each call to print() adds one new line of output. Notice how the program flows straight down — line 1 runs, then line 2, then line 3. Nothing happens out of order.
Use print() any time you want to display information while your program is running — to check a result, to show a message to a user, or simply to understand what your code is doing step by step.
Constraints
- –Your function must be named exactly `say_hello`.
- –Use `return` to send back the string — do not use `print()`.
- –The returned string must be exactly `Hello, world!` with a comma and an exclamation mark.
2.Talking to Python — Your First Conversation
The print() function sends output to the screen — it is how Python speaks back to you.
When you type print("Hello"), Python evaluates the argument inside the parentheses and writes the result to the terminal. You can pass a string (text wrapped in quotes), a number, or even a whole expression — Python handles the evaluation before it prints.
pythonprint("Hello, world!") # prints: Hello, world! print(42) # prints: 42 print(3 + 7) # prints: 10
Multiple Arguments and the sep Parameter
print() can accept more than one argument at a time. Separate each value with a comma and Python will print them all on one line, with a space between them by default.
The sep keyword argument lets you change that separator to anything you like — a dash, a newline, or an empty string.
pythonprint("Name:", "Zuzu") # prints: Name: Zuzu print(1, 2, 3) # prints: 1 2 3 print(1, 2, 3, sep="-") # prints: 1-2-3 print("line one", "line two", sep="\n") # two separate lines
You will use print() in almost every Python program you write — to inspect a value while debugging, to show results to a user, or to trace what your code is doing step by step. Mastering its arguments early saves you from guessing what your program is actually producing.
Constraints
- –Use the `return` keyword — do not use `print()` inside the function.
- –The function must accept two parameters: a string `name` and an integer `score`.
- –Return a single string that matches the format `"Name: <name>, Score: <score>"` exactly.
3.Variables, Expressions and Statements
A variable is a named container that stores a value so your program can remember and reuse it.
You create a variable with the assignment operator =. The name goes on the left, the value goes on the right. Python figures out the type automatically — an integer (int) is a whole number, a float is a decimal number, and a string (str) is text wrapped in quotes.
pythonage = 16 # int price = 9.99 # float name = "Zuzu" # str
Variable names must start with a letter or underscore, contain only letters, digits, and underscores, and cannot be a Python keyword. score_1 is valid; 1score is not.
Arithmetic Expressions
An expression is any piece of code that evaluates to a value — and arithmetic expressions combine numbers with operators to produce a numeric result.
Python supports six arithmetic operators: + (add), - (subtract), * (multiply), / (divide), // (integer division — drops the decimal), and % (modulo — gives the remainder).
pythontotal = 3 + 7 # 10 diff = 10 - 4 # 6 area = 5 * 4 # 20 ratio = 10 / 4 # 2.5 quot = 10 // 4 # 2 (whole number only) rem = 10 % 4 # 2 (remainder after dividing)
You can store the result of any expression in a variable and use that variable in a later expression — this is how programs build up multi-step calculations step by step. Use variables with arithmetic any time you need to compute a result that depends on input values rather than hard-coded numbers.
Constraints
- –Use the `return` keyword — do not use `print()` inside the function.
- –Declare `pi = 3.14159` as a local variable inside the function and use it in the calculation.
- –Use the `**` operator to square the radius (e.g. `radius ** 2`).
4.Words and Sentences — Working with Strings
A string (str) is a sequence of characters — letters, digits, spaces, or punctuation — stored as a single value in Python.
You can join two strings together using the + operator, a technique called concatenation. If you want to combine a string with a number, you must first convert the number to a string using str(), otherwise Python raises a TypeError.
pythonfirst = "Ada" last = "Lovelace" full = first + " " + last # "Ada Lovelace" age = 28 blurb = "Age: " + str(age) # "Age: 28"
Concatenation works, but it gets awkward fast — every variable needs a str() call and every space must be typed by hand.
F-Strings
An f-string (formatted string literal) lets you embed variables directly inside a string by prefixing the opening quote with f and wrapping each variable in curly braces {}.
pythonfirst = "Ada" age = 28 message = f"Hello, {first}! You are {age} years old." # "Hello, Ada! You are 28 years old."
Python evaluates the expression inside each {} at runtime and inserts the result as a string — no str() call needed. You can also put simple expressions, not just variable names, inside the braces: f"Area: {3.14 * r ** 2:.2f}" rounds to two decimal places.
pythondef introduce(name, age): return f"{name} is {age} years old." print(introduce("Maya", 17)) # Maya is 17 years old.
Use concatenation when you are joining a handful of pre-built strings without any formatting needs. Use f-strings whenever you are building sentences from variables — they are shorter, easier to read, and handle any type automatically.
Constraints
- –Use an f-string (prefix `f`) — do not use the `+` concatenation operator in your return statement.
- –Use the `return` keyword — do not use `print()` inside the function.
- –The returned string must match the format exactly, including the comma after the name and the exclamation mark.
02Making Your Computer Smarter
Take your programs beyond straight-line code — add decision-making with conditionals and repeat actions automatically with loops.
1.Asking Questions — Conditionals and Booleans
A boolean is a value that is either True or False — the two possible answers to any yes/no question a program can ask. Python uses the bool type to represent these answers, and almost every decision your code ever makes starts with a boolean.
pythonis_raining = True has_umbrella = False print(type(is_raining)) # <class 'bool'> print(is_raining) # True print(has_umbrella) # False
Booleans are produced by comparison operators — symbols that compare two values and return True or False. Python has six of them: == (equal), != (not equal), < (less than), > (greater than), <= (less than or equal), and >= (greater than or equal). Notice that equality uses two equals signs — a single = is for assignment, not comparison.
pythonage = 14 print(age == 14) # True print(age != 10) # True print(age > 18) # False print(age <= 14) # True print(age >= 20) # False
Logical operators let you combine or flip boolean values so you can ask more powerful compound questions. and returns True only when both sides are True. or returns True when at least one side is True. not flips a boolean — not True becomes False, and not False becomes True.
pythonspeed = 75 within_limit = speed >= 60 and speed <= 90 print(within_limit) # True has_ticket = False print(not has_ticket) # True score = 55 passed = score >= 50 or score == 100 print(passed) # True
Because comparison expressions already evaluate to True or False, you can return them directly from a function — no extra variable needed. A function that returns a boolean expression is sometimes called a predicate, and predicates are one of the most common patterns in Python code. You will use them whenever you need to check eligibility, validate input, or filter data.
pythondef is_teen(age): return age >= 13 and age <= 19 print(is_teen(15)) # True print(is_teen(22)) # False
Constraints
- –Your function must be named `is_valid_speed` and accept exactly one integer parameter.
- –You must return the result of a boolean expression directly — do not use if/elif/else.
- –The function must return `True` when speed is between 40 and 120 inclusive, and `False` otherwise.
- –You must use the `and` logical operator to combine two comparison conditions.
2.Choosing a Path — if, elif, and else
An if statement tells Python to run a block of code only when a condition is True. You already know how to form boolean expressions — now you give Python a choice about what to do next.
pythonscore = 85 if score >= 90: print("Excellent work!")
Here Python checks whether score >= 90. Because 85 >= 90 is False, the print is skipped entirely. Nothing happens — and that is perfectly fine. An if block runs zero or one times depending on the condition.
Adding More Paths with elif and else
elif (short for "else if") lets you chain additional conditions after an if. Python checks each condition in order and runs the first block whose condition is True — then skips the rest. else is an optional catch-all that runs only when every condition above it was False.
pythonscore = 72 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" else: grade = "F" print(grade) # C
Python evaluates from top to bottom. Because 72 >= 90 is False and 72 >= 80 is False, it reaches 72 >= 70, which is True, assigns "C", and moves on. The else branch is never reached. Use if/elif/else any time your program needs to respond differently to a range of possible values — score bands, age groups, temperature levels, or any other scale where a single yes/no is not enough.
Constraints
- –The function must accept a single integer or float argument representing a score from 0 to 100.
- –Return the string "A" for scores of 90 and above.
- –Return the string "B" for scores from 80 up to (but not including) 90.
- –Return the string "C" for scores from 70 up to (but not including) 80.
- –Return the string "F" for any score below 70.
3.Doing It Again — Definite Loops with for
A for loop repeats a block of code a fixed number of times, once for each item in a sequence. In Python the most common sequence for counting is produced by range(), which generates a series of integers for the loop to step through.
pythonfor i in range(5): print(i) # prints 0, 1, 2, 3, 4
range(n) gives you the integers from 0 up to — but not including — n. The variable i takes each value in turn, and the indented block runs once per value. Because the number of repetitions is decided before the loop starts, this is called a definite loop.
Accumulating a Result
The accumulator pattern lets you build up an answer across many iterations. You create a variable before the loop, then update it inside the loop on every pass.
pythondef sum_to(n): total = 0 for i in range(1, n + 1): total = total + i return total print(sum_to(5)) # 15 (1+2+3+4+5) print(sum_to(10)) # 55
Here range(1, n + 1) starts at 1 and stops just before n + 1, so it covers every integer from 1 to n inclusive. Each pass adds the current value of i to total. When the loop finishes, total holds the complete sum. Use this pattern whenever you need to compute a running count, product, or combined value across a sequence of numbers.
Constraints
- –Your function must be named `sum_to` and accept exactly one parameter `n`.
- –You must use a `for` loop with `range()` to iterate over the integers — do not use built-in functions like `sum()`.
- –Initialise an accumulator variable to `0` before the loop and add each integer to it inside the loop.
- –Return the final accumulated total after the loop completes.
- –You may assume `n` is a positive integer greater than or equal to 1.
4.Looping Until It's Done — Indefinite Loops with while
A while loop repeats a block of code for as long as a condition remains True — you use it when you don't know upfront how many iterations you need.
The last lesson introduced for loops, which are ideal when you know the count in advance (for i in range(10)). A while loop hands control to a condition instead of a counter. Python checks the condition before every iteration; the moment it becomes False, the loop stops.
pythoncount = 0 while count < 3: print("count is", count) count += 1 # Output: # count is 0 # count is 1 # count is 2
The variable count starts at 0. Each pass through the loop prints it, then adds 1. When count reaches 3, the condition count < 3 is False and the loop exits. Notice that you are responsible for updating the variable — forgetting count += 1 would create an infinite loop that never stops.
Finding the First Value That Qualifies
The real power of while shows up when the number of steps depends on the data. Suppose you need the first number greater than or equal to some starting point that is divisible by a given divisor. You can't use range() for this because you don't know how many steps it will take.
pythondef first_multiple(start, divisor): n = start while n % divisor != 0: n += 1 return n print(first_multiple(7, 4)) # 8 print(first_multiple(12, 6)) # 12
n begins at start. The loop keeps adding 1 until n % divisor == 0, meaning n divides evenly. If start is already a multiple, the condition is False immediately and the loop body never runs — start is returned as-is.
Use a while loop any time your stopping point is a condition, not a count: waiting for user input, searching through data until a match is found, or converging on a numerical result. When the number of steps is fixed, stick with for; when you're looping until something changes, reach for while.
Constraints
- –The function must use a while loop — not a for loop or list comprehension.
- –If the starting value is already divisible by the divisor, return it immediately without incrementing.
- –Both arguments will be positive integers greater than zero.
- –The divisor will always be a valid positive integer, so the loop will always terminate.
Frequently Asked Questions
- What does the following code print? ```python print("Step 1") print("Step 2") print("Step 3") ```
- Step 1 Step 2 Step 3. Python executes each line in order from top to bottom, and each call to print() adds a new line of output. The strings are printed exactly as written, including the space before each number.
- Which of the following is a valid variable assignment in Python?
- score_1 = 95. Variable names must start with a letter or underscore and can only contain letters, digits, and underscores. Options a, c, and d are invalid because they start with a digit or contain a hyphen or space.
- What is the value of `result` after this code runs? ```python result = 10 // 3 ```
- 3. The `//` operator is integer (floor) division — it divides and drops any decimal remainder. 10 divided by 3 is 3 with a remainder of 1, so `//` returns the integer 3, not 3.33 or 3.0.
- What does the following function return? ```python def introduce(name, age): return f"{name} is {age} years old." introduce("Maya", 17) ```
- "Maya is 17 years old.". An f-string evaluates the expressions inside `{}` at runtime and automatically converts them to strings — so `{name}` becomes `Maya` and `{age}` becomes `17`, producing the final string without any explicit `str()` call.
- How do I write a function called `say_hello` that returns the string `"Hello, world!"`.?
- A program is a list of instructions that tells a computer exactly what to do, one step at a time. Computers are fast, but they are not smart — they follow instructions with zero guesswork. When you write code, you are writing those instructions in a language the computer can understand. Python is one of those languages, and it reads your code from the very first line to the last, executing each instruction before moving to the next.
- How do I write a Python function named `make_label` that uses string concatenation or an expression to return a single formatted string in the form `"Name: <name>, Score: <score>"` — mirroring what `print()` would display if given those values.?
- The `print()` function sends output to the screen — it is how Python speaks back to you.
- How do I write a Python function named `circle_area` that accepts a numeric `radius` parameter and uses the `*` and `**` arithmetic operators with the variable `pi = 3.14159` to return the area of a circle (area = pi × radius²).?
- A variable is a named container that stores a value so your program can remember and reuse it.
- How do I write a Python function named `make_greeting` that accepts two string parameters — `first_name` and `last_name` — and uses an f-string to return the sentence `"Hello, {first_name} {last_name}! Welcome to Python."`.?
- A string (`str`) is a sequence of characters — letters, digits, spaces, or punctuation — stored as a single value in Python.
- What does the following expression return? ```python speed = 75 speed >= 60 and speed <= 90 ```
- True. Both conditions are satisfied: 75 >= 60 is True and 75 <= 90 is True. Because `and` requires both sides to be True, the entire expression evaluates to True.
- What does the following function return when called with `grade(72)`? ```python def grade(score): if score >= 90: return "A" elif score >= 80: return "B" elif score >= 70: return "C" else: return "F" ```
- "C". Python checks conditions top to bottom. 72 >= 90 is False, 72 >= 80 is False, but 72 >= 70 is True, so the function returns "C" and stops — the else branch is never reached.
- What is the value of `total` after this loop finishes? ```python total = 0 for i in range(1, 4): total = total + i ```
- 6. `range(1, 4)` produces the integers 1, 2, and 3. The accumulator adds each in turn: 0 + 1 = 1, 1 + 2 = 3, 3 + 3 = 6. The final value of `total` is 6.
- What value does `first_multiple(7, 4)` return? ```python def first_multiple(start, divisor): n = start while n % divisor != 0: n += 1 return n ```
- 8. Starting at n = 7: 7 % 4 = 3 (not 0), so n becomes 8. Then 8 % 4 = 0, so the condition is False and the loop stops. The function returns 8, the first multiple of 4 that is >= 7.
- How do I write a function called `is_valid_speed` that takes an integer `speed` and returns `True` if the speed is at least 40 and no more than 120, using Python's comparison and logical operators.?
- A **boolean** is a value that is either `True` or `False` — the two possible answers to any yes/no question a program can ask. Python uses the `bool` type to represent these answers, and almost every decision your code ever makes starts with a boolean.
- How do I write a function that uses if, elif, and else to classify a numeric score and return the corresponding letter grade as a string.?
- An `if` statement tells Python to run a block of code only when a condition is `True`. You already know how to form boolean expressions — now you give Python a choice about what to do next.
- How do I write a function called `sum_to(n)` that uses a `for` loop and the accumulator pattern to compute and return the sum of all integers from 1 to n inclusive.?
- A `for` loop repeats a block of code a fixed number of times, once for each item in a sequence. In Python the most common sequence for counting is produced by `range()`, which generates a series of integers for the loop to step through.
- How do I write a function that uses a `while` loop to find and return the first integer greater than or equal to a given starting value that is evenly divisible by a given divisor.?
- A `while` loop repeats a block of code for as long as a condition remains `True` — you use it when you don't know upfront how many iterations you need.
Ready to write code?
Theory is just the start. Write real code, run tests, build the habit.
Open the playground →