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
- Processing items in a list: printing all item, calculating sum, send mail to all etc.
- Performing task multiple times: printing a message multiple times
- Iterating over data structures: traversing a linked list, accessing elements of an array, etc.
- for
- while
Example Scenarios:
Type of Loops in Python:
for Loop
- Used to iterate over sequences (list, tuple, string, etc.)
- for item in sequence:{expression}
for item in [1, 2, 3]:# can be list, tuple, setprint(item ** 2)for char in "Hello": print(char.upper())user_data = {"name": "Rabindra", "age": 30} for key, value in user_data.items(): print(f"{key}: {value}")
Syntax:
Example:
while Loop
- Executes as long as condition is True
- while condition:{expression}
count = 0 while count < 5: print(count) count = count + 1num = 10 while num > 0: print(num) num = num - 2
Syntax:
Example:
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.for i in range(10): if i == 5: break print(i)i = 10 while i > 0: i = i - 1 if i % 2 == 0: continue print(i)
Example:
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
for i in range(5): print(i) else: print("Loop completed successfully")for i in range(5): if i == 3: break print(i) else: print("Loop completed successfully")
Example:
Nested Loops
- A loop inside another loop is called a nested loop
- The inner loop is executed for each iteration of the outer loop
for i in range(3): for j in range(2): print(f"i: {i}, j: {j}")for i in range(1, 4): for j in range(1, 4): print(f"{i} x {j} = {i * j}")
Example:
List Comprehensions
- A concise way to create lists or sets using a single line of code
- Syntax:
[expression for item in sequence] squared = [x ** 2 for x in range(5)] print(squared)# [0, 1, 4, 9, 16]num_list = [1, 2, 3, 4, 5] even_numbers = [x for x in num_list if x % 2 == 0] print(even_numbers)# [2, 4]num_set = {x if x % 2 == 0 else x + 1 for x in range(10) } print(num_set)# {0, 2, 4, 6, 8}country_names = ["Nepal", "usa", "UK"] country_upper = {country.upper() for country in country_names} print(country_upper)# {"NEPAL", "USA", "UK"}
Example:
Dictionary Comprehensions
- A concise way to create dictionaries using a single line of code
- Syntax:
{key: value for key, value in sequence} num_list = [1, 2, 3] squared_dict = {x: x ** 2 for x in num_list} print(squared_dict)# {1: 1, 2: 4, 3: 9}countries = ["Nepal", "usa", "UK"] country_dict = {country: len(country) for country in countries} print(country_dict)# {"Nepal": 5, "usa": 3, "UK": 2}
Example:
