0% found this document useful (0 votes)
10 views9 pages

Only - Loop

The document provides a comprehensive overview of various looping constructs in Python, including for loops, while loops, and their combinations with conditionals and functions. It covers specific use cases such as looping through lists, dictionaries, and sets, as well as advanced techniques like list comprehensions, generators, and itertools. Each section includes code examples demonstrating the functionality and application of these loops.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views9 pages

Only - Loop

The document provides a comprehensive overview of various looping constructs in Python, including for loops, while loops, and their combinations with conditionals and functions. It covers specific use cases such as looping through lists, dictionaries, and sets, as well as advanced techniques like list comprehensions, generators, and itertools. Each section includes code examples demonstrating the functionality and application of these loops.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

1.

Basic For Loop

for i in range(5):
print(i)

::::::::::::::::::::::::::::::::::::

2. For Loop with List

fruits = ['apple', 'banana', 'cherry']


for fruit in fruits:
print(fruit)

:::::::::::::::::::::::::::::::::::::::::::::::::

3. For Loop with String

text = "Hello"
for char in text:
print(char)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::

4. For Loop with Enumerate

fruits = ['apple', 'banana', 'cherry']


for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

5. For Loop with Conditional

for i in range(10):
if i % 2 == 0:
print(f"{i} is even")

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::

6. Nested For Loop

for i in range(3):
for j in range(2):
print(f"i: {i}, j: {j}")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

7. While Loop

count = 0
while count < 5:
print(count)
count += 1

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

8. While Loop with Break


count = 0
while True:
if count >= 5:
break
print(count)
count += 1

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

9. While Loop with Continue

count = 0
while count < 5:
count += 1
if count == 3:
continue
print(count)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

10. Looping Through a Dictionary

student = {'name': 'John', 'age': 20}


for key, value in student.items():
print(f"{key}: {value}")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

11. Looping Through a Set

my_set = {1, 2, 3, 4}
for num in my_set:
print(num)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

12. List Comprehension with Loop

squares = [x**2 for x in range(10)]


print(squares)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

13. Using break in a For Loop

for i in range(10):
if i == 5:
break
print(i)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
14. Using continue in a For Loop

for i in range(10):
if i % 2 == 0:
continue
print(i)

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

15. Looping with zip()

names = ['Alice', 'Bob', 'Charlie']


ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

16. Looping with reversed()

for i in reversed(range(5)):
print(i)

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

17. Looping with sorted()

numbers = [5, 2, 9, 1]
for num in sorted(numbers):
print(num)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

18. Using range() with Step

for i in range(0, 10, 2):


print(i)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

19. Looping Through a Multi-Dimensional List

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


for row in matrix:
for num in row:
print(num)

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

20. Using else with Loops

for i in range(5):
print(i)
else:
print("Loop finished.")

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

21. Looping Through a String with Index


text = "Hello"
for i in range(len(text)):
print(f"Character at index {i} is {text[i]}")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

22. Using break in a While Loop

count = 0
while count < 10:
if count == 5:
break
print(count)
count += 1

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

23. Using continue in a While Loop

count = 0
while count < 10:
count += 1
if count % 2 == 0:
continue
print(count)
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

24. Looping Through a List of Tuples

pairs = [(1, 'one'), (2, 'two'), (3, 'three')]


for number, word in pairs:
print(f"{number}: {word}")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

25. Looping with a Custom Range Function

def custom_range(start, end):


while start < end:
yield start
start += 1

for i in custom_range(1, 5):


print(i)

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

26. Looping with a List of Dictionaries

students = [{'name': 'Alice', 'age': 20}, {'name': 'Bob', 'age': 22}]


for student in students:
print(f"{student['name']} is {student['age']} years old.")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

27. Looping with a Generator


def countdown(n):
while n > 0:
yield n
n -= 1

for number in countdown(5):


print(number)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

28. Looping with filter()

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
for num in even_numbers:
print(num)

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
29. Looping with map()

numbers = [1, 2, 3, 4]
squared_numbers = map(lambda x: x**2, numbers)
for num in squared_numbers:
print(num)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

30. Looping with reduce()

from functools import reduce

numbers = [1, 2, 3, 4]
sum_of_numbers = reduce(lambda x, y: x + y, numbers)
print(sum_of_numbers)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

31. Looping with itertools.cycle()

import itertools

colors = ['red', 'green', 'blue']


for color in itertools.cycle(colors):
print(color)
if color == 'blue':
break

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

32. Looping with itertools.chain()

import itertools

list1 = [1, 2, 3]
list2 = [4, 5, 6]
for number in itertools.chain(list1, list2):
print(number)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

33. Looping with itertools.product()

import itertools

colors = ['red', 'green']


sizes = ['S', 'M', 'L']
for combination in itertools.product(colors, sizes):
print(combination)

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

34. Looping with while and User Input

while True:
user_input = input("Enter a number (or 'exit' to quit): ")
if user_input.lower() == 'exit':
break
print(f"You entered: {user_input}")

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

35. Looping with a Flag

found = False
for i in range(10):
if i == 5:
found = True
break
if found:
print("Found 5!")

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

36. Looping with a Counter

count = 0
for i in range(10):
count += 1
print(f"Loop ran {count} times.")

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

37. Looping with a List of Lists

list_of_lists = [[1, 2], [3, 4], [5, 6]]


for sublist in list_of_lists:
for item in sublist:
print(item)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

38. Looping with a Condition on the Index


numbers = [10, 20, 30, 40, 50]
for i in range(len(numbers)):
if i % 2 == 0:
print(f"Index {i} has value {numbers[i]}")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

39. Looping with a Timer

import time

for i in range(5):
print(i)
time.sleep(1) # Wait for 1 second
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

40. Looping with a Random Condition

import random

for i in range(10):
if random.choice([True, False]):
print(f"{i} is selected")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

41. Looping with a Condition on Length

words = ["apple", "banana", "cherry", "date"]


for word in words:
if len(word) > 5:
print(f"{word} is longer than 5 characters.")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

42. Looping with a Condition on Value

numbers = [1, 2, 3, 4, 5, 6]
for num in numbers:
if num > 3:
print(f"{num} is greater than 3.")

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

43. Looping with a List of Mixed Types

mixed_list = [1, 'apple', 3.14, 'banana']


for item in mixed_list:
if isinstance(item, str):
print(f"{item} is a string.")

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

44. Looping with a Dictionary Comprehension

squares = {x: x**2 for x in range(5)}


for key, value in squares.items():
print(f"{key} squared is {value}.")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

45. Looping with a Custom Function

def print_numbers(n):
for i in range(n):
print(i)

print_numbers(5)

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

46. Looping with a Condition on Even and Odd

for i in range(10):
if i % 2 == 0:
print(f"{i} is even.")
else:
print(f"{i} is odd.")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

47. Looping with a Condition on Prime Numbers

def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True

for i in range(20):
if is_prime(i):
print(f"{i} is a prime number.")

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

48. Looping with a Condition on Fibonacci Sequence

def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b

for num in fibonacci(10):


print(num)

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

49. Looping with a Condition on Factorials


def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result

for i in range(6):
print(f"Factorial of {i} is {factorial(i)}.")

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

50. Looping with a Condition on Palindromes

def is_palindrome(s):
return s == s[::-1]

words = ["radar", "hello", "level", "world"]


for word in words:
if is_palindrome(word):
print(f"{word} is a palindrome.")

You might also like