Loops help us repeat actions, making our code more efficient and easier to read. There are two main types of loops in Python: while loops and for loops.
4.2.1 while Loop
A while loop runs as long as a condition is true. It checks the condition before each iteration and stops running when the condition is no longer true.
# Syntax of while loop while condition:
code to run while the condition is true
Example: Add 1 to a number until it reaches 10.
number = 1 while number < 10 print(number) number += 1
4.2.2 for Loop
A for loop repeats a block of code a specific number of times. It is commonly used to iterate over a sequence (like a list, tuple, or string).
# Syntax of for loop
for variable in sequence: code to run for each element in the sequence
Example: Say "As- Salaam- Alaikum" to each friend in a list of friends.
friends = ["Sami", "Raza", "Moosa"] for friend in friends: print("Welcome to ", friend)
Output: Welcome to: Sami Welcome to: Raza Welcome to: Moosa
Explanation: In this example, the code goes through each friend in the list and prints a greeting message for each one.