Control flow structures in Python allow you to alter the flow of the program based on certain conditions or loops. This tutorial covers conditional statements (if, elif, else), loops (for, while), and exception handling.
1. Conditional Statements
1.1. if
Statement
The if
statement is used to execute a block of code only if a certain condition is true.
x = 10
if x > 0:
print("x is positive")
1.2. if-else
Statement
The if-else
statement allows you to execute one block of code if a condition is true and another block if the condition is false.
x = -5
if x > 0:
print("x is positive")
else:
print("x is non-positive")
1.3. if-elif-else
Statement
The if-elif-else
statement allows you to check multiple conditions.
x = 0
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
2. Loops
2.1. for
Loop
The for
loop is used for iterating over a sequence (such as a list, tuple, or string) or other iterable objects.
# Iterate over a range
for i in range(5):
print(i)
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
2.2. while
Loop
The while
loop is used to repeatedly execute a block of code as long as the condition is true.
counter = 0
while counter < 5:
print(counter)
counter += 1
2.3. break
and continue
Statements
The break
statement is used to exit the loop prematurely, and the continue
statement is used to skip the rest of the code inside the loop for the current iteration.
# Example of break statement
for i in range(10):
if i == 5:
break
print(i)
# Example of continue statement
for i in range(5):
if i == 2:
continue
print(i)
3. Exception Handling
Exception handling allows you to gracefully handle errors that may occur during the execution of your code.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful")
finally:
print("This code will run no matter what")
This tutorial provides an overview of control flow structures in Python. As you gain experience, explore more complex control flow scenarios and learn about additional features like nested loops and advanced exception handling. Practice implementing control flow in different situations to reinforce your understanding.
Next up: