MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Jupyter notebook – Lab Session – 6 – Conditions, Control Flow & Looping

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.

TopicKey point
if with x, y, inAny value can be a condition. 0, empty strings, empty lists and None are falsy. Most other values are truthy.
Indentation and blocksPython has no braces. A block (suite) is the set of lines indented under a colon. The block ends when the indentation goes back.
else / elifPython checks branches from top to bottom and runs only the first true one. else catches everything else.
elif 1/0 cellAfter one branch matches, Python skips the remaining conditions, so 1/0 and the undefined var never run.
One-line ifif cond: a; b; c is legal, but it hurts readability. Use it sparingly.
Conditional expressionvalue_if_true if condition else value_if_false returns a value, so you can use it inside print() or an assignment.
passA no-op placeholder for places where Python's syntax requires a statement.
whileRepeats while the condition is true. Something inside the loop must eventually make it false.
forIterates over any iterable: lists, tuples, strings, dictionaries (keys by default) and range().
break / continuebreak exits the loop. continue skips to the next iteration.
Loop elseRuns only when the loop finishes without hitting break.

Running the notebook cleanly

  1. Download the .ipynb file from the gist (use the Download ZIP or Raw button) and put it in a working folder.
  2. Start Jupyter from that folder with jupyter lab or jupyter notebook.
  3. Before you run anything, comment out the while True: cell, or be ready to interrupt it (see the warning below).
  4. 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.
  5. When a cell asks for input, as the temperature converter does, type something like 45F in 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 symptomCauseFix
IndentationError: expected an indented blockA line ending in : has nothing indented under itIndent 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 definedThe variable is only assigned in some branchesAssign a default before the if, or print inside each branch
Cell shows [*] foreverInfinite while loopInterrupt the kernel, then make sure the loop variable changes on every iteration
Items skipped while removing from a list in a for loopThe list changes size while you iterate over itLoop over a copy (for x in items[:]) or build a new list
RuntimeError: dictionary changed size during iterationAdding or removing keys while looping over a dictLoop over list(d) or list(d.items())

Practice exercises

  1. Write a FizzBuzz for 1 to 30 using for and range(): print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number otherwise.
  2. Use a while loop to keep asking for input until the user types quit, and print each entry in upper case.
  3. Given scores = {'Ana': 91, 'Raj': 78, 'Li': 64}, use d.items() and an if/elif/else chain to print a grade (A for 90 or above, B for 75 or above, C for anything lower) for each student.
  4. Use for ... else to check whether a number entered by the user is prime, printing prime from the else branch.
  5. Rewrite the nested son/father/grandfather example 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services — all in one place.

Explore Hospitals
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.

Related Posts

Jupyter notebook – Lab Session – 10 – Introduction of Data Types, Variables & checkpoint

This lab is a Jupyter notebook that introduces Python's basic data types (str, int, float, bool), variables and naming rules, arithmetic, comparison and string operators, and the…

Read More

Jupyter notebook – Lab Session – 8 – Calculating Descriptive Statistics with math, statistics, numpy, pandas

This lab calculates descriptive statistics in a Jupyter notebook with Python's built-in math and statistics modules, NumPy, SciPy and pandas. It covers central tendency (mean, weighted, harmonic…

Read More

Jupyter notebook – Lab Session – 5 – Exploring Datasets with Pandas and Matplotlib

This lab loads the UN Canada immigration dataset (Canada.xlsx) into a pandas DataFrame, cleans it, and draws a waffle chart with Matplotlib comparing total immigration from Denmark,…

Read More

Jupyter notebook – Lab Session – 4 – Exploring Datasets with Pandas

This lab loads the Canada immigration dataset (1980 to 2013) from an Excel file into a pandas DataFrame. It then inspects the data with head(), tail(), info(),…

Read More

Jupyter notebook – Lab Session – 2 – Analyzing Data with Pandas, NumPy & Visualizing Data with matplotlib

This lab loads a historical earthquake dataset into a Jupyter notebook with pandas, joins the separate Date and Time columns into one datetime column, and makes it…

Read More

Why Your Jupyter Notebook Forgets Everything Between Sessions

A notebook you closed on Friday rarely opens the same way on Monday. The file is exactly as you left it — every cell, every output, every…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x