Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Basics

Python Conditionals and Loops: if/elif/else, for, while, break and continue

How Python chooses which line runs next: an if/elif chain for a grade, indentation as structure, for over lists, strings and range, while with a countdown, and break, continue and pass, ending in one score processor that uses them all.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Basics

What you will learn

  • Write an if/elif/else chain and explain why the first True branch wins
  • Use indentation to mark blocks and read an IndentationError
  • Loop with for over lists, strings and range, and with while on a condition
  • Control a loop with break, continue and pass

Before you start

  • Python Operators
  • Python Lists, Tuples, Sets and Dicts

Every line written so far runs once, top to bottom, in order. Now your program starts choosing which lines run, and how many times. That's flow control.

Normally Python reads your code like walking down a straight road. Sometimes you reach a fork: if it's raining you take the umbrella, otherwise you don't. That's if. Sometimes there's a stack of plates in the sink and you wash each one until none are left. That's a for loop. Sometimes you don't know the count: you fill a bucket and keep the tap on while it isn't full. That's while. And you can change your mind midway, stopping early or skipping one plate: break and continue.

if, elif and else

score = 85
print("Score:", score)

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

print("Done")
Score: 85
Grade: B
Done
For score 85, the check score at least 90 is False, the check at least 80 is True so Grade B prints, and the remaining checks and else are skipped score >= 90 ? False score >= 80 ? True → print("Grade: B") >= 70 ? else skipped, never checked print("Done")
In one chain, the first True wins and the rest are skipped.

85 isn't at least 90, so Python skips that line. elif, short for else if, is one more check: 85 is at least 80, so it prints Grade B. Here's the important part: 85 is also above 70, but that check never runs. Once one branch is True, Python skips the rest of the chain. That's why the highest score goes first. else has no condition; it's the catch-all that runs only when every check above failed.

Indentation is the structure

temperature = 32

if temperature > 30:
    print("It is hot")
    print("Drink water")
print("This line always runs")
It is hot
Drink water
This line always runs

The colon opens a block. The two lines pushed in by four spaces are that block and run together. The last print starts at the left edge, so it's outside the block and runs whatever the check says. Leave the indented line flush left and Python refuses to run the file:

  File "S01L08_FlowControl\indent_error.py", line 4
    print("It is hot")
    ^^^^^
IndentationError: expected an indented block after 'if' statement on line 3

In Python, spacing isn't decoration. It's the structure of your program.

Truthiness in a condition

cart = []
name = "Asha"

if cart:
    print("Cart has items")
else:
    print("Cart is empty")

if name:
    print("Hello,", name)
Cart is empty
Hello, Asha

A condition doesn't have to be a comparison. An if uses the same rule as bool: empty things are False, everything else True. if cart reads almost like English: "if there's something in the cart". And else is optional.

Separate ifs can each run

age = 70
is_member = True
price = 100.0
print(f"Original price: ${price}")

if age >= 65 or age < 12:
    price *= 0.70
    print("Age discount applied: 30% off")

if is_member:
    price *= 0.90
    print("Member discount applied: extra 10% off")

print(f"Final price: ${price:.2f}")
Original price: $100.0
Age discount applied: 30% off
Member discount applied: extra 10% off
Final price: $63.00

With or, 70 being at least 65 is enough, so the price goes from 100 to 70. The next line is a fresh if, not an elif, so Python checks it no matter what happened above, and 70 becomes 63. An elif chain picks one branch; separate ifs can each run.

An if inside an if

age = 20
has_ticket = True

if age >= 18:
    print("Age check passed")
    if has_ticket:
        print("Welcome in")
    else:
        print("Please buy a ticket")
else:
    print("Adults only")
Age check passed
Welcome in

The inner check only runs if the outer one passed. Each else lines up with its own if. Two levels read fine; much deeper gets hard to follow.

The for loop

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print("Fruit:", fruit)

print("Loop finished, last fruit was", fruit)
Fruit: apple
Fruit: banana
Fruit: cherry
Loop finished, last fruit was cherry

The first time round, Python puts the first item in fruit and runs the body. Then it goes back up, and fruit is banana, then cherry. With nothing left, the loop ends. Notice fruit is still there afterwards, holding the last value it got. You can call that variable anything; the loop gives it one item each time round.

A string is a sequence of characters, so the same loop works on it: for letter in "Python" gives P, y, t, h, o, n. If you can go through a thing one item at a time, for can loop over it.

Counting with range

for i in range(5):
    print("i =", i)

print("Counting by 3:")
for n in range(0, 10, 3):
    print(n)

print("Countdown:")
for n in range(5, 0, -1):
    print(n)
i = 0
i = 1
i = 2
i = 3
i = 4
Counting by 3:
0
3
6
9
Countdown:
5
4
3
2
1

range(5) gives five numbers starting at 0; 5 itself isn't included. With three numbers it's start, stop, step. The step can be negative, which counts down and stops before 0. The stop number is never included.

The while loop

count = 5
print("Start:", count)

while count > 0:
    print("count =", count)
    count -= 1

print("Done, count is now", count)
Start: 5
count = 5
count = 4
count = 3
count = 2
count = 1
Done, count is now 0

A for loop knows its items. A while loop only knows a condition, and keeps going while it's True. Each round, count -= 1 takes it down by one, until 0 > 0 is False and the loop ends.

Watch this one. Take away the count -= 1 line and count stays at 5. The condition never turns False and the loop never ends. Something in the body has to move you towards False. Use for when you have items to go through, and while when you're waiting on a condition.

break, continue and pass

names = ["Alice", "Bob", "Charlie", "Diana"]
target = "Charlie"

for name in names:
    print("Checking:", name)
    if name == target:
        print("Found!", target)
        break
Checking: Alice
Checking: Bob
Checking: Charlie
Found! Charlie

break leaves the loop right there. Diana is never checked; there's no point looking further once you've found it.

for num in range(1, 11):
    if num % 2 == 0:
        continue
    print("Odd:", num)
Odd: 1
Odd: 3
Odd: 5
Odd: 7
Odd: 9

continue skips only the current round. For an even number the remainder is 0, so continue sends Python straight back to the for line and the print is skipped.

role = "admin"

if role == "admin":
    pass
elif role == "editor":
    pass
else:
    print("Regular user")

print("Program continues normally")
Program continues normally

pass does nothing and jumps nowhere. Why have it? A block can't be empty, or you'd get that same IndentationError. pass holds the place until you've written the logic.

A loop inside a loop

for row in range(1, 4):
    for col in range(1, 4):
        print(row, "x", col, "=", row * col)
    print("row", row, "done")
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
row 1 done
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
row 2 done
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
row 3 done

The inner loop runs all the way through for every round of the outer one, like the minute hand and hour hand on a clock. The "done" print is pushed in only one level, so it belongs to the outer loop.

Everything together

scores = [88, -5, 72, 95, -1, 60]

for score in scores:
    if score == -1:
        print("Sentinel found, stopping.")
        break
    if score < 0:
        print(f"Skipping invalid: {score}")
        continue
    if score >= 90:
        grade = "A"
    elif score >= 80:
        grade = "B"
    elif score >= 70:
        grade = "C"
    else:
        grade = "F"
    print(f"Score {score} -> Grade {grade}")
Score 88 -> Grade B
Skipping invalid: -5
Score 72 -> Grade C
Score 95 -> Grade A
Sentinel found, stopping.

-1 is a stop marker, called a sentinel: nothing more to process. -5 is below zero, so continue skips it with no grade. When -1 arrives, break ends the loop, so 60 never gets graded. One loop, one chain, one break and one continue.

Quick recap

ToolRemember
if / elif / elsefirst True wins; put the strictest check first
indentationdecides which lines belong to what
forone item each time round; works on lists and strings
range(start, stop, step)stop is never included
whileruns while True; the body must move it towards False
break / continue / passleave / skip this round / do nothing

For loops over real data, with enumerate, zip and dictionaries, carry on with Looping over real data.

Try it yourself

Change the scores in the last example and say what will print before you run it. Or prompt an AI tool for a similar loop, and step through every line it gives you.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 8 of 48

Previous
Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
Next post
Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Python for AI: The Five Tools You Actually Need

The small part of Python that carries most AI code: dicts and JSON, typed functions with a dataclass, comprehensions and f-strings, environment variables for keys, and try/except for replies that are not JSON. Three standard-library scripts on four support tickets.

Thinking Like a Python Architect in an AI-First World

Coding is laying bricks; architecting is deciding how the pieces fit. A two-line average function shows why someone still has to understand the code an AI tool writes.

Your First Python Program: print, Comments, sep and end

Five tiny files: print and quotes, top-to-bottom order, # comments, several values with sep and end, and the SyntaxError one missing quote causes. Every output is from a real run.

Set Up PyCharm for Python: Install, First Project and First Run

Install PyCharm, create a Pure Python project, and understand the two words that confuse beginners: the interpreter (the cook) and .venv (the project's own shelf). Then run a file and read the exit code.

On this page

  • if, elif and else
  • Indentation is the structure
  • Truthiness in a condition
  • Separate ifs can each run
  • An if inside an if
  • The for loop
  • Counting with range
  • The while loop
  • break, continue and pass
  • A loop inside a loop
  • Everything together
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.