Loops

Python Mastery: From Beginner to Expert - Sykalo Eugene 2023

Loops
Basics of Python

Introduction to Loops

In programming, loops are used to execute a block of code repeatedly until a certain condition is met. This is a powerful concept that allows us to automate repetitive tasks and process large amounts of data efficiently.

There are two main types of loops in Python: for loops and while loops. For loops are used when we want to iterate over a sequence of values, such as a list or a range of numbers. While loops, on the other hand, are used when we want to repeatedly execute a block of code until a certain condition is met.

Loops can also be nested, which means that we can have one loop inside another loop. This is a useful technique when we need to perform a task that requires multiple iterations.

In addition to for and while loops, Python provides two loop control statements: break and continue. The break statement is used to exit a loop prematurely, while the continue statement is used to skip over certain iterations of a loop.

For Loops in Python

For loops are used to iterate over a sequence of values, such as a list or a range of numbers. The basic syntax of a for loop in Python is as follows:

for variable in sequence:
 # code to execute for each value in the sequence

Here, variable is a placeholder for the current value in the sequence, and sequence is the sequence of values to iterate over. The code inside the loop is executed once for each value in the sequence.

For example, consider the following code:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
 print(fruit)

This code iterates over the fruits list and prints each fruit to the console. The output of this code would be:

apple
banana
cherry

In addition to lists, for loops can also iterate over other types of sequences, such as strings and tuples. For example:

string = "hello"
for char in string:
 print(char)

This code iterates over the characters in the string variable and prints each character to the console. The output of this code would be:

h
e
l
l
o

We can also use the range() function to generate a sequence of numbers to iterate over. The range() function takes one, two, or three arguments, depending on how the sequence should be generated. The basic syntax of the range() function is as follows:

range(start, stop, step)

Here, start is the first number in the sequence (defaults to 0 if not specified), stop is the last number in the sequence (not inclusive), and step is the difference between each number in the sequence (defaults to 1 if not specified).

For example, consider the following code:

for i in range(5):
 print(i)

This code generates a sequence of numbers from 0 to 4 (inclusive) and prints each number to the console. The output of this code would be:

0
1
2
3
4

In addition to the basic syntax, for loops in Python can also include an optional else clause. The else clause is executed after the loop has finished iterating over the sequence. The syntax for a for loop with an else clause is as follows:

for variable in sequence:
 # code to execute for each value in the sequence
else:
 # code to execute after the loop has finished

For example, consider the following code:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
 print(fruit)
else:
 print("No more fruits")

This code iterates over the fruits list and prints each fruit to the console. After the loop has finished, the code inside the else block is executed and the message "No more fruits" is printed to the console. The output of this code would be:

apple
banana
cherry
No more fruits

While Loops in Python

While loops are used when we want to repeatedly execute a block of code until a certain condition is met. The basic syntax of a while loop in Python is as follows:

while condition:
 # code to execute while the condition is true

Here, condition is the condition that is checked before each iteration of the loop. The code inside the loop is executed repeatedly as long as the condition is true.

For example, consider the following code:

i = 0
while i < 5:
 print(i)
 i += 1

This code initializes a variable i to 0 and then enters a while loop. The loop continues to execute as long as i is less than 5. During each iteration of the loop, the current value of i is printed to the console, and i is incremented by 1. The output of this code would be:

0
1
2
3
4

In addition to simple conditions, while loops can also use more complex conditions, such as logical operators and comparison operators. For example:

number = 0
while number != 5:
 number = int(input("Enter a number: "))
 print("You entered", number)

This code prompts the user to enter a number repeatedly until they enter the number 5. During each iteration of the loop, the current value of number is printed to the console. The input() function is used to get input from the user, and the int() function is used to convert the input to an integer.

While loops can also be used with the else clause, just like for loops. The else clause is executed after the loop has finished executing, as long as the condition is no longer true. The syntax for a while loop with an else clause is as follows:

while condition:
 # code to execute while the condition is true
else:
 # code to execute after the loop has finished

For example, consider the following code:

i = 0
while i < 5:
 print(i)
 i += 1
else:
 print("Loop finished")

This code initializes a variable i to 0 and then enters a while loop. The loop continues to execute as long as i is less than 5. During each iteration of the loop, the current value of i is printed to the console, and i is incremented by 1. After the loop has finished executing, the code inside the else block is executed and the message "Loop finished" is printed to the console. The output of this code would be:

0
1
2
3
4
Loop finished

Loop Control Statements: break and continue

In addition to for and while loops, Python provides two loop control statements: break and continue. These statements allow us to alter the normal flow of a loop and provide more control over how the loop executes.

The break statement is used to exit a loop prematurely. When a break statement is encountered inside a loop, the loop is immediately terminated, and control is transferred to the next statement after the loop. This is useful when we want to exit a loop early, such as when we have found what we were looking for.

For example, consider the following code:

fruits = ["apple", "banana", "cherry", "orange", "pear"]
for fruit in fruits:
 if fruit == "cherry":
 break
 print(fruit)

print("Loop finished")

This code iterates over the fruits list and prints each fruit to the console. However, when the loop encounters the string "cherry", the break statement is executed, and the loop terminates early. The message "Loop finished" is then printed to the console. The output of this code would be:

apple
banana
Loop finished

The continue statement, on the other hand, is used to skip over certain iterations of a loop. When a continue statement is encountered inside a loop, the current iteration of the loop is skipped, and the loop proceeds with the next iteration. This is useful when we want to skip over certain values in a sequence, such as when we are processing data and want to ignore certain entries.

For example, consider the following code:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
 if number % 2 == 0:
 continue
 print(number)

print("Loop finished")

This code generates a sequence of numbers from 1 to 10 and prints each odd number to the console. When the loop encounters an even number, the continue statement is executed, and the current iteration of the loop is skipped. The message "Loop finished" is then printed to the console. The output of this code would be:

1
3
5
7
9
Loop finished

Nested Loops

Nested loops are a powerful technique that allows us to have one loop inside another loop. This is useful when we need to perform a task that requires multiple iterations, such as iterating over a two-dimensional array or a list of lists.

The basic syntax of a nested loop in Python is as follows:

for variable1 in sequence1:
 for variable2 in sequence2:
 # code to execute for each combination of variable1 and variable2

Here, variable1 is a placeholder for the current value in sequence1, and sequence1 is the sequence of values to iterate over in the outer loop. variable2 is a placeholder for the current value in sequence2, and sequence2 is the sequence of values to iterate over in the inner loop. The code inside the inner loop is executed once for each value in sequence2, for each value in sequence1.

For example, consider the following code:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
 for item in row:
 print(item)

This code iterates over a two-dimensional list matrix and prints each item to the console. The output of this code would be:

1
2
3
4
5
6
7
8
9

In addition to two-dimensional arrays, nested loops can also be used with other types of sequences, such as lists of lists or tuples of tuples.

List Comprehension with Loops

List comprehension is a concise way to create lists in Python. It allows us to create a new list by iterating over an existing sequence and applying a function or expression to each element in the sequence. The basic syntax of list comprehension in Python is as follows:

new_list = [expression for variable in sequence if condition]

Here, expression is the function or expression to apply to each element in the sequence, variable is a placeholder for the current value in the sequence, sequence is the sequence of values to iterate over, and condition is an optional condition that filters which elements from the sequence to include in the new list.

For example, consider the following code:

numbers = [1, 2, 3, 4, 5]
squares = [number**2 for number in numbers]
print(squares)

This code creates a new list squares by iterating over the numbers list and squaring each number in the list. The output of this code would be:

[1, 4, 9, 16, 25]

List comprehension can also be used with loops to create more complex expressions. For example:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_matrix = [item for row in matrix for item in row]
print(flattened_matrix)

This code creates a new list flattened_matrix by iterating over each row in the matrix list and then iterating over each item in the row. The output of this code would be:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

List comprehension with loops can be a powerful tool in Python that allows us to create complex expressions in a concise and readable way.