All 38 Python Programming Exercises
1) Bitwise Operator
a = 10 # 1010
b = 4 # 0100
print("a & b =", a & b)
print("a | b =", a | b)
print("a ^ b =", a ^ b)
print("~a =", ~a)
print("a << 1 =", a << 1)
print("a >> 1 =", a >> 1)
2) Relational Operator
a = 5
b = 10
print("a > b =", a > b)
print("a < b =", a < b)
print("a == b =", a == b)
print("a != b =", a != b)
print("a >= b =", a >= b)
print("a <= b =", a <= b)
3) Logical Operator
a = True
b = False
print("a and b =", a and b)
print("a or b =", a or b)
print("not a =", not a)
4) Arithmetic Operator
a = 15
b = 4
print("a + b =", a + b)
print("a - b =", a - b)
print("a * b =", a * b)
print("a / b =", a / b)
print("a % b =", a % b)
print("a ** b =", a ** b)
print("a // b =", a // b)
5) Greatest of Three Numbers
a = 10
b = 20
c = 15
if a > b and a > c:
print("Greatest is:", a)
elif b > c:
print("Greatest is:", b)
else:
print("Greatest is:", c)
6) Distance Between Two Points
import math
x1, y1 = 0, 0
x2, y2 = 3, 4
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
print("Distance:", distance)
7) String Operations
s = "Hello World"
print("Upper:", s.upper())
print("Lower:", s.lower())
print("Title:", s.title())
print("Length:", len(s))
print("Split:", s.split())
8) Implicit Conversion
a = 5
b = 2.0
c = a + b
print(c)
print("Type of c:", type(c))
9) Explicit Conversion
a = 5.6
b = int(a)
print(b)
print("Type of b:", type(b))
10) Nested if Statement
num = 15
if num > 0:
if num % 2 == 0:
print("Positive Even")
else:
print("Positive Odd")
else:
print("Non-positive")
11) Check Character Type
ch = input("Enter a character: ")
if ch.isalpha():
print("Alphabet")
if ch.isupper():
print("Uppercase")
else:
print("Lowercase")
elif ch.isdigit():
print("Digit")
elif ch.isspace():
print("Space")
elif ch.isalnum():
print("Alphanumeric")
else:
print("Special Character")
12) Check Eligibility to Marry
age = int(input("Enter age: "))
gender = input("Enter gender (M/F): ").upper()
if gender == "M":
if age >= 21:
print("Eligible to marry")
else:
print("Not eligible to marry")
elif gender == "F":
if age >= 18:
print("Eligible to marry")
else:
print("Not eligible to marry")
else:
print("Invalid gender input")
13) Print Each Character of a String
s = input("Enter a string: ")
for char in s:
print(char)
14) Sum of Even and Odd Numbers
n = int(input("Enter range limit: "))
even_sum = 0
odd_sum = 0
for i in range(1, n + 1):
if i % 2 == 0:
even_sum += i
else:
odd_sum += i
print("Sum of even numbers:", even_sum)
print("Sum of odd numbers:", odd_sum)
15) Check Armstrong Number
num = int(input("Enter a number: "))
sum = 0
temp = num
order = len(str(num))
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num, "is an Armstrong number")
else:
print(num, "is not an Armstrong number")
16) Vowel or Consonant
ch = input("Enter a character: ").lower()
if ch in 'aeiou':
print("Vowel")
elif ch.isalpha():
print("Consonant")
else:
print("Not an alphabet")
17) Prime or Composite
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, num):
if num % i == 0:
print("Composite")
break
else:
print("Prime")
else:
print("Neither Prime nor Composite")
18) Multiplication Table
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
19) Factorial Using Loop
num = int(input("Enter a number: "))
fact = 1
for i in range(1, num + 1):
fact *= i
print("Factorial:", fact)
20) Fibonacci Series
n = int(input("Enter number of terms: "))
a, b = 0, 1
print("Fibonacci Series:")
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
21) Palindrome Number
num = int(input("Enter a number: "))
if str(num) == str(num)[::-1]:
print("Palindrome")
else:
print("Not a palindrome")
22) GCD Using Recursion
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print("GCD is:", gcd(x, y))
23) Prime Numbers in Interval
start = int(input("Enter start: "))
end = int(input("Enter end: "))
for num in range(start, end + 1):
if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
print(num, end=' ')
24) Sum and Product of N Natural Numbers
n = int(input("Enter a number: "))
sum = 0
product = 1
i = 1
while i <= n:
sum += i
product *= i
i += 1
print("Sum:", sum)
print("Product:", product)
25) Palindrome String Using Function
def is_palindrome(s):
return s == s[::-1]
s = input("Enter a string: ")
if is_palindrome(s):
print("Palindrome")
else:
print("Not a palindrome")
26) Check List is Sorted
def is_sorted(lst):
return lst == sorted(lst)
lst = list(map(int, input("Enter list elements: ").split()))
if is_sorted(lst):
print("List is sorted")
else:
print("List is not sorted")
27) Nested Function
def outer():
print("Outer function")
def inner():
print("Inner function")
inner()
outer()
28) Rename a File
import os
old_name = input("Enter current file name: ")
new_name = input("Enter new file name: ")
try:
os.rename(old_name, new_name)
print("File renamed successfully")
except FileNotFoundError:
print("File not found")
29) Remove Duplicates from List
def remove_duplicates(lst):
return list(set(lst))
lst = list(map(int, input("Enter list elements: ").split()))
print("List after removing duplicates:", remove_duplicates(lst))
30) Arithmetic Operations Using Module
# arith.py
def add(a, b): return a + b
def sub(a, b): return a - b
def mul(a, b): return a * b
def div(a, b): return a / b
# main.py
import arith
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Add:", arith.add(a, b))
print("Subtract:", arith.sub(a, b))
print("Multiply:", arith.mul(a, b))
print("Divide:", arith.div(a, b))
31) Set Cursor in File
with open("sample.txt", "r") as file:
file.seek(5)
print("Cursor at 5, character:", file.read(1))
32) Command Line Arguments
# Save as cli_example.py
import sys
print("Number of arguments:", len(sys.argv))
print("Arguments list:", sys.argv)
33) Return Statement Demo
def square(x):
return x * x
num = int(input("Enter a number: "))
print("Square is:", square(num))
34) Variable Length Argument
def add_all(*args):
return sum(args)
print("Sum:", add_all(2, 3, 5))
35) Even/Odd Using Functions
def even_func(n): print(n, "is even")
def odd_func(n): print(n, "is odd")
num = int(input("Enter a number: "))
if num % 2 == 0:
even_func(num)
else:
odd_func(num)
36) Check Duplicates in List
def has_duplicates(lst):
return len(lst) != len(set(lst))
lst = list(map(int, input("Enter list: ").split()))
if has_duplicates(lst):
print("Duplicates found")
else:
print("No duplicates")
37) Convert Number to Binary
def to_binary(n):
return bin(n)[2:]
num = int(input("Enter number: "))
print("Binary:", to_binary(num))
38) Copy File
src = input("Enter source file name: ")
dst = input("Enter destination file name: ")
with open(src, 'r') as f1, open(dst, 'w') as f2:
f2.write(f1.read())
print("File copied successfully.")
39) Write a program to demonstrate Anonymous (OR) Lambda function?
# Program to demonstrate lambda function
square = lambda x: x ** 2
print("Square of 5 is:", square(5))
40) Write a program to find cursor position in a file?
# Program to find cursor position in a file
with open("example.txt", "r") as file:
file.read(10)
position = file.tell()
print("Current cursor position:", position)
41) Write a program to find GCD of two numbers by using functions?
# Program to find GCD using functions
def gcd(a, b):
while b:
a, b = b, a % b
return a
print("GCD of 48 and 18 is:", gcd(48, 18))
42) Write a program to print below pattern using nested loops?
# Pattern
# *
# **
# * *
# ****
# *****
# * * * *
for i in range(1, 6):
for j in range(1, i + 1):
if i == 3 or i == 6:
print("*", end=" ")
else:
print("*", end="")
print()
43) Write a program to print below pattern using nested loops?
# Pattern
# 5
# 4 4
# 3 3 3
# 2 2 2 2
# 1 1 1 1 1
for i in range(5, 0, -1):
for j in range(6 - i):
print(i, end=" ")
print()
44) Write a program to print below pattern using nested loops?
# Pattern
# 1
# 12
# 123
# 1234
# 12345
for i in range(1, 6):
for j in range(1, i + 1):
print(j, end="")
print()
45) Write a program to print below pattern using nested loops?
# Pattern
# A
# B B
# C C C
# D D D D
# E E E E E
for i in range(65, 70):
for j in range(i - 64):
print(chr(i), end=" ")
print()