Back to Blog
Loops and Conditionals in Python Programming
May 20, 20268 min read

Loops and Conditionals in Python Programming

Loops and conditionals are where a program stops being a fixed list of steps and starts making decisions and repeating work — where code becomes genuinely powerful. They are also where beginners most often write code that runs but does the wrong thing, because the logic is subtly off. Building a clear mental model of how Python makes choices and repeats actions is what turns fragile, guessed-at code into reliable programs.

The good news is that control flow in Python is small and consistent: a couple of ways to make decisions, a couple of ways to repeat, and a set of boolean rules underneath. Understanding those rules — rather than pattern-matching examples — is what lets you write loops and conditions that do exactly what you intend.

This is a core skill we build carefully in Python tutoring in Burnaby and online, for beginners, high-school computer science and university courses.

Conditionals: making the code decide

An if statement runs a block only when a condition is true, and it is the basic unit of decision-making. Adding elif and else lets a program choose between several paths, checking each condition in order and taking the first that matches. The order matters, because once a branch is taken the rest are skipped.

score = 75
if score >= 90:
    grade = "A"
elif score >= 70:      # checked only if the first was false
    grade = "B"
else:
    grade = "C"
print(grade)           # B

The common beginner mistake is getting the order or the boundaries wrong, so a value falls into the wrong branch. Because Python checks conditions top to bottom and stops at the first true one, arranging them correctly — usually most specific or most extreme first — is essential. Thinking through which branch a given input should take, and tracing it against your conditions, is the habit that eliminates a whole category of logic bugs.

Boolean logic: the rules underneath every condition

Every condition ultimately reduces to True or False, and Python combines these with and, or and not. The subtlety that catches beginners is short-circuiting: Python stops evaluating as soon as the answer is certain. In an and, if the first part is false, the whole thing is false and the second part is never checked; in an or, a true first part means the rest is skipped.

# short-circuiting prevents the crash:
x = 0
if x != 0 and 10 / x > 1:   # second part skipped when x is 0
    print("big")
print("no crash")            # runs fine

This is not a curiosity — it is used constantly to write safe conditions, like checking that a value is valid before using it. Python also allows chained comparisons that read like mathematics, so 1 < x < 10 means exactly what it looks like. Understanding that conditions are evaluated left to right and abandoned as soon as the outcome is known lets you both avoid crashes and write conditions that are efficient and clear.

The for loop: repeating over a collection

A for loop repeats an action once for each item in a collection, and it is the workhorse of Python iteration. Crucially, Python's for loop is built to walk directly over the items of a list, the characters of a string, or the keys of a dictionary — you rarely need to manage a counter by hand, which is a common source of errors in other languages.

total = 0
for n in [4, 8, 15]:
    total += n
print(total)          # 27

for i in range(5):    # 0, 1, 2, 3, 4
    print(i)

When you do need numbers, the range function generates them — range(5) gives 0 through 4, and range(2, 8, 2) gives 2, 4, 6. The most frequent beginner error is an off-by-one mistake, because range stops one before its end value, so range(5) does not include 5. Understanding that range goes up to but not including its endpoint prevents a bug that otherwise appears constantly, and thinking of a for loop as 'do this once for each of these' keeps the intent clear.

The while loop, and the infinite-loop trap

A while loop repeats as long as a condition stays true, which makes it the right tool when you do not know in advance how many repetitions you need — keep asking for input until it is valid, keep processing until a total is reached. Its power is also its danger: if the condition never becomes false, the loop runs forever.

k = 10
count = 0
while k > 1:
    k //= 2       # 10 -> 5 -> 2 -> 1
    count += 1
print(count)      # 3

The classic beginner disaster is a while loop whose condition never changes inside the body, so it spins endlessly and freezes the program. The discipline is to make sure that something inside the loop moves the condition toward becoming false — here, k shrinks each pass until it drops to 1. Every while loop should have a clear answer to the question 'what will eventually make this stop?', and being able to state that answer is how you avoid infinite loops.

List comprehensions: the Pythonic loop

Once the basics are solid, Python offers a compact, elegant way to build a list from a loop in a single line — the list comprehension. It expresses 'make a new list by doing something to each item, optionally keeping only some' in a form that reads almost like its description.

evens = [n for n in range(10) if n % 2 == 0]
print(evens)      # [0, 2, 4, 6, 8]

This is not just shorthand; it is considered the idiomatic, readable way to transform collections in Python, and you will see it everywhere in real code. Beginners should first understand it as the ordinary loop it replaces — build the list step by step, then learn to compress it — so that the comprehension is a clear expression of intent rather than a magic incantation. Reading and writing comprehensions fluently is a mark of moving from beginner toward genuine Python fluency.

break and continue: steering a loop

Two keywords give you finer control inside a loop. break exits the loop immediately, no matter how many iterations were left — useful when you have found what you were looking for and there is no reason to keep going. continue skips the rest of the current iteration and jumps straight to the next one, useful when you want to ignore certain items but keep looping. Together they let a loop respond to what it finds rather than blindly running to the end.

for n in [3, 7, 0, 4]:
    if n == 0:
        continue      # skip zeros
    if n > 5:
        break         # stop at the first big number
    print(n)          # prints 3, then stops at 7

The beginner's task is to use these deliberately rather than as a tangle. A well-placed break can make a search loop clean and efficient — stop the moment you succeed — while overusing them makes a loop hard to follow. Understanding exactly what each does, that break leaves the loop entirely while continue only skips one pass, prevents the confusion of a loop that ends earlier or processes fewer items than expected. They are precise tools, and used well they make loops both faster and clearer.

Nested loops: loops inside loops

A loop can contain another loop, and this nesting is how you work with grids, tables, and combinations — for each row, do something for each column. It is powerful and appears constantly, from processing a spreadsheet to comparing every item against every other. The key to reading nested loops is to recognise that the inner loop runs completely for each single pass of the outer one.

The thing to watch is that the work multiplies: an outer loop of ten and an inner loop of ten means a hundred iterations, so nested loops can become slow if the collections are large. Beginners should understand both how to write them — keeping clear which loop is which, often by naming the loop variables meaningfully — and why they can be expensive. Recognising that the total work is the product of the loop sizes is an early, valuable step toward thinking about efficiency, which becomes important as programs grow.

Truthiness: what counts as true

Python lets you use non-boolean values directly in conditions, and it has clear rules for what counts as true or false. Zero, an empty string, an empty list and the special value None are all treated as false; almost everything else is true. This enables clean, idiomatic checks — testing whether a list has items by writing 'if the list' rather than 'if the length of the list is greater than zero'.

This is convenient and very common in real Python, but it can surprise beginners who do not know the rules, producing conditions that behave unexpectedly on empty or zero values. Learning what Python considers false — the empties and the zeros and None — lets you both read idiomatic code and write conditions that handle edge cases correctly. It is a small set of rules with an outsized effect on how natural your Python looks.

Where beginners actually go wrong with control flow

  • Ordering if/elif conditions wrongly, so values land in the wrong branch.
  • Off-by-one errors with range, forgetting it stops before its end value.
  • Writing while loops with no way for the condition to become false — infinite loops.
  • Not knowing short-circuiting, and so writing conditions that crash on edge cases.
  • Being surprised by truthiness on empty or zero values.

How to master loops and conditionals

  • Trace each input through your if/elif/else by hand to check it lands in the right branch.
  • Remember range stops one before its endpoint, and check your boundaries deliberately.
  • For every while loop, answer 'what will make this stop?' before running it.
  • Learn short-circuiting and use it to guard conditions safely.
  • Build a list comprehension by first writing the plain loop it replaces.

Getting help with Python loops and conditionals

If your loops run but do the wrong thing, the fix is usually the logic underneath — boundaries, boolean rules, and stopping conditions. Our Python tutoring in Burnaby and online, for beginners, high-school computer science and university courses.

Sessions run in person in Burnaby or online across Metro Vancouver. Book a free 30-minute consultation and bring the code or concept you are stuck on.

Recommended Reads

Book a Free 30-Minute Consultation

Use the form below and a member of our team will respond within the next 24 hours.

Or

Prefer Quick Communication? Message Us On Whatsapp Or Call Us!

Chat With Us On Whatsapp+1 672-514-7587
Chat with us