Contents
Roadmap info from roadmap website
Conditionals
Conditional Statements in Python perform different actions depending on whether a specific condition evaluates to true or false. Conditional Statements are handled by IF-ELIF-ELSE statements and MATCH-CASE statements in Python.
Visit the following resources to learn more:
- @article@Python Conditional Statements: IF…Else, ELIF & Switch Case
- @article@Conditional Statements in Python
- @article@How to use a match statement in Python
Conditional Type | Syntax | Description | Use Case |
---|---|---|---|
if statement | if condition: | Executes a block of code if the condition evaluates to True . | Basic conditional execution. |
else statement | else: | Executes a block of code if the preceding if condition evaluates to False . | Provides an alternative code path. |
elif statement | elif condition: | Executes a block of code if the previous conditions are False and this one is True . | Adds multiple conditions. |
Nested if | if condition: <br> if condition: | An if statement inside another if or else block. | Allows more complex decision trees. |
if-else in one line (Ternary) | x = a if condition else b | Conditionally assigns a value in a single line. | Compact conditional assignment. |
match statement (Python 3.10+) | match value: <br> case pattern: | Matches a value against multiple patterns, similar to a switch-case in other languages. | Handling multiple conditions with pattern matching. |
while loop with else | while condition: <br> else: | Executes the else block if the while loop finishes normally (not interrupted by break ). | Adding a final action after a loop. |
for loop with else | for item in iterable: <br> else: | Executes the else block if the for loop finishes normally (not interrupted by break ). | Adding a final action after iteration. |
try-except | try: <br> except Exception: | Executes the except block if an exception is raised in the try block. | Error handling based on specific conditions. |
try-except-else | try: <br> except: <br> else: | Executes the else block if no exceptions are raised in the try block. | Handling code that should run only if no exceptions occur. |
try-finally | try: <br> finally: | Executes the finally block regardless of whether an exception was raised. | Ensuring cleanup actions always occur. |
with statement | with expression as variable: | Executes a block of code with context management, ensuring setup and teardown actions occur. | Managing resources like file streams. |