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
Practice QuestionsNot started
1. Loop Basics
Question 1 of 7
- Display numbers from 1 to 10 using a
forloop. - Display numbers from 1 to 10 using a
whileloop. - Display even numbers from 1 to 20 using a
forloop. - Display odd numbers from 1 to 20 using a
whileloop. - Assign
num = 7. Display its factorial using aforloop. - Assign
num = 7. Display its factorial using awhileloop.
1.1 Practice basic loop tasks:- Display numbers from 1 to 10 using a
2. Looping Through Collections
Question 2 of 7
- Assign
num_tuple = (1, 4, 7, 12, 20). Using a loop, find even numbers and their sum. - Assign
num_set = {1, 3, 5, 7, 9}. Using a loop, find odd numbers and their product. - Assign a list of numbers. Find the second largest number in it using a
forloop. - Store fruit names in a list. Generate a new list such that: if fruit name starts with a or A, convert it to uppercase, otherwise convert it to lowercase. Use both normal
forloop and list comprehension. - Print this pattern using loops:
***************
2.1 Practice tasks looping through collections:- Assign
3. break and continue
Question 3 of 7
- Generate a new list
evaluated_datausing aforloop. Rules: - If the number is odd, double it. - If the number is even, triple it. - If you encounter 4, skip it. - If you encounter 8, stop the loop. - Use
breakto stop a loop when number 5 is found in this list:[1, 2, 3, 4, 5, 6, 7] - Use
continueto skip negative numbers from this list:[1, -3, 4, -2, 7, -8]
3.1 Assign list as[1, 4, 5, 7, 8, 12]3.2 Practice break and continue tasks:- Generate a new list
4. Dictionary and loop else
Question 4 of 7
- Using a loop, display the names of students who are absent in the Python class.
- If number 10 is found, display:
10 found - If number 10 is not found, display:
10 not found - Use loop else.
4.1 Student records are stored asstudent_record = {"9843": {"course": "Python", "name": "Ram", "present": False}, "9844": {"course": "Java", "name": "Shyam", "present": True}, "9845": {"course": "Python", "name": "Sita", "present": True}}4.2 Write a program to search for number 10 in a list.5. Nested Loops
Question 5 of 7
- Print multiplication tables from 1 to 5 using nested loops.
- Print all pairs from two lists:
names = ["Ram", "Sita"]andsubjects = ["Python", "SQL"]. Expected pairs:Ram - PythonRam - SQLSita - PythonSita - SQL
5.1 Practice nested loop tasks:6. Comprehensions
Question 6 of 7
- Create a list of squares from 0 to 9 using list comprehension.
- Create a list of even numbers from 1 to 20 using list comprehension.
- Create a set of uppercase country names from:
["Nepal", "usa", "UK"] - Create a dictionary where numbers from 1 to 5 are keys and their squares are values.
- Given
marks = {"Ram": 80, "Sita": 45, "Hari": 30}, create a dictionary showing "Pass" or "Fail" for each student.
6.1 Practice comprehension tasks:7. Bonus Loop Challenge
Question 7 of 7
- The first letter of each word should always be uppercase.
- If the previous letter comes earlier in the alphabet than the current letter, the current letter should be uppercase.
- If the previous letter comes later in the alphabet than the current letter, the current letter should be lowercase.
- If the previous letter is the same as the current letter, keep the current letter unchanged.
Example:
Input:
applE is fruitOutput:APple IS FRUiTExplanation: A โ First letter, uppercase 1st P โ Previous letter A comes earlier, uppercase 2nd p โ Previous letter P is same, no change l โ Previous letter P comes later, lowercase e โ Previous letter L comes later, lowercase I โ First letter of new word, uppercase S โ Previous letter I comes earlier, uppercase
7.1 This is an advanced challenge. Try it after completing the previous questions. Write a function that accepts a string and returns output using the following rules:
