Your language · Python
Conditions and loops
if and else, switch or match, loops, break and continue.
Learn: Conditions and loops in Python7 minute read
Control flow decides which code runs next: conditions choose a branch and loops repeat code. Python's four main statements for it are if, match, for and while. Interviewers ask about the parts that work differently from other languages: how range counts, the else block on a loop, the match statement, and the fact that loops do not create a new scope (a scope is the area of code where a name can be used).
Step 1: if, elif and else
Python marks blocks with indentation instead of braces. A condition can be any object, judged by truthiness (whether an object counts as true or false; see Basics): zero, None (no value) and empty containers count as false. Comparisons can be chained as in maths, so 0 < score <= 100 works. A conditional expression picks one of two values in one line: status = "PASS" if ok else "FAIL".
and and or short-circuit: they stop as soon as the answer is known. So if element and element.is_displayed(): (a Selenium check that an element shows on the page) never calls a method on None. They also return one of their operands, which is why name = value or "guest" works as a default.
Step 2: match and case
Before Python 3.10 there was no switch, so code used if/elif chains or a dict that maps keys to functions. Since 3.10, match compares a value against patterns from top to bottom and runs the first case that fits. A pattern can be a literal (a fixed value such as "ping"), several choices joined by |, the shape of a list, keys of a dict or a type. It can also bind names (give a name to a part of the value) and add an if guard (an extra condition that must also be true). case _: matches anything, and there is no fall-through.
def route(event):
match event:
case "ping" | "health":
return "ok"
case {"type": "click", "target": target}:
return f"clicked {target}"
case [command, *args]:
return f"{command} with {len(args)} args"
case int(code) if code >= 500:
return "server error"
case _:
return "unknown"
print(route("health"))
print(route({"type": "click", "target": "#login", "x": 10}))
print(route(["open", "https://example.com", "--headless"]))
print(route(503))
print(route(404))
score = 72
print("PASS" if 50 <= score <= 100 else "FAIL")
ok clicked #login open with 2 args server error unknown PASS
The dict pattern matched even though the event had an extra key "x": mapping patterns ignore keys they do not name.
Step 3: for and while
A for loop walks over any iterable, which is anything you can loop over: a list, a string, a dict (its keys), a file (its lines). To count, use range(start, stop, step). It includes start and stops before stop: range(3) is 0, 1, 2 and range(10, 0, -3) is 10, 7, 4, 1. Instead of counting indexes, Python code uses helpers:
enumerate(items, start=1)gives a counter with each item.zip(a, b)walks two lists together and stops at the shorter one.zip(a, b, strict=True)raisesValueError(an error for a bad value) when the lengths differ, which helps when you compare expected and actual lists.dict.items()gives each key with its value.
while condition: repeats while the condition is true. Python has no do-while; when the body must run at least once, write while True: and break when done. Give every polling loop a limit, such as a maximum number of attempts.
Step 4: break, continue and the loop else
break leaves the loop and continue skips to the next pass. Python has no labelled break, so to leave nested loops, put them in a function and return. A loop may have an else block, which runs only if the loop finished without break. Read it as "no break": it suits a search that should report when nothing was found.
for i in range(1, 6):
if i == 3:
continue
if i == 5:
break
print(i, end=" ")
print()
rows = [("Asha", "QA"), ("Ravi", "Dev"), ("Bea", "QA")]
for number, (name, team) in enumerate(rows, start=1):
if team == "Ops":
print("found", name)
break
else:
print("no Ops member in", number, "rows")
expected = ["Home", "Login", "Cart"]
actual = ["Home", "Login", "Basket"]
for exp, act in zip(expected, actual, strict=True):
if exp != act:
print(f"mismatch: expected {exp}, got {act}")
attempt = 0
while True:
attempt += 1
if attempt >= 3:
break
print("attempts:", attempt)
1 2 4 no Ops member in 3 rows mismatch: expected Cart, got Basket attempts: 3
Only modules, functions, classes and comprehensions create a scope (the area where a name is visible). A name set inside a for loop or an if block is still visible after it, and the loop variable keeps its last value. That is why number could be printed after the loop above. A comprehension variable does not leak out.
How to answer in an interview
For an output question, list the values the loop produces first, then trace each pass: "range(1, 6) gives 1 to 5. At 3 continue skips the print; at 5 break runs first. So the output is 1 2 4." For "how do you write a switch in Python?", answer with match for 3.10 and later, show a two-case example, and mention the dict-of-functions approach for older code.
Common mistakes
- Expecting
range(1, 5)to include 5. - Thinking a loop's
elseruns after every loop. It runs only when nobreakhappened. - Using
value or defaultwhen 0 or an empty string is a valid value (theorwould replace it with the default). - Writing
for i in len(items):.lenreturns a number, which you cannot loop over; useenumerate(items). - A
while Truepolling loop with no limit, which can hang a test run.
Recap
Conditions use truthiness and can chain comparisons. match checks patterns top to bottom with no fall-through. for walks any iterable, range excludes its stop value, and enumerate and zip replace index counting. break leaves, continue skips, and a loop else means "no break". Loops do not create a new scope.
8 questions0/8 solved
| Status | Question | Difficulty | Asked in |
|---|---|---|---|
| Not started | break and continue in one loop | Easy | Asked in: TCS, Wipro |
| Not started | Loops in Python, and break versus continue | Easy | Asked in: TCS, Wipro |
| Pro+ | The else clause of a for loop | Easy-Medium | |
| Pro+ | Structural pattern matching with match | Medium | |
| Pro+ | What does range produce? | Easy-Medium | Asked in: TCS |
| Pro+ | What do and and or return? | Easy-Medium | |
| Pro+ | enumerate and zip | Easy-Medium | |
| Pro+ | The loop variable after the loop | Medium |
The first 2 questions of each topic are free. Pro+ opens every question.