Conditional Statements
Python uses
if, elif (else if), and else for decision-making. Significant indentation defines the code blocks.python
Single-line (Ternary) Expression: For simple
if/else logic in one line.python
Loops: for and while
1. for Loop
Use it to iterate over any sequence (list, string, range, tuple).
python
2. while Loop
Use it to repeat code as long as a condition is
True.python
Loop Control: break, continue, else
- break: Stops the loop completely.
- continue: Skips the current iteration and jumps to the next.
- pass: A null operation; used when syntax requires a statement but you don't want to do anything.
- else: (Wait!) In loops, the
elseblock runs only if the loop finishes normally (not if it's broken).
python
Structural Pattern Matching (match-case)
Introduced in Python 3.10, this is a powerful alternative to complex
if/elif chains.python
Advanced Case: Match against data structures and capture values.python
Summary
| Feature | Usage | Purpose |
|---|---|---|
| if/elif/else | if x > 0: | Branching |
| for | for x in seq: | Iteration |
| while | while x > 0: | Condition-based loop |
| break | break | Terminate loop |
| continue | continue | Skip iteration |
| match-case | match x: | Better branching (3.10+) |