Python Loops: for & while

Python Loops: A Comprehensive Guide for Beginners

 

Table of Contents

  1. Introduction to Loops in Python
  1. The “for” Loop
  1. The “while” Loop
  1. Nested Loops
  1. Breaking out of Loops
  1. Skipping Iterations with “continue”
  1. The “else” Clause in Loops
  1. Benefits of Using Loops in Python
  1. Code Examples

1. Introduction to Loops in Python

Loops are constructs that allow you to repeat a block of code multiple times based on a set of conditions. They are particularly useful when you need to perform repetitive tasks or iterate over a sequence of values.
In Python, there are two main types of loops: the “for” loop and the “while” loop. Both loops follow a similar structure – they check a condition, execute the code block if the condition is true, and then update the condition before repeating the process. The key difference between the two lies in the way they handle the iteration process.
Loops play a crucial role in programming because they allow you to automate repetitive tasks, iterate over data structures, and simplify complex operations. Without loops, you would need to write repetitive code for each task, leading to redundancy and decreased efficiency. Loops enable you to write concise and elegant code, making your Python programs more readable and maintainable.

2. The “for” Loop

The “for” loop is the most commonly used loop in Python. It is designed to iterate over a sequence of values, such as a list, tuple, dictionary, set, or string. The “for” loop allows you to perform a specific action for each element in the sequence, making it an essential tool for processing data and performing repetitive operations.

Syntax and Working Principle

The syntax of the “for” loop is as follows:

for variable in sequence:     
   # code block to be executed

 

Here’s how the “for” loop works:
1) The loop starts by assigning the first element of the sequence to the variable.
2) The code block under the loop is executed.
3) The loop moves to the next element in the sequence, and the process is repeated until all elements have been iterated over.

Iterating over a Sequence

Let’s look at an example to understand how the “for” loop iterates over a sequence:

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

##Output:
apple 
banana 
cherry

The “for” loop iterates over each element in the fruits list and prints it. The loop starts with the first element, “apple”, assigns it to the fruit variable, executes the code block (printing the value of fruit), and then moves on to the next element. This process continues until all elements have been processed.

The Versatility of the “for” Loop

The “for” loop in Python is highly versatile and can be used in various scenarios. Some of the common use cases for the “for” loop include:

  • Iterating over a range of numbers
  • Processing elements of a list or other data structures
  • Iterating over the characters of a string
  • Working with dictionaries and sets

The “range()” Function

The “range()” function generates a sequence of numbers that can be used with the “for” loop to repeat an action a certain number of times. It is a built-in function that enhances the functionality of the “for” loop.
The basic syntax of the range() function is as follows:

range(start, stop, step)

  • start (optional): The starting value of the sequence (default is 0).
  • stop (required): The value at which the sequence stops (exclusive).
  • step (optional): The increment between each value in the sequence (default is 1).

An example of using the range() function with the “for” loop:

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

##Output:
0 
1 
2 
3 
4

Here, the “for” loop iterates over the values generated by the range(5) function, which creates a sequence from 0 to 4. The loop assigns each value to the variable “i” and prints it.
Therefore, it is a powerful tool when combined with the “for” loop, allowing you to iterate over a specific range of numbers and perform actions accordingly.

3. The “while” Loop

The “while” loop is another fundamental loop in Python that repeats a block of code as long as a specified condition is true. Unlike the “for” loop, which iterates over a sequence of values, the “while” loop continues executing until its condition becomes false.

Syntax and Working Principle

The syntax of the “while” loop is as follows:

while condition:
# code block to be executed

Here’s how the “while” loop works:
1) The loop checks the condition before executing the code block.
2) If the condition is true, the code block is executed.
3) After executing the code block, the loop goes back to step 1 and checks the condition again.
4) The loop continues executing as long as the condition remains true.

Controlling the Loop with Conditions

Let’s look at an example of the “while” loop to understand how it works:

orders = 0
while orders < 5:
   print(orders)     
   orders += 1
##Output:
0 
1 
2 
3 
4

The first step the”while” loop does, is to check if the “orders” variable is less than 5. Since the initial value of “orders” is 0, the condition is true, and the code block is executed. After printing the value of count, the loop increments the value of “orders” by 1 (using orders += 1) and goes back to check the condition again. This process repeats until the condition becomes false (when “orders” is no longer less than 5).
The “while” loop is especially useful when the number of iterations is not known beforehand and depends on a specific condition.

Infinite Loops and How to Avoid Them

One thing to be cautious about when using the “while” loop is the possibility of creating an infinite loop. An infinite loop occurs when the condition of the loop is always true, causing the loop to continue indefinitely. This can lead to your program freezing or consuming excessive system resources. To prevent infinite loops, ensure that the condition within the loop eventually becomes false. You can achieve this by including an exit condition within the loop or by using control statements like break to terminate the loop when a certain condition is met.

4. Nested Loops

In Python, you can have loops within loops, known as nested loops. Nested loops are powerful constructs that allow you to perform complex iterations, such as generating a matrix or iterating over multi-dimensional arrays.
The concept of nested loops is straightforward – one loop is placed inside another loop. The inner loop is executed completely for each iteration of the outer loop. This nested structure allows you to iterate over multiple dimensions or perform operations that require multiple levels of iteration.
Here’s an example of a nested loop in Python:

for i in range(3):     
    for j in range(3):         
        print(i, j)

##Output:
0 0 
0 1 
0 2 
1 0 
1 1 
1 2 
2 0 
2 1 
2 2

The outer loop iterates over the values 0, 1, and 2. For each value of “i”, the inner loop iterates over the same set of values. The output shows the combination of “i” and “j” for each iteration, forming a 3×3 grid.
Nested loops are commonly used when working with multi-dimensional data structures or when generating patterns that require multiple levels of iteration.

5. Breaking out of Loops

Sometimes, you may need to exit a loop prematurely based on certain conditions. Python provides the “break” statement, which allows you to break out of a loop and skip the remaining iterations.
The break statement is a control statement that is used to exit the current loop. When encountered, the break statement immediately terminates the loop and continues execution with the next statement after the loop:

for num in range(10): 
    print(num)
    if num == 5:     
        break 

##Output:
0
1
2
3
4
5

The “for” loop iterates over the numbers from 0 to 9. When the value of num reaches 5, the condition num == 5 is true, and the “break” statement is executed. As a result, the loop is terminated, and the remaining iterations are skipped. Only the numbers 0 to 5 are printed.

Prematurely Exiting a Loop

The “break” statement can also be used with the “while” loop to exit the loop prematurely based on certain conditions. Here’s an example:

count = 0  
while count < 10:     
   if count == 5:    
      print(count)      
      break         
      count += 1
## Output:
5

As long as the value of count is less than 10, the “while” loop keeps running. When count equals 5, the “break” statement is executed, terminating the loop. As a result, the only number printed is 5.
The “break” statement is a powerful tool for controlling the flow of your loops and it can help you optimize your code and improve its efficiency.

6. Skipping Iterations with “continue”

In addition to prematurely exiting a loop, there are situations where you may want to skip the current iteration and continue with the next one. To do so, you can use the “continue” statement. When encountered, the “continue” statement skips the remaining code in the current iteration and moves on to the next iteration of the loop. An example of using the continue statement in a “for” loop:

for num in range(10):     
   if num == 5:         
       continue 
   print(num)

###Output:
0 
1 
2 
3 
4 
6 
7 
8 
9

The “for” loop iterates over the numbers from 0 to 9 as usual. When the value of num is 5, the condition num == 5 is true, and the “continue” statement is executed. As a result, the remaining code in the current iteration (the print(num) statement) is skipped, and the loop proceeds to the next iteration. Hence, the number 5 is not printed in the output.

Skipping Specific Iterations

The “continue” statement can also be used with the “while” loop to ignore specific iterations:

count = 0  
while count < 10:     
   count += 1     
   if count % 2 == 0:         
       continue     
   print(count)

##Output:
1
3 
5 
7 
9

In this example, the “while” loop continues as long as the value of count is less than 10. Within each iteration, the value of count is incremented by 1. The condition count % 2 == 0 checks if “count” is an even number. If so, the continue statement is executed, skipping the remaining code in the current iteration. As a result, only the odd numbers are showed. The “continue” statement provides a way to avoid specific iterations of a loop based on certain conditions. It allows you to control the flow of your loop and selectively execute code as needed.

7. The “else” Clause in Loops

In Python, you have the option to pair an “else” clause with a loop. The “else” clause is executed after the loop finishes its execution, but only if the loop was not terminated by a “break” statement. This can be useful when you want to execute additional code after a loop has completed its iterations.

The Role of the “else” Clause

The “else” clause in loops is a simple way to specify code that should be executed after the loop has finished its iterations. It is often used when you want to perform certain actions only when the loop completes successfully and  as long as there are no “break” statements.
For example:

for i in range(5):     
    print(i) 
else:     
    print("Loop has ended")

## Output:
0 
1 
2 
3 
4 
Loop has ended

The “for” loop iterates over the numbers from 0 to 4. After completing all iterations, the “else” clause is executed, printing the message “Loop has ended”. This script works because the loop finishes its iterations without any “break” statement.

Executing Code After a Loop

The “else” clause can also be used with the “while” loop to execute code after the loop has finished its iterations:

count = 0  
while count < 5:     
    print(count)     
    count += 1 
else:     
    print("Loop has ended")

##Output:
0 
1
2 
3 
4 
Loop has ended

In this example, the “while” loop continues as long as the value of “count” is less than 5. After completing all iterations, the “else” clause is executed, printing the message “Loop has ended”. The “else” clause in loops provides a way to specify code that should be executed after the loop has finished its iterations. It allows you to perform additional actions based on the completion of the loop with more control over the flow of your code.

8. Benefits of Using Loops in Python

Loops are an essential tool in Python programming, offering numerous benefits that make your code more efficient and flexible. Some of the key benefits of using loops are the following:

Automation and Efficiency

One of the main benefits of using loops is the ability to automate repetitive tasks. Instead of writing the same lines of code multiple times, you can use loops to iterate over a sequence of values and perform the desired actions. This automation saves you time and effort, making your programs more efficient and less prone to errors. Loops also allow you to handle large amounts of data without the need for manual intervention. Whether you are processing thousands of records or performing complex calculations, loops enable you to automate these tasks and handle them easily.

Simplifying Complex Operations

Loops are invaluable when it comes to simplifying complex operations. Instead of writing convoluted code with numerous conditional statements, you can use loops to manage intricate operations in a more structured and readable manner.
For example, if you need to perform calculations on each element of a list or process data from a file, loops may be an efficient way to iterate over the elements and apply the necessary operations. This simplification makes your code more maintainable and easier to understand for your co-workers and other developers.

Iterating over Data Structures

Python’s loops are particularly powerful when it comes to iterating over data structures such as lists, dictionaries, sets, and strings. Loops allow you to access each element or character in the data structure and perform operations on them individually. By iterating over a list, for example, you can process each item or extract specific information based on different conditions. Similarly, you can iterate over a dictionary to access both the keys and values, so you can perform actions on them or extract specific information from the dictionary. The flexibility to work with various data structures and manipulate their contents as needed is one of the main advantages of Python loops.

Streamlining Game Development

Loops are incredibly useful in game development, where repetitive actions and iterations are common. Whether you are creating a simple text-based game or a complex graphical game, loops allow you to handle game logic, update game states, and process user input efficiently.
For instance, in a game where the player has to navigate through a maze, you can use loops to continuously update the player’s position, check for collisions, and respond to user input. Loops provide the necessary structure and efficiency to handle the dynamic nature of games, making them a powerful tool for game developers.

9. Code Examples

To demonstrate the power and versatility of loops in Python, let’s explore some additional examples. These examples will showcase different use cases for loops, helping you understand how to apply them in your own projects.

Example 1: Finding the Sum of Numbers

numbers = [1, 2, 3, 4, 5] 
accumulated = 0 
for num in numbers:     
   accumulated += num  
print("The sum of the numbers is:", accumulated)

##Output:
The sum of the numbers is: 15

The “for” loop iterates over each number in the pre-defined list and add it to the “accumulated” variable. After completing all iterations, the final sum is displayed.

Example 2: Printing Patterns

size = 5  
for i in range(size):     
    print("*" * (i + 1))

##Output:
* 
** 
*** 
**** 
*****

The “for” loop to shows a triangle of asterisks. The loop iterates over the range of numbers from 0 to size – 1 and prints the corresponding number of asterisks for each iteration.

 

 


Python and Excel Projects for practice
Register New Account
Shopping cart