Fixed Top Ad (Local Preview)800x90 • Slot 6608427872
Loops
✕1. 🔁 Loops
- Imagine playing songs from a playlist. The music player plays the first song. Then it moves to the next song. It keeps doing this until all songs are played. A loop works in a similar way.
A loop is used to execute a block of code repeatedly. Loops help us avoid writing the same code again and again.
Example without loop:
print("Hello")print("Hello")print("Hello")Example with loop:for i in range(3):print("Hello")Output: Hello Hello Hello - Loops are useful when we want to: ✅ Repeat a task multiple times ✅ Process each item in a list, tuple, set, or dictionary ✅ Work with strings character by character ✅ Calculate totals, products, counts, etc. ✅ Avoid code repetition Example scenarios: - Playing each song in a playlist - Displaying each notification one by one - Checking each item in a shopping cart - Printing all names from a list - Calculating total marks from a list of marks - Repeating a task until a condition becomes False
- Python mainly has two types of loops: 1. for loop 2. while loop 📌 for loop is mostly used when we know what sequence we want to loop through. 📌 while loop is mostly used when repetition depends on a condition.
1.1 What is a Loop?
1.2 Why Use Loops?
1.3 Types of Loops in Python
2. 🔂 for Loop
- A
forloop is used to iterate over a sequence. 📌 To iterate means to go through each item one by one. A sequence can be: - List - Tuple - Set - String - Dictionary - range() Syntax:for item in sequence:code to repeat📌 The code inside theforloop must be indented. - Example:
numbers = [1, 2, 3]for item in numbers:print(item ** 2)Output: 1 4 9 Here,itemtakes each value from the list one by one. - A string is also a sequence of characters.
Example:
for char in "Hello":print(char.upper())Output: H E L L O - When looping through a dictionary, we can use
items()to get both key and value. Example:user_data = {"name": "Rabindra", "age": 30}for key, value in user_data.items():print(f"{key}: {value}")Output: name: Rabindra age: 30 range()is used when we want to repeat a task a specific number of times. Example:for i in range(5):print(i)Output: 0 1 2 3 4 📌range(5)gives numbers from 0 to 4. 📌 The stop value is not included.- Example 1:
for i in range(1, 6):print(i)Output: 1 2 3 4 5 Example 2:for i in range(0, 10, 2):print(i)Output: 0 2 4 6 8 Here: start ➜ 0 stop ➜ 10, not included step ➜ 2
2.1 What is for Loop?
2.2 for Loop with List
2.3 for Loop with String
2.4 for Loop with Dictionary
2.5 for Loop with range()
2.6 More range() Examples
3. 🔄 while Loop
- A
whileloop repeats a block of code as long as a condition is True. Imagine charging your phone. While the battery is less than 100%, charging continues. When the battery reaches 100%, charging stops. Awhileloop works in a similar way. Syntax:while condition:code to repeat📌 The loop continues while the condition is True. 📌 The loop stops when the condition becomes False. - Example:
count = 0while count < 5:print(count)count = count + 1Output: 0 1 2 3 4 Here,countincreases by 1 each time. Whencountbecomes 5, the conditioncount < 5becomes False, so the loop stops. - Example:
num = 10while num > 0:print(num)num = num - 2Output: 10 8 6 4 2 - If the condition never becomes False, the loop runs forever. This is called an infinite loop.
Example:
count = 0while count < 5:print(count)⚠️ This loop does not stop becausecountis never updated. Correct version:count = 0while count < 5:print(count)count = count + 1📌 Always make sure the condition can become False in awhileloop.
3.1 What is while Loop?
3.2 while Loop Example
3.3 Countdown Example
3.4 Infinite Loop Warning
4. 🚦 Loop Control Statements
- Loop control statements are used to change the normal flow of a loop.
Python has two common loop control statements:
-
break-continue📌breakstops the loop completely. 📌continueskips the current iteration and moves to the next iteration. - Imagine searching your wardrobe for a specific shirt. Once you find the shirt, you stop searching immediately.
breakworks in a similar way. 📌breakis used to exit the loop immediately. Example:for i in range(10):if i == 5:breakprint(i)Output: 0 1 2 3 4 📌 Whenibecomes 5,breakstops the loop. - Imagine listening to a playlist. If you do not like one song, you skip it and move to the next song.
continueworks in a similar way. 📌continueis used to skip the current iteration. Example:for i in range(1, 6):if i == 3:continueprint(i)Output: 1 2 4 5 📌 Whenibecomes 3,continueskips printing 3 and moves to the next value. - Example:
i = 10while i > 0:i = i - 1if i % 2 == 0:continueprint(i)Output: 9 7 5 3 1 📌 Even numbers are skipped because ofcontinue.
4.1 What are Loop Control Statements?
4.2 break
4.3 continue
4.4 continue with while Loop
5. ✅ Loop else
- Imagine searching your bag for your keys. If you find the keys, you stop searching early. If you check every item and still do not find the keys, you conclude that the keys are not in the bag.
The
elseblock in a loop works in a similar way. Python allowselsewith loops. Theelseblock runs only when the loop completes normally. If the loop stops because ofbreak, theelseblock does not run. 📌 loop else is usually used when searching for something. - Example:
for i in range(5):print(i)else:print("Loop completed successfully")Output: 0 1 2 3 4 Loop completed successfully Here, the loop completed normally, soelseran. - Example:
for i in range(5):if i == 3:breakprint(i)else:print("Loop completed successfully")Output: 0 1 2 Here, the loop stopped because ofbreak, soelsedid not run. - Example:
numbers = [1, 3, 5, 7]for num in numbers:if num % 2 == 0:print("Even number found")breakelse:print("No even number found")Output: No even number found 📌elseruns becausebreakwas not used.
5.1 What is loop else?
5.2 for else without break
5.3 for else with break
5.4 Search Example with loop else
6. 🔁 Nested Loops
- Imagine seats arranged in rows and columns. For each row, we check each seat in that row. A nested loop works in a similar way.
A loop inside another loop is called a nested loop. The outer loop goes through rows. The inner loop goes through items inside each row. The inner loop runs completely for each iteration of the outer loop.
Example:
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 - Example:
for i in range(1, 4):for j in range(1, 4):print(f"{i} x {j} = {i * j}")Output: 1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9
6.1 What is Nested Loop?
6.2 Multiplication Table Example
7. 🧾 Comprehensions
- A comprehension is a short way to create a collection using a loop in one line.
Comprehensions are commonly used to create:
- Lists
- Sets
- Dictionaries
They are useful when the logic is simple and easy to read.
Example using normal loop:
squares = []for x in range(5):squares.append(x ** 2)print(squares)# ➜ [0, 1, 4, 9, 16] Same example using list comprehension:squares = [x ** 2 for x in range(5)]print(squares)# ➜ [0, 1, 4, 9, 16] 📌 Comprehensions help us write shorter code. 📌 For complex logic, normal loops are usually easier to read. - Basic structure:
[expression for item in sequence]Here: expression ➜ What to store item ➜ Variable used in loop sequence ➜ Collection or range to loop through Example:squares = [x ** 2 for x in range(5)]Here:x ** 2➜ Expressionx➜ Itemrange(5)➜ Sequence
7.1 What is a Comprehension?
7.2 Basic Comprehension Structure
8. 📋 List Comprehension
- List comprehension is used to create a list in a short way.
Syntax:
[expression for item in sequence]Example:squared = [x ** 2 for x in range(5)]print(squared)# ➜ [0, 1, 4, 9, 16] - We can add
ifcondition in list comprehension. Syntax:[expression for item in sequence if condition]Example:num_list = [1, 2, 3, 4, 5]even_numbers = [x for x in num_list if x % 2 == 0]print(even_numbers)# ➜ [2, 4] 📌 This keeps only numbers that satisfy the condition. - When using if else inside a comprehension, the if else expression comes before for.
Syntax:
[expression_if_true if condition else expression_if_false for item in sequence]Example:num_list = [1, 2, 3, 4, 5]result = ["Even" if x % 2 == 0 else "Odd" for x in num_list]print(result)# ➜ ["Odd", "Even", "Odd", "Even", "Odd"] 📌 Useif elsewhen every item should produce a result. - Normal loop:
num_list = [1, 2, 3, 4, 5]even_numbers = []for x in num_list:if x % 2 == 0:even_numbers.append(x)print(even_numbers)# ➜ [2, 4] List comprehension:num_list = [1, 2, 3, 4, 5]even_numbers = [x for x in num_list if x % 2 == 0]print(even_numbers)# ➜ [2, 4]
8.1 What is List Comprehension?
8.2 List Comprehension with Condition
8.3 List Comprehension with if else
8.4 Normal Loop vs List Comprehension
9. 🔘 Set Comprehension
- Set comprehension is used to create a set in a short way. It uses curly braces
{ }. Syntax:{expression for item in sequence}Example:num_set = {x ** 2 for x in range(5)}print(num_set)# ➜ {0, 1, 4, 9, 16} 📌 Set stores unique values only. 📌 Output order may be different because sets are unordered. - Example:
num_list = [1, 2, 2, 3, 4, 4, 5]even_set = {x for x in num_list if x % 2 == 0}print(even_set)# ➜ {2, 4} - Example:
num_set = {x if x % 2 == 0 else x + 1 for x in range(10)}print(num_set)# ➜ {0, 2, 4, 6, 8, 10} Here: Odd numbers are converted to the next even number. Duplicate values are stored only once because this is a set. - Example:
country_names = ["Nepal", "usa", "UK"]country_upper = {country.upper() for country in country_names}print(country_upper)# ➜ {"NEPAL", "USA", "UK"}
9.1 What is Set Comprehension?
9.2 Set Comprehension with Condition
9.3 Set Comprehension with if else
9.4 String Example with Set Comprehension
10. 📖 Dictionary Comprehension
- Dictionary comprehension is used to create a dictionary in a short way. It stores data as key-value pairs.
Syntax:
{key: value for item in sequence}Example:num_list = [1, 2, 3]squared_dict = {x: x ** 2 for x in num_list}print(squared_dict)# ➜ {1: 1, 2: 4, 3: 9} - Example:
countries = ["Nepal", "usa", "UK"]country_dict = {country: len(country) for country in countries}print(country_dict)# ➜ {"Nepal": 5, "usa": 3, "UK": 2} - Example:
marks = {"Ram": 80, "Sita": 45, "Hari": 30}passed_students = {name: mark for name, mark in marks.items() if mark >= 40}print(passed_students)# ➜ {"Ram": 80, "Sita": 45} - Example:
marks = {"Ram": 80, "Sita": 45, "Hari": 30}result = {name: "Pass" if mark >= 40 else "Fail" for name, mark in marks.items()}print(result)# ➜ {"Ram": "Pass", "Sita": "Pass", "Hari": "Fail"}
10.1 What is Dictionary Comprehension?
10.2 Dictionary Comprehension with Strings
10.3 Dictionary Comprehension with Condition
10.4 Dictionary Comprehension with if else
11. ⚖️ When to Use Comprehensions
- Use comprehensions when: ✅ Logic is short ✅ Code is easy to read ✅ We are creating a new list, set, or dictionary ✅ We are applying simple transformation or filtering
- Use normal loops when:
✅ Logic is long
✅ Multiple steps are needed
✅ Many conditions are involved
✅ We need better readability
✅ We need to use
breakorcontinue
11.1 Use Comprehensions When
11.2 Use Normal Loops When
