This lab works through Python decision-making and looping in a Jupyter notebook: if, elif and else, one-line conditionals, the conditional (ternary) expression, pass, while and for loops, break, continue and the loop else clause. Below the notebook you'll find an explanation of each concept, corrections to a few cells that give misleading output or fail, idiomatic alternatives and practice exercises.
What the notebook demonstrates
The notebook above is a run of small cells, and each one isolates a single rule of Python control flow. The table maps each topic to the point it teaches. Use it to check your understanding once you've run the cells.
| Topic | Key point |
|---|---|
if with x, y, in | Any value can be a condition. 0, empty strings, empty lists and None are falsy. Most other values are truthy. |
| Indentation and blocks | Python has no braces. A block (suite) is the set of lines indented under a colon. The block ends when the indentation goes back. |
else / elif | Python checks branches from top to bottom and runs only the first true one. else catches everything else. |
elif 1/0 cell | After one branch matches, Python skips the remaining conditions, so 1/0 and the undefined var never run. |
One-line if | if cond: a; b; c is legal, but it hurts readability. Use it sparingly. |
| Conditional expression | value_if_true if condition else value_if_false returns a value, so you can use it inside print() or an assignment. |
pass | A no-op placeholder for places where Python's syntax requires a statement. |
while | Repeats while the condition is true. Something inside the loop must eventually make it false. |
for | Iterates over any iterable: lists, tuples, strings, dictionaries (keys by default) and range(). |
break / continue | break exits the loop. continue skips to the next iteration. |
Loop else | Runs only when the loop finishes without hitting break. |
Running the notebook cleanly
- Download the
.ipynbfile from the gist (use the Download ZIP or Raw button) and put it in a working folder. - Start Jupyter from that folder with
jupyter laborjupyter notebook. - Before you run anything, comment out the
while True:cell, or be ready to interrupt it (see the warning below). - Select Kernel > Restart Kernel and Run All Cells. The saved execution counts jump around (for example 36, then 2, then 1), which shows the original was not run top to bottom in a single session.
- When a cell asks for input, as the temperature converter does, type something like
45Fin the box that appears and press Enter.
Note: Infinite loop warning: while True: print('foo') never ends and floods the output area. To stop it, press I twice in command mode, click the stop button or choose Kernel > Interrupt Kernel. If the browser tab stops responding, restart the kernel.
Corrections to the example notebook
Stale output in the ternary cell. The first raining cell sets raining = False but shows Let's go to the library. The cell was edited after it last ran. Running it again prints beach:
raining = False
print("Let's go to the", 'beach' if not raining else 'library')
# Output: Let's go to the beachCode language: PHP (php)
Pseudocode cell. The cell containing while <expr>: is a syntax template, not code, so it always raises SyntaxError. Read it as documentation. Changing it to a markdown cell stops it from breaking Run All.
Mislabelled heading. The first cell under "Nested while loops" is a nested if statement. The nested while example is the second cell, which uses a.pop(0) and b.pop(0).
Book purchase boundary. The Indonesian variables mean book price (hargaBuku), magazine price (hargaMajalah) and money (uang). The outputs mean "Buy book", "Buy magazine" and "Not enough money". Because the code tests uang > hargaBuku, someone holding exactly 20000 is told they can't afford a 20000 book. Use >=:
book_price = 20000
magazine_price = 5000
money = 20000
if money >= book_price:
print('Buy book')
elif money >= magazine_price:
print('Buy magazine')
else:
print('Not enough money')
# Output: Buy bookCode language: PHP (php)
Temperature converter crash. For input that doesn't end in C or F, the last cell prints an error message, then hits print(..., result, ...) where result was never assigned, and raises NameError. It also crashes with ValueError on decimals like 98.6F or text like abcF, rejects lowercase units, and doesn't say which unit the result is in. A corrected version:
temp = input('Enter a temperature to convert, e.g. 45F or 120C: ').strip().upper()
try:
degree = float(temp[:-1])
except ValueError:
degree = None
unit = temp[-1:]
if degree is None:
print('Enter a number followed by C or F.')
elif unit == 'C':
print('The temperature is', round(9 * degree / 5 + 32), 'degrees F')
elif unit == 'F':
print('The temperature is', round((degree - 32) * 5 / 9), 'degrees C')
else:
print('Enter a number followed by C or F.')
# Input 45F -> The temperature is 7 degrees C
# Input 100c -> The temperature is 212 degrees FCode language: PHP (php)
Each branch now prints its own result, so no path reaches a variable that was never assigned. .strip().upper() handles stray spaces and lowercase units. try/except handles input that isn't a number.
Loop else, break and continue in practice
The loop else clause confuses most newcomers. Read it as "no break". Its main use is searching: break when you find the item, and the else branch handles the case where nothing matched. You don't need a separate flag variable.
numbers = [3, 7, 11, 15]
for n in numbers:
if n % 2 == 0:
print('First even number:', n)
break
else:
print('No even number found')
# Output: No even number foundCode language: PHP (php)
Change the list to [3, 8, 11] and the output becomes First even number: 8. The else branch is skipped because the loop ended with break. In nested loops, break and continue only affect the innermost loop they appear in.
More idiomatic ways to write the same logic
The notebook sticks to basic forms. Real-world Python code tends to use these patterns instead:
# Chained comparison instead of: age >= 18 and age < 65
age = 30
if 18 <= age < 65:
print('adult')
# Truthiness instead of: while len(a):
a = ['foo', 'bar']
while a:
print(a.pop(0))
# Index and value together
for i, fruit in enumerate(['apple', 'banana'], start=1):
print(i, fruit) # 1 apple / 2 banana
# Two sequences in parallel
for name, score in zip(['Ana', 'Raj'], [91, 78]):
print(name, score)
# range(start, stop, step): stop is excluded
for n in range(10, 0, -2):
print(n) # 10 8 6 4 2Code language: PHP (php)
From Python 3.10, a match statement can replace a long elif chain like the name == 'Fred' example. The notebook's kernel metadata shows Python 3.8, which doesn't support match. Check your version with import sys; print(sys.version).
name = 'Adrian'
match name:
case 'Fred' | 'Xander' | 'Adrian' | 'Arnold':
print(f'Hello {name}')
case _:
print('Who are you?')Code language: PHP (php)
Common errors and how to fix them
| Error or symptom | Cause | Fix |
|---|---|---|
IndentationError: expected an indented block | A line ending in : has nothing indented under it | Indent the body, or use pass as a placeholder |
SyntaxError: invalid syntax on if x = 5: | = assigns a value. Comparisons use == | Write if x == 5: |
NameError: name 'result' is not defined | The variable is only assigned in some branches | Assign a default before the if, or print inside each branch |
Cell shows [*] forever | Infinite while loop | Interrupt the kernel, then make sure the loop variable changes on every iteration |
Items skipped while removing from a list in a for loop | The list changes size while you iterate over it | Loop over a copy (for x in items[:]) or build a new list |
RuntimeError: dictionary changed size during iteration | Adding or removing keys while looping over a dict | Loop over list(d) or list(d.items()) |
Practice exercises
- Write a FizzBuzz for 1 to 30 using
forandrange(): printFizzfor multiples of 3,Buzzfor multiples of 5,FizzBuzzfor multiples of both, and the number otherwise. - Use a
whileloop to keep asking for input until the user typesquit, and print each entry in upper case. - Given
scores = {'Ana': 91, 'Raj': 78, 'Li': 64}, used.items()and anif/elif/elsechain to print a grade (A for 90 or above, B for 75 or above, C for anything lower) for each student. - Use
for ... elseto check whether a number entered by the user is prime, printingprimefrom theelsebranch. - Rewrite the nested
son/father/grandfatherexample so it uses chained comparisons and a conditional expression for gender.
Frequently asked questions
What is the difference between break and continue in Python?
break exits the innermost loop at once. continue skips the rest of the current iteration and moves on to the next one.
When does the else block of a Python loop run?
It runs when a for loop runs out of items, or when a while condition becomes false. It is skipped if the loop ends with break, and that's why it's useful for search loops.
Does Python have a ternary operator?
Yes. It's called a conditional expression and is written a if condition else b. For example, s = 'teen' if age < 21 else 'adult'.
How do I stop an infinite loop in Jupyter Notebook?
Interrupt the kernel: press I twice in command mode, click the stop button or use Kernel > Interrupt Kernel. If that doesn't work, restart the kernel.
Does Python have a switch statement?
Python 3.10 and later have match/case, which covers switch-style logic and more. In older versions, use an if/elif/else chain or a dictionary lookup.
Related tutorials
- More Data Science tutorials
- Top 10 Data Science Platforms: Features, Pros, Cons & Comparison
- Associate Data Scientist: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services — all in one place.
Explore Hospitals