Skip to content

Python Programming · Week 6 notes

Loops

Introduction to Loops

What are Loops in Python?

Loops are a fundamental concept in programming that allow you to execute a block of code repeatedly. They are essential for automating repetitive tasks and processing large amounts of data efficiently.

Why Use Loops?

  • Automate repetitive tasks
  • Process large datasets
  • Implement algorithms that require iteration
  • Create dynamic and interactive programs

Types of Loops in Python

Python provides two main types of loops:

  1. for loops: Used for iterating over a sequence (like a list, tuple, dictionary, set, or string) or other iterable objects.
  2. while loops: Used to execute a block of code as long as a condition is true.

Basic Structure of a Loop

# For loop for item in sequence: # Code to be executed for each item # While loop while condition: # Code to be executed as long as the condition is true

In the following lessons, we'll explore each type of loop in detail and learn about their various applications in Python programming.

For Loops

For Loops in Python

For loops are used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) or other iterable objects. They provide a concise way to execute a block of code for each item in a sequence.

Basic Syntax

for item in sequence: # Code to be executed for each item

Examples of For Loops

1. Iterating over a list:

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

2. Iterating over a string:

for char in "Python": print(char) # Output: # P # y # t # h # o # n

3. Using range() function:

for i in range(5): print(i) # Output: # 0 # 1 # 2 # 3 # 4

Nested For Loops

You can also nest for loops inside each other:

for i in range(3): for j in range(2): print(f"i: {i}, j: {j}") # Output: # i: 0, j: 0 # i: 0, j: 1 # i: 1, j: 0 # i: 1, j: 1 # i: 2, j: 0 # i: 2, j: 1

For loops are versatile and can be used in many different scenarios. In the next lesson, we'll explore while loops and compare them to for loops.

While Loops

While Loops in Python

While loops execute a block of code as long as a specified condition is true. They are useful when you don't know in advance how many times you need to execute a block of code.

Basic Syntax

while condition: # Code to be executed as long as the condition is true

Examples of While Loops

1. Basic while loop:

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

2. Using break to exit a while loop:

number = 0 while True: if number == 5: break print(number) number += 1 # Output: # 0 # 1 # 2 # 3 # 4

3. Using continue to skip an iteration:

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

While Loop vs For Loop

While loops are typically used when:

  • You don't know how many iterations you need in advance
  • You want to repeat an action until a specific condition is met
  • You need more complex loop control than what a for loop provides

For loops, on the other hand, are better when:

  • You want to iterate over a sequence of elements
  • You know the number of iterations in advance
  • You want to use the loop variable in your code

Understanding when to use each type of loop is crucial for writing efficient and readable Python code.

Loop Control Statements

Loop Control Statements in Python

Loop control statements change the execution from its normal sequence. Python supports the following loop control statements:

1. break statement

The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.

for letter in 'Python': if letter == 'h': break print(letter) # Output: # P # y # t

2. continue statement

The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.

for letter in 'Python': if letter == 'h': continue print(letter) # Output: # P # y # t # o # n

3. pass statement

The pass statement is a null operation; nothing happens when it executes. It's useful as a placeholder when a statement is required syntactically, but no code needs to be executed.

for letter in 'Python': if letter == 'h': pass print(letter) # Output: # P # y # t # h # o # n

Using else with Loops

Python allows the use of else with both for and while loops. The else block is executed when the loop condition becomes false:

for i in range(5): print(i) else: print("Loop completed normally") # Output: # 0 # 1 # 2 # 3 # 4 # Loop completed normally

Note that if a loop is exited with a break statement, the else block is not executed.

Understanding these loop control statements allows you to have finer control over your loops and create more complex and efficient algorithms.