Python Programs – Examples
Here’s a curated and efficient set of Python programs for all the listed topics. Due
to the large number of problems, I’ll provide them in batches, ensuring optimal
solutions for each. Here you go 🕺
Python program to print “Hello Python”
print("Hello Python")
Python program to do arithmetical operations
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(f"Addition: {a + b}")
print(f"Subtraction: {a - b}")
print(f"Multiplication: {a * b}")
print(f"Division: {a / b if b != 0 else 'Division by zero error'}")
Python program to find the area of a triangle
a = float(input("Enter the first side of the triangle: "))
b = float(input("Enter the second side of the triangle: "))
c = float(input("Enter the third side of the triangle: "))
s = (a + b + c) / 2
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
print(f"Area of the triangle is {area:.2f}")
Python program to solve a quadratic equation
import cmath
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))
d = (b**2) - (4*a*c)
sol1 = (-b - cmath.sqrt(d)) / (2 * a)
sol2 = (-b + cmath.sqrt(d)) / (2 * a)
print(f"The solutions are {sol1} and {sol2}")
Python program to swap two variables
x = input("Enter value of x: ")
y = input("Enter value of y: ")
x, y = y, x
print(f"Swapped values: x = {x}, y = {y}")
Python program to generate a random number
import random
print(f"Random number: {random.randint(1, 100)}")
Python program to convert kilometers to miles
km = float(input("Enter distance in kilometers: "))
miles = km * 0.621371
print(f"{km} kilometers is equal to {miles:.2f} miles")
Python program to convert Celsius to Fahrenheit
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius} Celsius is equal to {fahrenheit:.2f} Fahrenheit")
Python program to display calendar
import calendar
year = int(input("Enter year: "))
month = int(input("Enter month: "))
print(calendar.month(year, month))
Python Program to Check if a Number is Positive, Negative, or
Zero
num = float(input("Enter a number: "))
if num > 0:
print("Positive")
elif num == 0:
print("Zero")
else:
print("Negative")
Alright! Here are the next set of programs:
Python Program to Check if a Number is Odd or Even
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
Python Program to Check Leap Year
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
Python Program to Check Prime Number
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
print(f"{num} is not a prime number")
break
else:
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")
Python Program to Print all Prime Numbers in an Interval
start = int(input("Enter the starting value: "))
end = int(input("Enter the ending value: "))
for num in range(start, end + 1):
if num > 1:
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
break
else:
print(num, end=" ")
Python Program to Find the Factorial of a Number
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Factorial does not exist for negative numbers")
else:
for i in range(1, num + 1):
factorial *= i
print(f"Factorial of {num} is {factorial}")
Python Program to Display the Multiplication Table
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
Python Program to Print the Fibonacci Sequence
n = int(input("Enter the number of terms: "))
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
Python Program to Check Armstrong Number
num = int(input("Enter a number: "))
order = len(str(num))
sum_of_powers = sum(int(digit)**order for digit in str(num))
if num == sum_of_powers:
print(f"{num} is an Armstrong number")
else:
print(f"{num} is not an Armstrong number")
Python Program to Find Armstrong Numbers in an Interval
start = int(input("Enter the starting value: "))
end = int(input("Enter the ending value: "))
for num in range(start, end + 1):
order = len(str(num))
sum_of_powers = sum(int(digit)**order for digit in str(num))
if num == sum_of_powers:
print(num, end=" ")
Python Program to Find the Sum of Natural Numbers
n = int(input("Enter a number: "))
if n < 0:
print("Enter a positive number")
else:
total = n * (n + 1) // 2
print(f"The sum of the first {n} natural numbers is {total}")
Python Program to Print Reverse of a String
string = input("Enter a string: ")
print(f"Reversed string: {string[::-1]}")
Python Program to Print Sum of First Ten Natural Numbers
n = 10
total = n * (n + 1) // 2
print(f"The sum of the first {n} natural numbers is {total}")
Python Program to Find LCM
def find_lcm(a, b):
greater = max(a, b)
while True:
if greater % a == 0 and greater % b == 0:
return greater
greater += 1
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(f"LCM of {num1} and {num2} is {find_lcm(num1, num2)}")
Python Program to Find HCF
def find_hcf(a, b):
while b:
a, b = b, a % b
return a
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(f"HCF of {num1} and {num2} is {find_hcf(num1, num2)}")
Python Program to Convert Decimal to Binary, Octal and
Hexadecimal
num = int(input("Enter a decimal number: "))
print(f"Binary: {bin(num)[2:]}")
print(f"Octal: {oct(num)[2:]}")
print(f"Hexadecimal: {hex(num)[2:].upper()}")
Python Program To Find ASCII Value of a Character
char = input("Enter a character: ")
print(f"ASCII value of '{char}' is {ord(char)}")
Python Program to Make a Simple Calculator
def calculator(a, b, op):
if op == '+':
return a + b
elif op == '-':
return a - b
elif op == '*':
return a * b
elif op == '/':
return a / b if b != 0 else "Division by zero error"
else:
return "Invalid operator"
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
op = input("Enter an operator (+, -, *, /): ")
print(f"Result: {calculator(a, b, op)}")
Python Program to Display Fibonacci Sequence Using Recursion
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
n_terms = int(input("Enter the number of terms: "))
for i in range(n_terms):
print(fibonacci(i), end=" ")
Python Program to Find Factorial of Number Using Recursion
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
num = int(input("Enter a number: "))
print(f"Factorial of {num} is {factorial(num)}")
Python Program to Calculate the Power of a Number
base = float(input("Enter the base: "))
exp = int(input("Enter the exponent: "))
result = base ** exp
print(f"{base} raised to the power {exp} is {result}")
Let me know if you’d like me to keep going!
Here are the next set of programs:
Python program to check if the given number is a Disarium
Number
def is_disarium(num):
return num == sum(int(digit)**(i + 1) for i, digit in
enumerate(str(num)))
num = int(input("Enter a number: "))
if is_disarium(num):
print(f"{num} is a Disarium Number")
else:
print(f"{num} is not a Disarium Number")
Python program to print all Disarium numbers between 1 to 100
def is_disarium(num):
return num == sum(int(digit)**(i + 1) for i, digit in
enumerate(str(num)))
print("Disarium numbers between 1 and 100:")
for num in range(1, 101):
if is_disarium(num):
print(num, end=" ")
Python program to check if the given number is a Happy Number
def is_happy(num):
seen = set()
while num != 1 and num not in seen:
seen.add(num)
num = sum(int(digit)**2 for digit in str(num))
return num == 1
num = int(input("Enter a number: "))
if is_happy(num):
print(f"{num} is a Happy Number")
else:
print(f"{num} is not a Happy Number")
Python program to print all Happy Numbers between 1 and 100
def is_happy(num):
seen = set()
while num != 1 and num not in seen:
seen.add(num)
num = sum(int(digit)**2 for digit in str(num))
return num == 1
print("Happy numbers between 1 and 100:")
for num in range(1, 101):
if is_happy(num):
print(num, end=" ")
Python program to determine whether the given number is a
Harshad Number
def is_harshad(num):
return num % sum(int(digit) for digit in str(num)) == 0
num = int(input("Enter a number: "))
if is_harshad(num):
print(f"{num} is a Harshad Number")
else:
print(f"{num} is not a Harshad Number")
Python program to print all Pronic Numbers between 1 and 100
def is_pronic(num):
for i in range(1, int(num**0.5) + 1):
if i * (i + 1) == num:
return True
return False
print("Pronic numbers between 1 and 100:")
for num in range(1, 101):
if is_pronic(num):
print(num, end=" ")
Python program to print first ten natural numbers
print("First ten natural numbers:")
for num in range(1, 11):
print(num, end=" ")
Python Program to Check an Armstrong Number
num = int(input("Enter a number: "))
order = len(str(num))
sum_of_powers = sum(int(digit)**order for digit in str(num))
if num == sum_of_powers:
print(f"{num} is an Armstrong number")
else:
print(f"{num} is not an Armstrong number")
Python Program to Add Two Matrices
X = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Y = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
result = [[X[i][j] + Y[i][j] for j in range(len(X[0]))] for i in
range(len(X))]
print("Resultant Matrix after Addition:")
for row in result:
print(row)
Python Program to Multiply Two Matrices
X = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Y = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
result = [[sum(a * b for a, b in zip(X_row, Y_col)) for Y_col in
zip(*Y)] for X_row in X]
print("Resultant Matrix after Multiplication:")
for row in result:
print(row)
Let me know if you’d like me to continue!
Here are the next programs for the remaining topics:
Python Program to Transpose a Matrix
X = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = [[X[j][i] for j in range(len(X))] for i in range(len(X[0]))]
print("Transpose of the Matrix:")
for row in result:
print(row)
Python Program to Perform Matrix Rotation
def rotate_matrix_90(matrix):
return [list(reversed(col)) for col in zip(*matrix)]
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
rotated = rotate_matrix_90(matrix)
print("Rotated Matrix by 90 Degrees:")
for row in rotated:
print(row)
Python Program to Print Inverse of a Matrix
import numpy as np
matrix = [[4, 7], [2, 6]]
matrix_np = np.array(matrix)
try:
inverse = np.linalg.inv(matrix_np)
print("Inverse of the Matrix:")
print(inverse)
except np.linalg.LinAlgError:
print("Matrix is singular and cannot be inverted")
Python Program to Sort Words in Alphabetic Order
sentence = input("Enter a sentence: ")
words = sentence.split()
words.sort()
print("Sorted Words:")
print(" ".join(words))
Python Program to Remove Punctuation From a String
import string
text = input("Enter a string: ")
cleaned_text = text.translate(str.maketrans("", "",
string.punctuation))
print("String without punctuation:")
print(cleaned_text)
Python Program to Reverse a String
string = input("Enter a string: ")
print(f"Reversed string: {string[::-1]}")
Python Program to Convert List to String
lst = ['Python', 'is', 'fun']
result = " ".join(lst)
print(f"Converted string: {result}")
Python Program to Convert Int to String
num = 123
string_num = str(num)
print(f"Converted string: {string_num}")
Python Program to Concatenate Two Strings
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
result = str1 + str2
print(f"Concatenated String: {result}")
Python Program to Generate a Random String
import random
import string
length = int(input("Enter the length of the random string: "))
random_string = ''.join(random.choice(string.ascii_letters +
string.digits) for _ in range(length))
print(f"Random String: {random_string}")
Python Program to Convert Bytes to String
byte_data = b'Hello Python'
string_data = byte_data.decode("utf-8")
print(f"Converted string: {string_data}")
Python Program to Check if a String is Palindrome
string = input("Enter a string: ")
if string == string[::-1]:
print("The string is a palindrome")
else:
print("The string is not a palindrome")
Python Program to Print Length of a String
string = input("Enter a string: ")
print(f"Length of the string: {len(string)}")
Python Program to Reverse the Characters of a String
string = input("Enter a string: ")
print(f"Reversed string: {''.join(reversed(string))}")
Python Program to Convert Lowercase to Uppercase
string = input("Enter a string: ")
print(f"String in uppercase: {string.upper()}")
Python Program to Convert Uppercase to Lowercase
string = input("Enter a string: ")
print(f"String in lowercase: {string.lower()}")
Python Program to Find the Occurrence of a Substring Within a
String
string = input("Enter the main string: ")
substring = input("Enter the substring: ")
count = string.count(substring)
print(f"The substring '{substring}' occurred {count} time(s) in the
string.")
Python Program to Append Element in the List
lst = [1, 2, 3, 4]
element = int(input("Enter an element to append: "))
lst.append(element)
print(f"Updated List: {lst}")
Python Program to Compare Two Lists
lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
if lst1 == lst2:
print("The lists are equal")
else:
print("The lists are not equal")
Python Program to Convert List to Dictionary
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(f"Converted Dictionary: {dictionary}")
Python Program to Remove an Element From a List
lst = [1, 2, 3, 4, 5]
element = int(input("Enter an element to remove: "))
if element in lst:
lst.remove(element)
print(f"Updated List: {lst}")
else:
print("Element not found in the list")
Python Program to Add Two Lists
lst1 = [1, 2, 3]
lst2 = [4, 5, 6]
result = [x + y for x, y in zip(lst1, lst2)]
print(f"Resultant List: {result}")
Python Program to Convert List to Set
lst = [1, 2, 2, 3, 4, 4]
unique_set = set(lst)
print(f"Converted Set: {unique_set}")
Python Program to Remove Duplicates From a List
lst = [1, 2, 2, 3, 4, 4]
unique_list = list(set(lst))
print(f"List after removing duplicates: {unique_list}")
Python Program to Print Length of a List
lst = [1, 2, 3, 4, 5]
print(f"Length of the list: {len(lst)}")
Python Program to Implement Linear Search
def linear_search(lst, target):
for i, value in enumerate(lst):
if value == target:
return i
return -1
lst = [10, 20, 30, 40, 50]
target = int(input("Enter the target value: "))
index = linear_search(lst, target)
if index != -1:
print(f"Element found at index {index}")
else:
print("Element not found")
Python Program to Implement Binary Search
def binary_search(lst, target):
left, right = 0, len(lst) - 1
while left <= right:
mid = (left + right) // 2
if lst[mid] == target:
return mid
elif lst[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
lst = [10, 20, 30, 40, 50]
target = int(input("Enter the target value: "))
index = binary_search(lst, target)
if index != -1:
print(f"Element found at index {index}")
else:
print("Element not found")
Python Program to Implement Bubble Sort
def bubble_sort(lst):
n = len(lst)
for i in range(n):
for j in range(0, n-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
lst = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(lst)
print(f"Sorted List: {lst}")
Python Program to Implement Insertion Sort
def insertion_sort(lst):
for i in range(1, len(lst)):
key = lst[i]
j = i - 1
while j >= 0 and key < lst[j]:
lst[j + 1] = lst[j]
j -= 1
lst[j + 1] = key
lst = [64, 34, 25, 12, 22, 11, 90]
insertion_sort(lst)
print(f"Sorted List: {lst}")
Python Program to Implement Selection Sort
def selection_sort(lst):
for i in range(len(lst)):
min_idx = i
for j in range(i + 1, len(lst)):
if lst[j] < lst[min_idx]:
min_idx = j
lst[i], lst[min_idx] = lst[min_idx], lst[i]
lst = [64, 34, 25, 12, 22, 11, 90]
selection_sort(lst)
print(f"Sorted List: {lst}")
Python Program to Implement Merge Sort
def merge_sort(lst):
if len(lst) > 1:
mid = len(lst) // 2
L = lst[:mid]
R = lst[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
lst[k] = L[i]
i += 1
else:
lst[k] = R[j]
j += 1
k += 1
while i < len(L):
lst[k] = L[i]
i += 1
k += 1
while j < len(R):
lst[k] = R[j]
j += 1
k += 1
lst = [64, 34, 25, 12, 22, 11, 90]
merge_sort(lst)
print(f"Sorted List: {lst}")
Python Program to Implement Quick Sort
def quick_sort(lst):
if len(lst) <= 1:
return lst
pivot = lst[len(lst) // 2]
left = [x for x in lst if x < pivot]
middle = [x for x in lst if x == pivot]
right = [x for x in lst if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
lst = [64, 34, 25, 12, 22, 11, 90]
sorted_lst = quick_sort(lst)
print(f"Sorted List: {sorted_lst}")
Python Program to Implement Dijkstra’s Algorithm to Find
Minimum Spanning Tree
import heapq
def dijkstra(graph, start):
queue = [(0, start)]
distances = {vertex: float('inf') for vertex in graph}
distances[start] = 0
while queue:
(cost, vertex) = heapq.heappop(queue)
for neighbor, weight in graph[vertex]:
new_cost = cost + weight
if new_cost < distances[neighbor]:
distances[neighbor] = new_cost
heapq.heappush(queue, (new_cost, neighbor))
return distances
graph = {
'A': [('B', 1), ('C', 4)],
'B': [('A', 1), ('C', 2), ('D', 5)],
'C': [('A', 4), ('B', 2), ('D', 1)],
'D': [('B', 5), ('C', 1)]
}
distances = dijkstra(graph, 'A')
print(f"Shortest distances from A: {distances}")
Python Program to Implement Prim’s Algorithm
import heapq
def prim(graph, start):
mst = []
visited = {start}
edges = [(weight, start, to) for to, weight in graph[start]]
heapq.heapify(edges)
while edges:
weight, frm, to = heapq.heappop(edges)
if to not in visited:
visited.add(to)
mst.append((frm, to, weight))
for to_next, weight in graph[to]:
if to_next not in visited:
heapq.heappush(edges, (weight, to, to_next))
return mst
graph = {
'A': [('B', 1), ('C', 4)],
'B': [('A', 1), ('C', 2), ('D', 5)],
'C': [('A', 4), ('B', 2), ('D', 1)],
'D': [('B', 5), ('C', 1)]
}
mst = prim(graph, 'A')
print(f"Minimum Spanning Tree: {mst}")
Python Program to Implement Kruskal’s Algorithm
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, u):
if self.parent[u] != u:
self.parent[u] = self.find(self.parent[u])
return self.parent[u]
def union(self, u, v):
root_u = self.find(u)
root_v = self.find(v)
if root_u != root_v:
if self.rank[root_u] > self.rank[root_v]:
self.parent[root_v] = root_u
elif self.rank[root_u] < self.rank[root_v]:
self.parent[root_u] = root_v
else:
self.parent[root_v] = root_u
self.rank[root_u] += 1
def kruskal(graph, n):
edges = [(w, u, v) for u in graph for v, w in graph[u]]
edges.sort()
disjoint_set = DisjointSet(n)
mst = []
for w, u, v in edges:
if disjoint_set.find(u) != disjoint_set.find(v):
disjoint_set.union(u, v)
mst.append((u, v, w))
return mst
graph = {
0: [(1, 1), (2, 4)],
1: [(0, 1), (2, 2), (3, 5)],
2: [(0, 4), (1, 2), (3, 1)],
3: [(1, 5), (2, 1)]
}
mst = kruskal(graph, 4)
print(f"Minimum Spanning Tree: {mst}")
Python Program to Solve the Fractional Knapsack Problem Using
Greedy Approach
def fractional_knapsack(weights, values, capacity):
n = len(weights)
ratio = [(values[i] / weights[i], weights[i], values[i]) for i in
range(n)]
ratio.sort(reverse=True, key=lambda x: x[0])
total_value = 0
for r, w, v in ratio:
if capacity >= w:
capacity -= w
total_value += v
else:
total_value += (capacity / w) * v
break
return total_value
weights = [10, 20, 30]
values = [60, 100, 120]
capacity = 50
result = fractional_knapsack(weights, values, capacity)
print(f"Maximum value in the knapsack: {result}")
Python Program to Solve the Coin Change Problem Using Greedy
Approach
def coin_change(coins, amount):
coins.sort(reverse=True)
count = 0
for coin in coins:
if amount == 0:
break
count += amount // coin
amount %= coin
return count
coins = [1, 5, 10, 25]
amount = int(input("Enter the amount: "))
result = coin_change(coins, amount)
print(f"Minimum coins needed: {result}")
Python Program to Solve the N-Queen Problem
def is_safe(board, row, col, n):
for i in range(row):
if board[i] == col or board[i] - i == col - row or board[i] + i
== col + row:
return False
return True
def solve_n_queens(board, row, n):
if row == n:
print(board)
return True
res = False
for col in range(n):
if is_safe(board, row, col, n):
board[row] = col
res = solve_n_queens(board, row + 1, n) or res
return res
def n_queens(n):
board = [-1] * n
if not solve_n_queens(board, 0, n):
print("Solution does not exist")
else:
print("Solution found")
n = int(input("Enter the value of N: "))
n_queens(n)
Enjoy bro.! 😎