Loops

โœ•

1. ๐Ÿ” Loops

    1.1 What is a Loop?
    1. 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
    1.2 Why Use Loops?
    1. 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
    1.3 Types of Loops in Python
    1. 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.

2. ๐Ÿ”‚ for Loop

    2.1 What is for Loop?
    1. A for loop 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 the for loop must be indented.
    2.2 for Loop with List
    1. Example: numbers = [1, 2, 3]for item in numbers:print(item ** 2)Output: 1 4 9 Here, item takes each value from the list one by one.
    2.3 for Loop with String
    1. A string is also a sequence of characters. Example: for char in "Hello":print(char.upper())Output: H E L L O
    2.4 for Loop with Dictionary
    1. 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
    2.5 for Loop with range()
    1. 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.
    2.6 More range() Examples
    1. 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

3. ๐Ÿ”„ while Loop

    3.1 What is while Loop?
    1. A while loop 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. A while loop 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.
    3.2 while Loop Example
    1. Example: count = 0while count < 5:print(count)count = count + 1Output: 0 1 2 3 4 Here, count increases by 1 each time. When count becomes 5, the condition count < 5 becomes False, so the loop stops.
    3.3 Countdown Example
    1. Example: num = 10while num > 0:print(num)num = num - 2Output: 10 8 6 4 2
    3.4 Infinite Loop Warning
    1. 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 because count is never updated. Correct version: count = 0while count < 5:print(count)count = count + 1 ๐Ÿ“Œ Always make sure the condition can become False in a while loop.

4. ๐Ÿšฆ Loop Control Statements

    4.1 What are Loop Control Statements?
    1. Loop control statements are used to change the normal flow of a loop. Python has two common loop control statements: - break - continue ๐Ÿ“Œ break stops the loop completely. ๐Ÿ“Œ continue skips the current iteration and moves to the next iteration.
    4.2 break
    1. Imagine searching your wardrobe for a specific shirt. Once you find the shirt, you stop searching immediately. break works in a similar way. ๐Ÿ“Œ break is used to exit the loop immediately. Example: for i in range(10):if i == 5:breakprint(i)Output: 0 1 2 3 4 ๐Ÿ“Œ When i becomes 5, break stops the loop.
    4.3 continue
    1. Imagine listening to a playlist. If you do not like one song, you skip it and move to the next song. continue works in a similar way. ๐Ÿ“Œ continue is used to skip the current iteration. Example: for i in range(1, 6):if i == 3:continueprint(i)Output: 1 2 4 5 ๐Ÿ“Œ When i becomes 3, continue skips printing 3 and moves to the next value.
    4.4 continue with while Loop
    1. Example: i = 10while i > 0:i = i - 1if i % 2 == 0:continueprint(i)Output: 9 7 5 3 1 ๐Ÿ“Œ Even numbers are skipped because of continue.

5. โœ… Loop else

    5.1 What is loop else?
    1. 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 else block in a loop works in a similar way. Python allows else with loops. The else block runs only when the loop completes normally. If the loop stops because of break, the else block does not run. ๐Ÿ“Œ loop else is usually used when searching for something.
    5.2 for else without break
    1. 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, so else ran.
    5.3 for else with break
    1. 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 of break, so else did not run.
    5.4 Search Example with loop else
    1. Example: numbers = [1, 3, 5, 7]for num in numbers:if num % 2 == 0:print("Even number found")break else:print("No even number found")Output: No even number found ๐Ÿ“Œ else runs because break was not used.

6. ๐Ÿ” Nested Loops

    6.1 What is Nested Loop?
    1. 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
    6.2 Multiplication Table Example
    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

7. ๐Ÿงพ Comprehensions

    7.1 What is a Comprehension?
    1. 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.
    7.2 Basic Comprehension Structure
    1. 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 โžœ Expression x โžœ Item range(5) โžœ Sequence

8. ๐Ÿ“‹ List Comprehension

    8.1 What is List Comprehension?
    1. 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]
    8.2 List Comprehension with Condition
    1. We can add if condition 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.
    8.3 List Comprehension with if else
    1. 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"] ๐Ÿ“Œ Use if else when every item should produce a result.
    8.4 Normal Loop vs List Comprehension
    1. 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]

9. ๐Ÿ”˜ Set Comprehension

    9.1 What is Set Comprehension?
    1. 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.
    9.2 Set Comprehension with Condition
    1. 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}
    9.3 Set Comprehension with if else
    1. 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.
    9.4 String Example with Set Comprehension
    1. Example: country_names = ["Nepal", "usa", "UK"]country_upper = {country.upper() for country in country_names}print(country_upper) # โžœ {"NEPAL", "USA", "UK"}

10. ๐Ÿ“– Dictionary Comprehension

    10.1 What is Dictionary Comprehension?
    1. 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}
    10.2 Dictionary Comprehension with Strings
    1. Example: countries = ["Nepal", "usa", "UK"]country_dict = {country: len(country) for country in countries}print(country_dict) # โžœ {"Nepal": 5, "usa": 3, "UK": 2}
    10.3 Dictionary Comprehension with Condition
    1. 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}
    10.4 Dictionary Comprehension with if else
    1. 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"}

11. โš–๏ธ When to Use Comprehensions

    11.1 Use Comprehensions When
    1. 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
    11.2 Use Normal Loops When
    1. Use normal loops when: โœ… Logic is long โœ… Multiple steps are needed โœ… Many conditions are involved โœ… We need better readability โœ… We need to use break or continue

Practice QuestionsNot started

  1. 1. Loop Basics

    Question 1 of 7

      1.1 Practice basic loop tasks:
      1. Display numbers from 1 to 10 using a for loop.
      2. Display numbers from 1 to 10 using a while loop.
      3. Display even numbers from 1 to 20 using a for loop.
      4. Display odd numbers from 1 to 20 using a while loop.
      5. Assign num = 7. Display its factorial using a for loop.
      6. Assign num = 7. Display its factorial using a while loop.
  2. 2. Looping Through Collections

    Question 2 of 7

      2.1 Practice tasks looping through collections:
      1. Assign num_tuple = (1, 4, 7, 12, 20). Using a loop, find even numbers and their sum.
      2. Assign num_set = {1, 3, 5, 7, 9}. Using a loop, find odd numbers and their product.
      3. Assign a list of numbers. Find the second largest number in it using a for loop.
      4. 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 for loop and list comprehension.
      5. Print this pattern using loops: * ** *** **** *****
  3. 3. break and continue

    Question 3 of 7

      3.1 Assign list as [1, 4, 5, 7, 8, 12]
      1. Generate a new list evaluated_data using a for loop. 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.
      3.2 Practice break and continue tasks:
      1. Use break to stop a loop when number 5 is found in this list: [1, 2, 3, 4, 5, 6, 7]
      2. Use continue to skip negative numbers from this list: [1, -3, 4, -2, 7, -8]
  4. 4. Dictionary and loop else

    Question 4 of 7

      4.1 Student records are stored as student_record = {"9843": {"course": "Python", "name": "Ram", "present": False}, "9844": {"course": "Java", "name": "Shyam", "present": True}, "9845": {"course": "Python", "name": "Sita", "present": True}}
      1. Using a loop, display the names of students who are absent in the Python class.
      4.2 Write a program to search for number 10 in a list.
      1. If number 10 is found, display: 10 found
      2. If number 10 is not found, display: 10 not found
      3. Use loop else.
  5. 5. Nested Loops

    Question 5 of 7

      5.1 Practice nested loop tasks:
      1. Print multiplication tables from 1 to 5 using nested loops.
      2. Print all pairs from two lists: names = ["Ram", "Sita"] and subjects = ["Python", "SQL"]. Expected pairs: Ram - Python Ram - SQL Sita - Python Sita - SQL
  6. 6. Comprehensions

    Question 6 of 7

      6.1 Practice comprehension tasks:
      1. Create a list of squares from 0 to 9 using list comprehension.
      2. Create a list of even numbers from 1 to 20 using list comprehension.
      3. Create a set of uppercase country names from: ["Nepal", "usa", "UK"]
      4. Create a dictionary where numbers from 1 to 5 are keys and their squares are values.
      5. Given marks = {"Ram": 80, "Sita": 45, "Hari": 30}, create a dictionary showing "Pass" or "Fail" for each student.
  7. 7. Bonus Loop Challenge

    Question 7 of 7

      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:
      1. The first letter of each word should always be uppercase.
      2. If the previous letter comes earlier in the alphabet than the current letter, the current letter should be uppercase.
      3. If the previous letter comes later in the alphabet than the current letter, the current letter should be lowercase.
      4. If the previous letter is the same as the current letter, keep the current letter unchanged. Example: Input: applE is fruit Output: 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