Control structures in Python are vital for determining the flow of program execution. They let the programmer make decisions, loop through sequences, and alter execution pathways based on certain conditions.
Selection:
1. 'if' statement:
The if statement in Python allows you to execute a block of code if a certain condition holds true. It has the following syntax:
if condition:
# code to be executed if the condition is true
Example of if statement:
x = 10
if x > 0:
print("x is positive")
2. 'if-else' statement:
The if-else statement in Python lets you execute one block of code if a condition is true and another if it's false. It has the following syntax:
if condition:
# code to be executed if the condition is true
else:
# code to be executed if the condition is false
Example of if-else statement:
x = 5
if x % 2 == 0:
print("x is even")
else:
print("x is odd")
3. 'elif' statement:
Python uses elif, a contraction of "else if", to handle multiple conditions in sequence. It has the following syntax:
if condition1:
# code to be executed if condition1 is true
elif condition2:
# code to be executed if condition1 is false and condition2 is true
else:
# code to be executed if both condition1 and condition2 are false
Example of elif statement:
x = 10
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
4. Nested 'if-else':
You can also nest if-else statements within each other to handle more intricate conditions.
Example:
x = 10
y = 5
if x > 5:
if y > 5:
print("both x and y are greater than 5")
else:
print("only x is greater than 5")
else:
print("x is not greater than 5")
5. Short hand if:
Python allows a concise way to write the if statement. It has the following syntax:
if condition: statement
Example:
x = 10
if x > 5: print("x is greater than 5")
6. Short hand if-else:
Python also offers a short version of the if-else statement, known as the ternary operation. It has the following syntax:
value_if_true if condition else value_if_false
Example:
x = 10
result = "x is positive" if x > 0 else "x is non-positive"
print(result)
Loops:
1. 'while' loop:
The while loop in Python repeatedly executes a block of code as long as a condition remains true. It has the following syntax:
while condition:
# code to be executed repeatedly as long as the condition is true
Example of while loop:
count = 0
while count < 5:
print("Count:", count)
count += 1
2. 'for' loop:
The for loop in Python is different from many traditional programming languages, as it's more like an iterator based loop, rather than a traditional numeric-based loop. The for loop iterates over any sequence, such as lists, strings, tuples, or dictionaries. It has the following syntax:
for variable in sequence :
# code to be executed for each item in the sequence
1. Iterating through a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits :
print(fruit)
2. Iterating through a string:
Strings are sequences of characters, so you can iterate through them using a for loop.
for char in "apple":
print(char)
3. Looping through dictionaries:
Using 'items()', you can retrieve both keys and values from a dictionary.
person = { "name": "John", "age" : 30 }
for key, value in person.items() :
print(key, value)
4. Nested loops:
You can have for loops inside for loops to iterate over multiple dimensions.
colors = ["red", "green"]
fruits = ["apple", "banana"]
for color in colors :
for fruit in fruits :
print(color, fruit)
Using the 'else' clause with Loops:
Unique to Python, a loop can have an else block that gets executed once the loop finishes, provided the loop didn't break out early.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits :
print(fruit)
else:
print("Loop finished!")
'range()' Function:
The `range()` function is a built-in function in Python that's commonly used with loops, especially the `for` loop, to generate a sequence of numbers. It's particularly helpful when you need to repeat a block of code a specific number of times.
Basic Syntax:
range(stop) # Generates numbers from 0 up to (but not including) 'stop'.
range(start, stop) # Generates numbers from 'start' up to (but not including) 'stop'.
range(start, stop, step) # Generates numbers from 'start', incrementing by 'step', up to (but not including) 'stop'.
1. Using 'range()' with a single argument:
If you provide only one argument to 'range()', it will generate numbers starting from 0 up to (but not including) the number you provided.
for i in range(5):
print(i)
Output:
0
1
2
3
4
2. Using 'range()' with two arguments:
Here, you can specify both the start and stop values.
for i in range(2, 5):
print(i)
Output:
2
3
4
3. Using 'range()' with three arguments:
The third argument is the `step`, which represents the increment value.
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
4. Iterating in reverse:
By using a negative step value, you can generate numbers in decreasing order.
for i in range(5, 1, -1):
print(i)
Output:
5
4
3
2
Points to Remember:
- The numbers produced by 'range()' are generated on-the-fly and aren't stored in memory (it produces an immutable sequence type). This makes it memory efficient when iterating over large ranges.
- The output from 'range()' is not a list. To convert it to a list, you can use the 'list()' function:
numbers = list(range(5))
print(numbers) # Output: [0, 1, 2, 3, 4]
List Comprehensions:
A list comprehension consists of an expression followed by a 'for' clause, and optionally, one or more 'if' clauses. The result is a new list that's constructed by evaluating the expression for each iteration of the 'for' loop, and including the result in the new list if the 'if' clause (if present) is true.
Basic Syntax:
[expression for item in iterable if condition]
Examples:
1. Basic List Comprehension:
Create a list of the squares of numbers from 0 to 4.
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
2. Using 'if' clause:
Create a list of even numbers from 0 to 9.
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # Output: [0, 2, 4, 6, 8]
3. Multiple 'for' clauses:
Create a list of combinations of two lists.
a = [1, 2]
b = [3, 4]
product = [(x, y) for x in a for y in b]
print(product) # Output: [(1, 3), (1, 4), (2, 3), (2, 4)]
4. Nested List Comprehensions:
Flatten a matrix into a list.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Jump Statements:
In Python, jump statements are used to alter the normal flow of control in a program. They allow you to transfer program control to a different part of the code. The two main jump statements are:
1. break statement:
The break statement is used to exit the current loop. When encountered, it terminates the innermost loop, and the control is transferred to the next statement after the loop. Here's an example:
for i in range(10):
if i == 5:
break
print(i, end=' ')
print("\nLoop ended.")
Output:
0 1 2 3 4
Loop ended.
2. continue statement:
The continue statement is used to skip the rest of the current iteration of a loop and move to the next iteration. It forces the loop to immediately jump to the next iteration without executing the remaining code inside the loop for the current iteration. Here's an example:
for i in range(5):
if i == 2:
continue
print(i, end=' ')
print("\nLoop ended.")
Output:
0 1 3 4
Loop ended.
These are the main control structures in Python. They provide powerful ways to control the flow of your program based on various conditions and loops.