Mastering Python Control Flow: Loops and Conditionals
🐍 Python Loop and Branching Statements
Python provides powerful structures for iteration (loops) and flow control (branching statements) that allow you to execute blocks of code repeatedly or conditionally.
Python Loop Statements
Loops are used to execute a block of code multiple times. The main loop types in Python are while and for.
1. The while Loop
The while loop repeatedly executes a block of statements as long as a given condition is True.
- Syntax:
while condition: # statement(s) to be executed
Key Point: You must ensure that the condition eventually becomes False to avoid an infinite loop. This is typically done by modifying a variable within the loop body.
Example:
count = 0
while count < 3:
print(f"Count is {count}")
count += 1
# Output:
# Count is 0
# Count is 1
# Count is 22. The for Loop
The for loop is used to iterate over a sequence (like a list, tuple, string, or dictionary) or other iterable objects.
- Syntax:
for item in iterable: # statement(s) to be executed for each item
Iterable: Any object capable of returning its members one at a time.
Example (Iterating over a list):
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
# Output:
# I like apple
# I like banana
# I like cherry3. The range() Function
The range() function is often used with the for loop to generate a sequence of numbers.
- Syntax:
range(stop): Generates numbers from 0 up to (but not including)stop.range(start, stop): Generates numbers fromstartup to (but not including)stop.range(start, stop, step): Generates numbers fromstartup tostop, incrementing bystep.
Example:
# range(5) -> 0, 1, 2, 3, 4
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 44. Nested Loop Structures
A nested loop is a loop inside another loop. The inner loop executes completely for every single iteration of the outer loop.
Example (Creating a multiplication table):
for i in range(1, 3): # Outer loop (i=1, then i=2)
for j in range(1, 3): # Inner loop (j=1, then j=2)
print(f"{i} x {j} = {i * j}")
# Output:
# 1 x 1 = 1
# 1 x 2 = 2
# 2 x 1 = 2
# 2 x 2 = 45. Inserting Conditions in Loops
You can use conditional statements (if/elif/else) inside loops to execute certain code only when a specific condition is met during an iteration. Conversely, you can also use a loop inside a conditional block.
Example (Using if inside a for loop):
numbers = [1, 2, 3, 4, 5, 6]
for num in numbers:
if num % 2 == 0: # Check if the number is even
print(f"{num} is even.")
else:
print(f"{num} is odd.")Python Branching Statements
Branching statements (also known as loop control statements) are used to change the execution flow from its normal sequence.
1. break Statement
The break statement immediately terminates the current loop (both for and while) and transfers execution to the statement immediately following the loop.
Example:
for letter in "Python":
if letter == "h":
break
print(letter)
# Output:
# P
# y
# t2. continue Statement
The continue statement skips the rest of the code inside the current iteration of the loop and proceeds to the next iteration.
Example:
for i in range(5): # 0, 1, 2, 3, 4
if i == 2:
continue # Skips the print statement for i=2
print(i)
# Output:
# 0
# 1
# 3
# 43. pass Statement
The pass statement is a null operation; nothing happens when it executes. It is often used as a placeholder when a statement is syntactically required but you do not want any code to execute.
Example:
for item in [1, 2, 3]:
if item == 2:
pass # To be implemented later (e.g., logging)
else:
print(item)
# Output:
# 1
# 3Working with Python Lists
Python lists are versatile data structures used to store an ordered collection of items that can be of any data type. You can create a list using square brackets or the list() constructor. For example, fruits = ["apple", "banana", "cherry"] creates a list with three string elements, while nums = list((1, 2, 3)) converts a tuple into a list. Lists are mutable, meaning you can modify their contents after creation. For instance, you can update an element by index: fruits[1] = "orange" changes “banana” to “orange”.
To add elements, lists provide methods such as append() which adds an item at the end (fruits.append("date")), extend() which adds multiple items from another iterable (fruits.extend(["fig", "grape"])), and insert() which places an item at a specific index (fruits.insert(1, "blueberry")). You can also update multiple elements simultaneously using slicing, like fruits[1:3] = ["blackberry", "kiwi"].
For deleting elements, Python lists offer several options: the del statement removes elements by index or slice (del fruits[0] removes the first element), the remove() method deletes the first occurrence of a value (fruits.remove("kiwi")), and the pop() method removes and returns an element at a specific index, or the last element if no index is provided (last = fruits.pop() removes and returns the last fruit). To clear all elements, you can use fruits.clear().
Python lists come with many built-in functions and methods that facilitate manipulation, including len() to get the number of items, max() and min() to find the largest and smallest elements, sum() to add numeric items, count() to find how many times a value occurs, and index() to find the position of a value. Lists can be sorted in place with sort() or you can create a new sorted list using the built-in sorted() function. Additionally, reverse() reverses the order of elements, and copy() creates a shallow copy of the list.
📑 Python Tuples and Sets
Both Tuples and Sets are core collection types in Python, each serving distinct purposes based on their inherent properties of order and mutability.
Python Tuples
A Tuple is an ordered and immutable sequence of items. Tuples are created using a comma-separated sequence of values, typically enclosed in parentheses (), such as my_tuple = (1, "a", 3.14). Since tuples are immutable, you cannot update, add, or delete elements directly. The common workaround for an “update” is to convert the tuple to a list (list(my_tuple)), modify the list, and then convert it back to a tuple (tuple(modified_list)). Tuples can be joined (concatenated) using the addition operator (+), which creates a new tuple (e.g., t1 + t2). The primary built-in methods are limited to those that read information: count(value), which returns the number of occurrences of a value, and index(value), which returns the index of the first occurrence.
Python Sets
A Set is an unordered collection of unique and immutable items. Sets are mutable containers, meaning you can add or remove items, but the items themselves must be immutable (like numbers or strings). Sets are created using curly braces {} (e.g., my_set = {1, 2, 3}) or the set() constructor for an empty set. To add items, you use add(item) for a single item or update(iterable) for multiple items. To remove items, you can use remove(item) (raises an error if not present) or the safer discard(item) (does nothing if not present). You can also remove an arbitrary item using pop() or remove all items with clear(). Sets excel at joining and comparison using set methods (often corresponding to mathematical set operations).
Set Joining and Comparison Methods
The key joining/comparison methods are: union() (|) to combine elements, intersection() (&) to find common elements, difference() (-) to find elements in the first set but not the second, and symmetric_difference() (^) to find elements present in either set but not both. Other methods include issubset() and issuperset().
