Python Programs
Python Programs
GENERAL PROGRAMS
1. Find the GCD (Greatest Common Divisor) of Two Numbers
2. LCM (Least Common Multiple) of Two Numbers
3. Binary Search Algorithm
4. Find the Sum of a Geometric Series
5. Calculate Compound Interest
6. Merge Two Sorted Lists
7. Remove Duplicates from a List
8. Flatten a Nested List
9. Generate Fibonacci Sequence
10. Check if a Number is Perfect
11. Check if a Number is a Happy Number
12. Find the Second Largest Element in a List
13. Count Vowels and Consonants in a String
14. Remove Punctuation from a String
15. Find the Longest Word in a Sentence
16. Transpose a Matrix
17. Count the Frequency of Elements in a List
18. Rotate a List by K Elements
19. Check if Two Strings are Isomorphic
20. Find the Intersection of Two Lists
21. Binary to Decimal Conversion
22. Decimal to Binary Conversion
23. Sort a List of Tuples by the Second Element
24. Calculate the Area of Different Geometric Shapes (Circle, Triangle, Rectangle)
25. Check if a String is a Pangram
26. Generate a Random Password
27. Check if a Given Number is a Fibonacci Number
28. Implement a Stack using a List
29. Implement a Queue using a List
30. Find the Union of Two Lists
31. Check if a String is a Subsequence of Another String
32. Find the Maximum Product of Two Integers in a List
33. Implement Depth-First Search (DFS) for a Graph
34. Implement Breadth-First Search (BFS) for a Graph
35. Merge Intervals
36. Find the Kth Largest Element in a List
37. Calculate the Median of a List
38. Check if a Matrix is a Magic Square
39. Calculate the Power of a Number using Recursion
40. Find the Longest Common Subsequence (LCS) of Two Strings
41. Palindrome Check
42. Bubble Sort Algorithm
43. Count the Number of Words in a String
44. Find the Maximum Element in a 2D List
45. Calculate the Sum of Elements in a List
46. Calculate the Sum of Natural Numbers
47. Find the GCD of Two Numbers using Euclidean Algorithm
48. Rock, Paper, Scissors Game
49. Convert Kilometers to Miles
50. Simulate a Simple ATM System
51. Simple Alarm Clock
52. Check whether is a Leap Year or not.
53. Count Words in a Sentence
54. Reverse a String
55. Convert Decimal to Roman Numerals
56. Check if a String is an Isogram
57. Funny Chatbot with Random Quotes
58. Convert Celsius to Fahrenheit
59. Simple To-Do List Program
60. Calculate the Area of a Circle
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. Find the GCD (Greatest Common Divisor) of Two Numbers
def gcd(a, b):
while b:
a, b = b, a % b
return a
# Example usage
num1 = 48
num2 = 18
result = gcd(num1, num2)
print(f"The GCD of {num1} and {num2} is {result}")
# Example usage
num1 = 48
num2 = 18
result = lcm(num1, num2)
print(f"The LCM of {num1} and {num2} is {result}")
# Example usage
sorted_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target_value = 7
result = binary_search(sorted_list, target_value)
if result != -1:
print(f"The target value {target_value} is at index {result}.")
else:
print(f"The target value {target_value} is not in the list.")
# Example usage
a = 3 # First term
r = 2 # Common ratio
n = 4 # Number of terms
result = geometric_series_sum(a, r, n)
print(f"The sum of the geometric series with first term {a}, common ratio {r}, and {n}
terms is {result:.2f}")
Output: The sum of the geometric series with first term 3, common ratio 2, and 4
terms is 45.00
amount = calculate_compound_interest(P, r, n, t)
print(f"The amount after {t} years is ${amount:.2f}")
return merged_list
# Example usage:
list1 = [1, 3, 5, 7]
list2 = [2, 4, 6, 8]
# Example usage
my_list = [1, 2, 3, 2, 4, 5, 1, 3, 6]
result = remove_duplicates(my_list)
print(f"The original list is: {my_list}")
print(f"The list after removing duplicates is: {result}")
# Example usage
nested_list = [1, [2, 3], [4, [5, 6]], 7, [8, 9, [10]]]
flattened = flatten_list(nested_list)
print(f"The original nested list is: {nested_list}")
print(f"The flattened list is: {flattened}")
Output: The original nested list is: [1, [2, 3], [4, [5, 6]], 7, [8, 9, [10]]]
The flattened list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
return fib_sequence
# Example usage
terms = 10 # Number of terms in the Fibonacci sequence
fibonacci = fibonacci_sequence(terms)
print(f"The Fibonacci sequence of {terms} terms is: {fibonacci}")
Output: The Fibonacci sequence of 10 terms is: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
sum_of_divisors = 0
for i in range(1, number):
if number % i == 0:
sum_of_divisors += i
# Example usage
num = 28
result = is_perfect_number(num)
if result:
print(f"{num} is a perfect number.")
else:
print(f"{num} is not a perfect number.")
# Example usage
num = 19
result = is_happy_number(num)
if result:
print(f"{num} is a happy number.")
else:
print(f"{num} is not a happy number.")
return second
# Example usage
my_list = [10, 20, 4, 45, 30, 50, 25]
result = second_largest_element(my_list)
print(f"The second largest element in the list is: {result}")
# Example usage
input_string = "Hello World! How are you?"
vowels, consonants = count_vowels_and_consonants(input_string)
print(f"The string '{input_string}' has {vowels} vowels and {consonants} consonants.")
Output: The string 'Hello World! How are you?' has 7 vowels and 12 consonants.
def remove_punctuation(input_string):
# Define the set of punctuation characters
punctuations = string.punctuation
return no_punctuation_string
# Example usage
input_string = "Hello! How are you doing today? I'm doing well, thank you!"
cleaned_string = remove_punctuation(input_string)
print(f"Original string: {input_string}")
print(f"String after removing punctuation: {cleaned_string}")
Output:
Original string: Hello! How are you doing today? I'm doing well, thank you!
String after removing punctuation: Hello How are you doing today Im doing well
thank you.
# Initialize variables to keep track of the longest word and its length
longest_word = ""
max_length = 0
Output: The longest word in the sentence 'Hello from the other side' is: Hello
return transposed
# Example usage
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
transposed_matrix = transpose_matrix(matrix)
print("Original Matrix:")
for row in matrix:
print(row)
print("\nTransposed Matrix:")
for row in transposed_matrix:
print(row)
Output:
Original Matrix:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Transposed Matrix:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
return frequency_dict
# Example usage
my_list = [1, 2, 3, 2, 2, 4, 5, 1, 3]
frequency = count_frequency(my_list)
Output:
Element 1 occurs 2 times
Element 2 occurs 3 times
Element 3 occurs 2 times
Element 4 occurs 1 times
Element 5 occurs 1 times
return rotated_list
my_list = [1, 2, 3, 4, 5]
k=2
rotated = rotate_list(my_list, k)
print(f"The list {my_list} rotated by {k} elements is: {rotated}")
mapping = {}
mapped_chars = set()
return True
string1 = "egg"
string2 = "add"
result = are_isomorphic(string1, string2)
if result:
print(f"The strings '{string1}' and '{string2}' are isomorphic.")
else:
print(f"The strings '{string1}' and '{string2}' are not isomorphic.")
return decimal
binary_number = "101010"
decimal_number = binary_to_decimal(binary_number)
print(f"The binary number {binary_number} is equivalent to decimal: {decimal_number}")
binary = ""
while decimal > 0:
remainder = decimal % 2
binary = str(remainder) + binary
decimal //= 2
return binary
decimal_number = 42
binary_number = decimal_to_binary(decimal_number)
print(f"The decimal number {decimal_number} is equivalent to binary: {binary_number}")
list_of_tuples = [(1, 5), (3, 2), (2, 8), (5, 1), (4, 3)]
sorted_tuples = sort_tuples_by_second_element(list_of_tuples)
print("Sorted list of tuples by the second element:")
for tpl in sorted_tuples:
print(tpl)
Output:
Sorted list of tuples by the second element:
(5, 1)
(3, 2)
(4, 3)
(1, 5)
(2, 8)
24. Calculate the Area of Different Geometric Shapes (Circle, Triangle, Rectangle)
Circle Area Calculation:
import math
def circle_area(radius):
return math.pi * radius ** 2
Output:
The area of the circle with radius 5 is: 78.54
The area of the triangle with base 6 and height 4 is: 12.0
The area of the rectangle with length 7 and width 3 is: 21
# Example usage
input_str1 = "The quick brown fox jumps over the lazy dog"
input_str2 = "Hello world"
Output:
'The quick brown fox jumps over the lazy dog' is a pangram: True
'Hello world' is a pangram: False
# Example usage
password = generate_random_password()
print(f"Generated random password: {password}")
def is_fibonacci_number(n):
# A number n is Fibonacci if and only if one or both of (5*n*n + 4) or (5*n*n - 4) is a
perfect square
return is_perfect_square(5 * n * n + 4) or is_perfect_square(5 * n * n - 4)
# Example usage
number = 8
if is_fibonacci_number(number):
print(f"{number} is a Fibonacci number.")
else:
print(f"{number} is not a Fibonacci number.")
def is_empty(self):
return len(self.stack) == 0
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
raise IndexError("pop from empty stack")
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
raise IndexError("peek from empty stack")
def size(self):
return len(self.stack)
# Example usage
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
Output:
Current stack: [1, 2, 3]
Pop item: 3
Peek item: 2
Current stack after operations: [1, 2]
Stack size: 2
def is_empty(self):
return self.items == []
def dequeue(self):
if self.is_empty():
return None
return self.items.pop(0)
def peek(self):
if self.is_empty():
return None
return self.items[0]
def size(self):
return len(self.items)
# Example usage:
queue = Queue()
# Dequeue elements
print("Dequeued item:", queue.dequeue()) # Output: Dequeued item: 1
print("Dequeued item:", queue.dequeue()) # Output: Dequeued item: 2
print("Queue size after dequeue:", queue.size()) # Output: Queue size after dequeue: 1
Output:
Queue size: 3
Front element: 1
Dequeued item: 1
Dequeued item: 2
Queue size after dequeue: 1
return union_list
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
union = find_union(list1, list2)
print(f"The union of {list1} and {list2} is: {union}")
# Example usage
string1 = "abc"
string2 = "ahbgdc"
result = is_subsequence(string1, string2)
if result:
print(f"'{string1}' is a subsequence of '{string2}'.")
else:
print(f"'{string1}' is not a subsequence of '{string2}'.")
# Maximum product could be max1*max2 or min1*min2 (if all numbers are negative)
return max(max1 * max2, min1 * min2)
# Example usage
numbers = [3, 4, 1, 2, 5, 6, -2, -3]
max_product = max_product_of_two(numbers)
print(f"The maximum product of two integers in the list {numbers} is: {max_product}")
Output: The maximum product of two integers in the list [3, 4, 1, 2, 5, 6, -2, -3] is:
30
# Example usage
graph = Graph()
# Adding edges
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 2)
graph.add_edge(2, 0)
graph.add_edge(2, 3)
graph.add_edge(3, 3)
Output:
DFS traversal starting from vertex 2:
2013
while queue:
vertex = queue.popleft()
print(vertex, end=' ')
# Example usage
graph = Graph()
# Adding edges
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 2)
graph.add_edge(2, 0)
graph.add_edge(2, 3)
graph.add_edge(3, 3)
print("BFS traversal starting from vertex 2:")
graph.bfs(2)
Output:
BFS traversal starting from vertex 2:
2031
merged = []
for interval in intervals:
# If the list of merged intervals is empty or if the current
# interval does not overlap with the previous, append it.
if not merged or merged[-1][1] < interval[0]:
merged.append(interval)
else:
# There is overlap, so merge the current and previous intervals.
merged[-1][1] = max(merged[-1][1], interval[1])
return merged
# Example usage
intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
merged_intervals = merge_intervals(intervals)
print("Merged intervals:", merged_intervals)
# For the remaining elements, push into the heap if larger than the smallest element
for num in nums[k:]:
if num > min_heap[0]:
heapq.heappushpop(min_heap, num)
if n % 2 == 1:
# If the length of nums is odd, return the middle element
median = nums[n // 2]
else:
# If the length of nums is even, return the average of the middle two elements
median = (nums[n // 2 - 1] + nums[n // 2]) / 2
return median
# Example usage
nums1 = [1, 3, 2, 5, 4]
nums2 = [1, 2, 3, 4, 5, 6]
median1 = calculate_median(nums1)
median2 = calculate_median(nums2)
Output:
The median of [1, 3, 2, 5, 4] is: 3
The median of [1, 2, 3, 4, 5, 6] is: 3.5
# Calculate the sum of the first row (this will be our magic constant)
magic_constant = sum(matrix[0])
# Check rows
for row in matrix:
if sum(row) != magic_constant:
return False
# Check columns
for col in range(n):
column_sum = 0
for row in range(n):
column_sum += matrix[row][col]
if column_sum != magic_constant:
return False
return True
# Example usage
matrix1 = [
[8, 1, 6],
[3, 5, 7],
[4, 9, 2]
]
matrix2 = [
[2, 7, 6],
[9, 5, 1],
[4, 3, 8]
]
if is_magic_square(matrix1):
print("matrix1 is a Magic Square.")
else:
print("matrix1 is not a Magic Square.")
if is_magic_square(matrix2):
print("matrix2 is a Magic Square.")
else:
print("matrix2 is not a Magic Square.")
Output:
matrix1 is a Magic Square.
matrix2 is not a Magic Square.
# Example usage
base = 3
exponent = 4
result = power(base, exponent)
print(f"{base} raised to the power of {exponent} is: {result}")
# Example usage
string1 = "ABCDGH"
string2 = "AEDFHR"
lcs = longest_common_subsequence(string1, string2)
print(f"The Longest Common Subsequence of '{string1}' and '{string2}' is: {lcs}")
Output: The Longest Common Subsequence of 'ABCDGH' and 'AEDFHR' is: ADH
# Example usage
string = "Madam"
if is_palindrome(string):
print(f"'{string}' is a palindrome")
else:
print(f"'{string}' is not a palindrome")
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array:", arr)
Output: Sorted array: [11, 12, 22, 25, 34, 64, 90]
matrix = [
[3, 5, 7],
[2, 6, 8],
[1, 4, 9]
]
max_element = find_max_2d_list(matrix)
print(f"The maximum element in the 2D list is: {max_element}")
# Example usage
numbers = [1, 2, 3, 4, 5]
total = sum_of_elements(numbers)
print(f"The sum of elements in the list is: {total}")
number = 10
print(f"The sum of the first {number} natural numbers is:
{sum_of_natural_numbers(number)}")
a, b = 48, 18
print(f"The GCD of {a} and {b} is: {gcd(a, b)}")
def play_rps():
choices = ['rock', 'paper', 'scissors']
computer_choice = random.choice(choices)
user_choice = input("Enter rock, paper, or scissors: ").lower()
print(play_rps())
def check_balance(self):
return f"Current balance: {self.balance}"
# Example usage
atm = ATM(100)
print(atm.deposit(50))
print(atm.withdraw(30))
print(atm.check_balance())
print(atm.withdraw(150))
def set_alarm(alarm_time):
print(f"Alarm set for {alarm_time}")
while True:
current_time = time.strftime("%H:%M:%S")
if current_time == alarm_time:
print("Wake up!")
for _ in range(5):
winsound.Beep(1000, 1000)
break
time.sleep(1)
# Example usage
# Please set the alarm time as per your current time in HH:MM:SS format
alarm_time = "15:30:00"
set_alarm(alarm_time)
Output:
Alarm set for 15:30:00
[Beep sounds]
Output:
2000 is a leap year.
2004 is a leap year.
2100 is not a leap year.
2021 is not a leap year.
Output: The sentence 'Hello, how are you today?' has 5 words.
# Example usage
number = 3549
roman = decimal_to_roman(number)
print(f"Roman numeral for {number}: {roman}")
# Example usage
string1 = "Machine"
string2 = "Algorithm"
string3 = "Python"
def get_random_quote():
quotes = [
"I'm not arguing, I'm just explaining why I'm right.",
"I'm on a seafood diet. I see food and I eat it.",
"Why don’t scientists trust atoms? Because they make up everything!",
"I told my wife she was drawing her eyebrows too high. She looked surprised.",
"Parallel lines have so much in common. It’s a shame they’ll never meet.",
"I threw a boomerang a few years ago. I now live in constant fear.",
"My wife told me to stop impersonating a flamingo. I had to put my foot down."
]
return random.choice(quotes)
def funny_chatbot():
print("Hello! I'm your funny chatbot. Type 'exit' to end the conversation.")
while True:
user_input = input("You: ")
if user_input.lower() == 'exit':
print("Chatbot: Goodbye! Have a funny day!")
break
print(f"Chatbot: {get_random_quote()}")
Output:
Hello! I'm your funny chatbot. Type 'exit' to end the conversation.
You: Hi there!
Chatbot: I'm not arguing, I'm just explaining why I'm right.
You: Tell me a joke.
Chatbot: Why don’t scientists trust atoms? Because they make up everything!
You: That's funny!
Chatbot: My wife told me to stop impersonating a flamingo. I had to put my foot
down.
You: exit
Chatbot: Goodbye! Have a funny day!
celsius = 25
fahrenheit = celsius_to_fahrenheit(celsius)
print(f"{celsius}°C is equal to {fahrenheit}°F")
asyncio.run(todo_list())
Output:
Enter a task (or 'done' to finish): Buy groceries
Enter a task (or 'done' to finish): Walk the dog
Enter a task (or 'done' to finish): done
Your to-do list:
1. Buy groceries
2. Walk the dog
radius = 5
area = area_of_circle(radius)
print(f"The area of a circle with radius {radius} is: {area}")
LOOPING PROGRAMS
Output:
P
y
t
h
o
n
Output:
0
1
2
3
4
Output:
apple
banana
cherry
Output:
0
1
2
3
4
Output:
0
1
3
4
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:
0
2
4
6
8
Output:
100 / 10 = 10.0
100 / 20 = 5.0
Cannot divide by zero
100 / 30 = 3.3333333333333335
Output: 10 is positive
Output: -5 is negative
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
Output:
1
3
5
7
9
Output:
0
1
3
4
Output:
Error: Division by zero is not allowed
This will execute no matter what
Output:
6 not found in the list.
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
recursive_print(5)
Output:
5
4
3
2
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
Output:
x: 1, y: 2
x: 3, y: 4
x: 5, y: 6
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
Output:
AB
AC
BC
Output:
Processing: first
Processing: second
Processing: third
Output:
red
green
blue
red
green
blue
red
PATTERN PROGRAMS
Output:
*
**
***
****
*****
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))
Output:
*
***
*****
*******
*********
*******
*****
***
*
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
Output:
12345
1234
123
12
1
Output:
1
22
333
4444
55555
Output:
A
AB
ABC
ABCD
ABCDE
Output:
*****
* *
* *
* *
*****
Output:
*
**
* *
* *
*********
Output:
1
121
12321
1234321
123454321
1234321
12321
121
1
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:
*********
*******
*****
***
*
***
*****
*******
*********
Output:
* * *
* ** *
** **
Output:
*
**
* *
* *
* *
* *
* *
**
*
Output:
*
***
*****
PYTHON
*****
***
*
Output:
*
**
***
****
*****
****
***
**
*
Output:
*****
* *
* *
* *
*****
Output:
1
121
12321
1234321
123454321
Output:
A
BC
DEF
GHIJ
KLMNO
Output:
*****
*****
*****
*****
*****