PYTHON PROGRAMS
LOOPING PROGRAMS
1. Basic for Loop
2. Basic while Loop
3. for Loop with List
4. while Loop with break
5. for Loop with continue
6. Nested for Loop
7. Looping Through a Dictionary
8. Using enumerates in a for Loop
9. Using zip in a for Loop
10. Using List Comprehensions
11. Looping with itertools
12. while Loop with try and except
13. Error Handling in Loops
14. Simple if Statement
15. if-else Statement
16. if-elif-else Statement
17. Nested if Statements
18. Using if Statement with Logical Operators
19. Using if-elif Statement with String Comparison
20. Break Statement
21. Continue Statement
22. Pass Statement
23. Try-Except-Finally Block
24. Loop with Else
25. Looping with a Decrementing Range
26. Looping with a Step Value
27. Looping with a Generator
28. Looping with a Recursion
29. Looping with a Conditional
30. Looping Through a List of Tuples
31. Looping Through a Range with Conditional Logic (Fizz & Buzz)
32. Looping with itertools.permutations
33. Looping with itertools.combinations
34. Using a List as a Queue in a Loop
35. Using itertools.cycle with a Condition
PATTERN PROGRAMS
1. Right-Angled Triangle Pattern
2. Inverted Right-Angled Triangle Pattern
3. Pyramid Pattern
4. Diamond Pattern
5. Number Pyramid Pattern
6. Pascal's Triangle
7. Floyd's Triangle
8. Checkerboard Pattern
9. Inverted Number Pattern
10. Right-Angled Triangle with Numbers
11. Character Pattern: Right Triangle
12. Hollow Square Pattern
13. Hollow Pyramid Pattern
14. Butterfly Pattern
15. Hourglass Pattern
16. Spiral Number Pattern
17. Zigzag Pattern
18. Hollow Diamond Pattern
19. Diamond with Name in Center
20. Diamond Star Pattern
21. Hollow Rhombus Pattern
22. Palindrome Pattern
23. Alphabet Pattern (A-Z)
24. Printing a Square Pattern
1. Basic for Loop
# Program to print each character in a string
text = "Python"
for char in text:
print(char)
Output:
P
y
t
h
o
n
2. Basic while Loop
# Loop while a condition is true
count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
4
3. for Loop with List
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
4. While Loop with break
# Use break to exit the loop
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
Output:
0
1
2
3
4
5. for Loop with continue
# Use continue to skip an iteration
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
6. Nested for Loop
# Nested loop example
for i in range(3):
for j in range(3):
print(f'i: {i}, j: {j}')
Output:
i: 0, j: 0
i: 0, j: 1
i: 0, j: 2
i: 1, j: 0
i: 1, j: 1
i: 1, j: 2
i: 2, j: 0
i: 2, j: 1
i: 2, j: 2
7. Looping Through a Dictionary
# Loop through a dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}
for key, value in person.items():
print(f'{key}: {value}')
Output: name: Alice
age: 25
city: New York
8. Using enumerate in a for Loop
# Using enumerate to get index and value
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f'Index: {index}, Color: {color}')
Output: Index: 0, Color: red
Index: 1, Color: green
Index: 2, Color: blue
9. Using zip in a for Loop
# Using zip to iterate over multiple lists
names = ["John", "Jane", "Doe"]
scores = [85, 90, 78]
for name, score in zip(names, scores):
print(f'{name} scored {score}')
Output: John scored 85
Jane scored 90
Doe scored 78
10. Using List Comprehensions
# List comprehension with a loop
squares = [x ** 2 for x in range(5)]
print(squares)
Output: [0, 1, 4, 9, 16]
11. Looping with itertools
import itertools
# Using itertools to create an infinite loop
counter = itertools.count(start=0, step=2)
for i in range(5):
print(next(counter))
Output:
0
2
4
6
8
12. while Loop with try and except
# Handling errors within a loop
numbers = [10, 20, 0, 30]
for number in numbers:
try:
result = 100 / number
print(f'100 / {number} = {result}')
except ZeroDivisionError:
print(‘Cannot divide by zero')
Output:
100 / 10 = 10.0
100 / 20 = 5.0
Cannot divide by zero
100 / 30 = 3.3333333333333335
13. Error Handling in Loops
# Program to handle errors in a loop
values = ["10", "20", "thirty", "40"]
for value in values:
try:
num = int(value)
print(f"Converted {value} to {num}")
except ValueError:
print(f"Error: {value} is not a number")
Output:
Converted 10 to 10
Converted 20 to 20
Error: thirty is not a number
Converted 40 to 40
14. Simple if Statement
# Program to check if a number is positive
number = 10
if number > 0:
print(f"{number} is positive")
Output: 10 is positive
15. if-else Statement
# Program to check if a number is positive or negative
number = -5
if number > 0:
print(f"{number} is positive")
else:
print(f"{number} is negative")
Output: -5 is negative
16. if-elif-else Statement
# Program to check if a number is positive, negative, or zero
number = 0
if number > 0:
print(f"{number} is positive")
elif number < 0:
print(f"{number} is negative")
else:
print(f"{number} is zero")
Output: 0 is zero
17. Nested if Statements
# Program to check if a number is positive, negative, zero, and even or odd
number = -4
if number >= 0:
if number == 0:
print(f"{number} is zero")
else:
print(f"{number} is positive")
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
else:
print(f"{number} is negative")
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
Output:
-4 is negative
-4 is even
18. Using if Statement with Logical Operators
# Program to check if a number is within a specific range
number = 25
if 10 <= number <= 30:
print(f"{number} is within the range 10 to 30")
else:
print(f"{number} is outside the range 10 to 30")
Output: 25 is within the range 10 to 30
19. Using if-elif Statement with String Comparison
# Program to check the category of an animal
animal = "dog"
if animal == "cat":
print("This is a cat")
elif animal == "dog":
print("This is a dog")
else:
print("This is another type of animal")
Output: This is a dog
20. Break Statement
# Program to find the first number greater than 10 in a list
numbers = [4, 7, 10, 11, 15]
for num in numbers:
if num > 10:
print(f"First number greater than 10: {num}")
break
Output: First number greater than 10: 11
21. Continue Statement
# Program to print only odd numbers from 1 to 10
for i in range(1, 11):
if i % 2 == 0:
continue
print(i)
Output:
1
3
5
7
9
22. Pass Statement
# Program with a placeholder in a loop
for i in range(5):
if i == 2:
pass # Placeholder for future code
else:
print(i)
Output:
0
1
3
4
23. Try-Except-Finally Block
# Program to handle division by zero error
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed")
finally:
print("This will execute no matter what")
Output:
Error: Division by zero is not allowed
This will execute no matter what
24. Loop with Else
# Loop with an else clause
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 6:
print("Found 6!")
break
else:
print("6 not found in the list.")
Output:
6 not found in the list.
25. Looping with a Decrementing Range
# Looping with a decrementing range
for i in range(10, 0, -1):
print(i)
Output:
10
9
8
7
6
5
4
3
2
1
26. Looping with a Step Value
# Looping with a step value
for i in range(0, 10, 2):
print(i)
Output:
0
2
4
6
8
27. Looping with a Generator
# Looping with a generator
def countdown(n):
while n > 0:
yield n
n -= 1
for num in countdown(5):
print(num)
Output:
5
4
3
2
1
28. Looping with a Recursion
# Looping with recursion
def recursive_print(n):
if n <= 0:
return
print(n)
recursive_print(n - 1)
recursive_print(5)
Output:
5
4
3
2
1
29. Looping with a Conditional
# Looping with a conditional
i=1
while i <= 10:
if i % 2 == 0:
print(f'{i} is even')
else:
print(f'{i} is odd')
i += 1
Output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
30. Looping Through a List of Tuples
# Looping through a list of tuples
coordinates = [(1, 2), (3, 4), (5, 6)]
for x, y in coordinates:
print(f'x: {x}, y: {y}')
Output:
x: 1, y: 2
x: 3, y: 4
x: 5, y: 6
31. Looping Through a Range with Conditional Logic
# Looping through a range with conditional logic
for i in range(1, 21):
if i % 3 == 0 and i % 5 == 0:
print(f'{i}: FizzBuzz')
elif i % 3 == 0:
print(f'{i}: Fizz')
elif i % 5 == 0:
print(f'{i}: Buzz')
else:
print(i)
Output:
1
2
3: Fizz
4
5: Buzz
6: Fizz
7
8
9: Fizz
10: Buzz
11
12: Fizz
13
14
15: FizzBuzz
16
17
18: Fizz
19
20: Buzz
32. Looping with itertools.permutations
import itertools
# Using itertools.permutations to generate all permutations
letters = 'ABC'
permutations = itertools.permutations(letters)
for perm in permutations:
print(''.join(perm))
Output:
ABC
ACB
BAC
BCA
CAB
CBA
33. Looping with itertools.combinations
import itertools
# Using itertools.combinations to generate all combinations
letters = 'ABC'
combinations = itertools.combinations(letters, 2)
for comb in combinations:
print(''.join(comb))
Output:
AB
AC
BC
34. Using a List as a Queue in a Loop
# Using a list as a queue
queue = ["first", "second", "third"]
while queue:
item = queue.pop(0)
print(f' Processing: {item}')
Output:
Processing: first
Processing: second
Processing: third
35. Using itertools.cycle with a Condition
import itertools
# Using itertools.cycle with a condition
colors = ["red", "green", "blue"]
cycled_colors = itertools.cycle(colors)
for i in range(7):
color = next(cycled_colors)
print(color)
Output:
red
green
blue
red
green
blue
red
PATTERN PROGRAMS
1. Right-Angled Triangle Pattern
# Program to print a right-angled triangle pattern
n=5
for i in range(1, n+1):
print('*' * i)
Output:
*
**
***
****
*****
2. Inverted Right-Angled Triangle Pattern
# Program to print an inverted right-angled triangle pattern
n=5
for i in range(n, 0, -1):
print('*' * i)
Output:
*****
****
***
**
*
3. Pyramid Pattern
# Program to print a pyramid pattern
n=5
for i in range(1, n+1):
print(' ' * (n-i) + '*' * (2*i-1))
Output:
*
***
*****
*******
*********
4. Diamond Pattern
# Program to print a diamond pattern
n=5
# Upper part of the diamond
for i in range(1, n+1):
print(' ' * (n-i) + '*' * (2*i-1))
# Lower part of the diamond
for i in range(n-1, 0, -1):
print(' ' * (n-i) + '*' * (2*i-1))
Output:
*
***
*****
*******
*********
*******
*****
***
*
5. Number Pyramid Pattern
# Program to print a number pyramid pattern
n=5
for i in range(1, n+1):
for j in range(1, i+1):
print(j, end=' ')
print('')
Output:
1
12
123
1234
12345
6. Pascal's Triangle
# Program to print Pascal's triangle
def print_pascals_triangle(n):
for i in range(n):
for j in range(n-i+1):
print(end=" ")
C=1
for j in range(1, i+1):
print(C, end=" ")
C = C * (i - j) // j
print(1)
n=5
print_pascals_triangle(n)
Output:
1
11
111
1211
13311
7. Floyd's Triangle
# Program to print Floyd's triangle
n=5
num = 1
for i in range(1, n+1):
for j in range(1, i+1):
print(num, end=' ')
num += 1
print('')
Output:
1
23
456
7 8 9 10
11 12 13 14 15
8. Checkerboard Pattern
# Program to print a checkerboard pattern
n=5
for i in range(n):
for j in range(n):
if (i + j) % 2 == 0:
print('X', end=' ')
else:
print('O', end=' ')
print('')
Output:
XOXOX
OXOXO
XOXOX
OXOXO
XOXOX
9. Inverted Number Pattern
# Program to print an inverted number pattern
n=5
for i in range(n, 0, -1):
for j in range(1, i + 1):
print(j, end='')
print()
Output:
12345
1234
123
12
1
10. Right-Angled Triangle with Numbers
# Program to print a right-angled triangle with numbers
n=5
for i in range(1, n + 1):
for j in range(1, i + 1):
print(i, end='')
print()
Output:
1
22
333
4444
55555
11. Character Pattern: Right Triangle
# Program to print a right triangle character pattern
n=5
alphabet = 65 # ASCII value of 'A'
for i in range(n):
for j in range(i+1):
print(chr(alphabet + j), end='')
print()
Output:
A
AB
ABC
ABCD
ABCDE
12. Hollow Square Pattern
# Program to print a hollow square pattern
n=5
for i in range(n):
if i == 0 or i == n-1:
print('*' * n)
else:
print('*' + ' ' * (n-2) + '*')
Output:
*****
* *
* *
* *
*****
13. Hollow Pyramid Pattern
# Program to print a hollow pyramid pattern
n=5
for i in range(1, n + 1):
if i == 1:
print(' ' * (n - i) + '*')
elif i == n:
print('*' * (2 * n - 1))
else:
print(' ' * (n - i) + '*' + ' ' * (2 * i - 3) + '*')
Output:
*
**
* *
* *
*********
14. Diamond Number Pattern
# Program to print a diamond number pattern
n=5
# Upper part of diamond
for i in range(1, n+1):
print(' ' * (n-i) + ''.join(str(j) for j in range(1, i+1)) + ''.join(str(j) for j in range(i-1, 0,
-1)))
# Lower part of diamond
for i in range(n-1, 0, -1):
print(' ' * (n-i) + ''.join(str(j) for j in range(1, i+1)) + ''.join(str(j) for j in range(i-1, 0,
-1)))
Output:
1
121
12321
1234321
123454321
1234321
12321
121
1
15. Butterfly Pattern
# Program to print a butterfly pattern
n=5
# Upper part of butterfly
for i in range(1, n+1):
print('*' * i + ' ' * (2*(n-i)) + '*' * i)
# Lower part of butterfly
for i in range(n, 0, -1):
print('*' * i + ' ' * (2*(n-i)) + '*' * i)
Output:
* *
** **
*** ***
**** ****
**********
**********
**** ****
*** ***
** **
* *
16. Hourglass Pattern
# Program to print an hourglass pattern
n=5
# Upper part of hourglass
for i in range(n, 0, -1):
print(' ' * (n-i) + '*' * (2*i-1))
# Lower part of hourglass
for i in range(2, n+1):
print(' ' * (n-i) + '*' * (2*i-1))
Output:
*********
*******
*****
***
*
***
*****
*******
*********
17. Spiral Number Pattern
# Program to print a spiral number pattern
n=5
matrix = [[0]*n for _ in range(n)]
num = 1
left, right = 0, n-1
top, bottom = 0, n-1
while left <= right and top <= bottom:
for i in range(left, right+1):
matrix[top][i] = num
num += 1
top += 1
for i in range(top, bottom+1):
matrix[i][right] = num
num += 1
right -= 1
for i in range(right, left-1, -1):
matrix[bottom][i] = num
num += 1
bottom -= 1
for i in range(bottom, top-1, -1):
matrix[i][left] = num
num += 1
left += 1
for row in matrix:
print(' '.join(map(str, row)))
Output:
12345
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
18. Zigzag Pattern
# Program to print a zigzag pattern
n=9
zigzag_height = 3
for i in range(zigzag_height):
for j in range(n):
if (i + j) % (zigzag_height - 1) == 0:
print('*', end='')
else:
print(' ', end='')
print()
Output:
* * *
* ** *
** **
19. Hollow Diamond Pattern
# Hollow diamond pattern
n=5
for i in range(1, n+1):
for j in range(n-i):
print(' ', end='')
for j in range(2*i-1):
if j == 0 or j == 2*i-2:
print('*', end='')
else:
print(' ', end='')
print()
for i in range(n-1, 0, -1):
for j in range(n-i):
print(' ', end='')
for j in range(2*i-1):
if j == 0 or j == 2*i-2:
print('*', end='')
else:
print(' ', end='')
print()
Output:
*
**
* *
* *
* *
* *
* *
**
*
20. Diamond with Name in Center
# Diamond with name in center pattern
name = "PYTHON"
n=6
mid = n // 2
for i in range(n):
if i < mid:
spaces = mid - i
stars = 2 * i + 1
elif i == mid:
spaces = 0
stars = len(name)
else:
spaces = i - mid
stars = 2 * (n - i) - 1
print(' ' * spaces + '*' * stars)
print(name.center(n))
Output:
*
***
*****
PYTHON
*****
***
*
21. Diamond Star Pattern
# Diamond star pattern
rows = 5
for i in range(1, rows + 1):
print(' ' * (rows - i) + '* ' * i)
for i in range(rows - 1, 0, -1):
print(' ' * (rows - i) + '* ' * i)
Output:
*
**
***
****
*****
****
***
**
*
22. Hollow Rhombus Pattern
# Hollow rhombus pattern
rows = 5
for i in range(rows):
print(' ' * (rows - i - 1) + '*' * rows if i == 0 or i == rows - 1 else '*' + ' ' * (rows - 2)
+ '*')
Output:
*****
* *
* *
* *
*****
23. Palindrome Pattern
# Palindrome pattern
n=5
for i in range(1, n+1):
print(' ' * (n-i), end='')
for j in range(1, i+1):
print(j, end='')
for j in range(i-1, 0, -1):
print(j, end='')
print()
Output:
1
121
12321
1234321
123454321
24. Alphabet Pattern (A-Z)
# Alphabet pattern (A-Z)
n=5
ascii_value = 65 # ASCII value of 'A'
for i in range(1, n+1):
for j in range(1, i+1):
print(chr(ascii_value), end=' ')
ascii_value += 1
print()
Output:
A
BC
DEF
GHIJ
KLMNO
25. Printing a Square Pattern
def print_square(n):
for i in range(n):
for j in range(n):
print("*", end=" ")
print()
# Example usage
print_square(5)
Output:
*****
*****
*****
*****
*****