Loops

Concept of Loops

  • Used to execute a block of code repeatedly until a certain condition is met
  • Helps to avoid code repetition and makes code more efficient
  • Example Scenarios:
    1. Processing items in a list: printing all item, calculating sum, send mail to all etc.
    2. Performing task multiple times: printing a message multiple times
    3. Iterating over data structures: traversing a linked list, accessing elements of an array, etc.
    Type of Loops in Python:
    1. for
    2. while

for Loop

  • Used to iterate over sequences (list, tuple, string, etc.)
  • Syntax:
    1. for item in sequence:{expression}
    Example:
    1. for item in [1, 2, 3]: # can be list, tuple, set print(item ** 2)
    2. for char in "Hello": print(char.upper())
    3. user_data = {"name": "Rabindra", "age": 30} for key, value in user_data.items(): print(f"{key}: {value}")

while Loop

  • Executes as long as condition is True
  • Syntax:
    1. while condition:{expression}
    Example:
    1. count = 0 while count < 5: print(count) count = count + 1
    2. num = 10 while num > 0: print(num) num = num - 2

Transfer

  • Used to alter normal flow of loops based on certain conditions.
  • There are two transfer statements in Python: break and continue
  • break => exits the loop, continue => skips the current iteration of the loop.
  • Example:
    1. for i in range(10): if i == 5: break print(i)
    2. i = 10 while i > 0: i = i - 1 if i % 2 == 0: continue print(i)

for-else

  • Python provides an optional else clause that can be used with loops
  • else is executed when the loop completes without encountering a break statement
  • Example:
    1. for i in range(5): print(i) else: print("Loop completed successfully")
    2. for i in range(5): if i == 3: break print(i) else: print("Loop completed successfully")

Nested Loops

  • A loop inside another loop is called a nested loop
  • The inner loop is executed for each iteration of the outer loop
  • Example:
    1. for i in range(3): for j in range(2): print(f"i: {i}, j: {j}")
    2. for i in range(1, 4): for j in range(1, 4): print(f"{i} x {j} = {i * j}")

List Comprehensions

  • A concise way to create lists or sets using a single line of code
  • Syntax: [expression for item in sequence]
  • Example:
    1. squared = [x ** 2 for x in range(5)] print(squared) # [0, 1, 4, 9, 16]
    2. num_list = [1, 2, 3, 4, 5] even_numbers = [x for x in num_list if x % 2 == 0] print(even_numbers) # [2, 4]
    3. num_set = {x if x % 2 == 0 else x + 1 for x in range(10) } print(num_set) # {0, 2, 4, 6, 8}
    4. country_names = ["Nepal", "usa", "UK"] country_upper = {country.upper() for country in country_names} print(country_upper) # {"NEPAL", "USA", "UK"}

Dictionary Comprehensions

  • A concise way to create dictionaries using a single line of code
  • Syntax: {key: value for key, value in sequence}
  • Example:
    1. num_list = [1, 2, 3] squared_dict = {x: x ** 2 for x in num_list} print(squared_dict) # {1: 1, 2: 4, 3: 9}
    2. countries = ["Nepal", "usa", "UK"] country_dict = {country: len(country) for country in countries} print(country_dict) # {"Nepal": 5, "usa": 3, "UK": 2}