Dr. Roger Ianjamasimanana

Python loops and control statements

By Dr. Roger Ianjamasimanana

Python while loop

A while loop repeatedly executes a block of program inside it as long as a given condition is true. Imagine you're repeatedly checking if a jar still has cookies. As long as there are cookies inside, you take one and enjoy it.

This simple loop continues until the cookie jar is empty. In each cycle, it checks the condition (cookies > 0), similar to asking, "Is there still a cookie in the jar?" If yes, you take one and eat it (decreasing the number of cookies left in the jar).

Python for loop

A for loop lets you iterate over a sequence (like a list or range) without manually tracking a condition. Imagine you have a box of candies and want to give each one to a friend. Each candy is handled exactly once:

Python if statement

An if statement checks whether a condition is true. If it is, the code inside the if block runs. Think of it like deciding whether you need an umbrella:

Python if...elif...else

When you have multiple conditions, you can chain them together with elif (short for "else if") and end with else as a catch-all. Think of it like choosing an activity depending on the time of day:

Python control statements

There are three control statements in Python: break, continue, and pass.

A break stops a loop immediately, while continue skips the rest of the current loop iteration and moves on to the next. A pass does nothing (a placeholder) and is useful when a statement is required syntactically but you don’t want to run any code.

Suppose you're looking through fruit in a basket and want to stop when you find a "rotten" apple, but skip any that are "unripe":

Suppose you are searching through a box of fruits:

  • If you find something rotten, you stop searching inside the box and may be move to another box. In this case, you use a break.
  • If you find something unripe, you skip it for now but keep checking the rest. For this, you use continue
  • If you find something you’re not sure about, you can simply ignore it and decide later what to do. A pass is suitable for this case.

feature-top
Readers’ comment
feature-top
Log in to add a comment
🔐 Access