DiSHA Computer Institute
Python Programs
with Line-by-Line Comments
77 Programs • 344 Comments • 1085
Lines Basic | Math | Control Structures |
Arrays Strings | Functions | File Handling |
Bitwise
[Link]. Computer Science | Savitribai Phule Pune University | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 2
"""
DiSHA Computer Institute – C Programs Converted to Python
Covers: Basic | Math | Control Structures | Arrays |
Strings | Functions | File Handling
NOTE: Every line below has an explanation in comment format
so you can understand exactly what each line does.
"""
# 'math' module gives us mathematical functions like sqrt(), pow()
import math
# 'os' module gives file/directory utilities (available if needed)
import os
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 3
SECTION 1 – BASIC PROGRAMS
# ■■■ Program 1 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#1 1. Addition of two numbers
def prog1_addition():
"""1. Addition of two numbers"""
# input() reads text from user; int() converts that text to integer
a = int(input("Enter a: "))
b = int(input("Enter b: "))
# '+' operator adds two numbers; print() displays the result
print("Addition =", a + b)
# ■■■ Program 2 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#2 2. Subtraction of two numbers
def prog2_subtraction():
"""2. Subtraction of two numbers"""
a = int(input("Enter a: ")) # Read first integer from user
b = int(input("Enter b: ")) # Read second integer from user
# '-' operator subtracts b from a
print("Subtraction =", a - b)
# ■■■ Program 3 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#3 3. Swap two numbers using third variable
def prog3_swap():
"""3. Swap two numbers using third variable"""
a = int(input("Enter a: ")) # Read first number
b = int(input("Enter b: ")) # Read second number
# Python allows simultaneous assignment: a gets old b, b gets old a
a, b = b, a
# \n inside a string prints a new line; f-string inserts variable values
print(f"After swapping\na={a}\nb={b}")
# ■■■ Program 4 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#4 4. Division of two numbers
def prog4_division():
"""4. Division of two numbers"""
a = int(input("Enter a: ")) # Numerator
b = int(input("Enter b: ")) # Denominator
# Check denominator is not zero to avoid ZeroDivisionError
if b != 0:
# '//' is integer (floor) division – gives whole number result
print("Division =", a // b)
else:
print("Cannot divide by zero")
# ■■■ Program 5 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 4
#5 5. Roots of quadratic equation
def prog5_quadratic():
"""5. Roots of quadratic equation"""
# Quadratic equation: ax² + bx + c = 0
a = float(input("Enter a: ")) # Coefficient of x²
b = float(input("Enter b: ")) # Coefficient of x
c = float(input("Enter c: ")) # Constant term
# Discriminant: b²-4ac decides nature of roots
disc = b**2 - 4*a*c
# If discriminant >= 0, roots are real numbers
if disc >= 0:
# Formula: root = (-b ± disc) / 2a
r1 = (-b + [Link](disc)) / (2*a) # Root 1 (plus)
r2 = (-b - [Link](disc)) / (2*a) # Root 2 (minus)
# :.4f formats float to 4 decimal places
print(f"Root1 = {r1:.4f}\nRoot2 = {r2:.4f}")
else:
# Negative discriminant means imaginary roots
print("Roots are complex (discriminant < 0)")
# ■■■ Program 6 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#6 6. Print ASCII value of a character
def prog6_ascii():
"""6. Print ASCII value of a character"""
ch = input("Enter character: ") # Read character as string
# ord() returns integer ASCII value of a character
# ch[0] picks only the first character in case user types more
print("ASCII value =", ord(ch[0]))
# ■■■ Program 7 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#7 7. Square of entered number
def prog7_square():
"""7. Square of entered number"""
n = int(input("Enter any number: ")) # Read integer
# '**' is the power operator; n**2 means n × n
print("Square =", n * n)
# ■■■ Program 8 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#8 8. Square root of entered number
def prog8_square_root():
"""8. Square root of entered number"""
n = float(input("Enter any number: ")) # Allow decimal input
# [Link]() computes the square root
print("Square root =", [Link](n))
# ■■■ Program 9 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#9 9. Power of entered number
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 5
def prog9_power():
"""9. Power of entered number"""
n = int(input("Enter any number: ")) # Base number
p = int(input("Enter power: ")) # Exponent
# n**p computes n raised to the power p (same as pow(n,p))
print("Power =", n ** p)
# ■■■ Program 10 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#10 10. Employee payment slip
def prog10_salary_slip():
"""10. Employee payment slip"""
sal = int(input("Enter one day salary: ")) # Daily salary
md = int(input("Enter monthly days: ")) # Total working days in month
msal = sal * md # Monthly salary = daily × days
print("Monthly salary =", msal)
absd = int(input("Enter absent days: ")) # Number of absent days
tabsd = sal * absd # Total salary lost for absences
print("Absent days salary =", tabsd)
fsal = msal - tabsd # Final salary = monthly - deduction
print("Final salary =", fsal)
# ■■■ Program 11 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#11 11. Area of circle, rectangle, triangle, and square
def prog11_areas():
"""11. Area of circle, rectangle, triangle, and square"""
r = float(input("Enter radius: "))
# Area of circle = × r² (using 3.14 as approximate )
print("Area of circle =", 3.14 * r * r)
l = float(input("Enter length: "))
b = float(input("Enter breadth: "))
# Area of rectangle = length × breadth
print("Area of rectangle =", l * b)
w = float(input("Enter width of triangle: "))
h = float(input("Enter height of triangle: "))
# Area of triangle = ½ × base × height
print("Area of triangle =", 0.5 * w * h)
s = float(input("Enter side of square: "))
# Area of square = side × side
print("Area of square =", s * s)
# ■■■ Program 12 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#12 12. Fahrenheit to Celsius
def prog12_f_to_c():
"""12. Fahrenheit to Celsius"""
f = float(input("Enter temperature in Fahrenheit: "))
# Conversion formula: C = 5 × (F - 32) / 9
c = 5 * (f - 32) / 9
# :.2f formats to 2 decimal places
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 6
print(f"Temperature in Celsius = {c:.2f}")
# ■■■ Program 13 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#13 13. Celsius to Fahrenheit
def prog13_c_to_f():
"""13. Celsius to Fahrenheit"""
c = float(input("Enter temperature in Celsius: "))
# Conversion formula: F = 32 + (9 × C / 5)
f = 32 + 9 * c / 5
print(f"Temperature in Fahrenheit = {f:.2f}")
# ■■■ Program 14 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#14 14. Swap two numbers without third variable
def prog14_swap_no_third():
"""14. Swap two numbers without third variable"""
a = int(input("Enter a: "))
b = int(input("Enter b: "))
# Step 1: a holds sum of both numbers
a = a + b
# Step 2: subtract new a minus b gives original a stored in b
b = a - b
# Step 3: subtract new a minus new b gives original b stored in a
a = a - b
print(f"After swapping\na={a}\nb={b}")
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 7
SECTION 2 – CONTROL STRUCTURES
# ■■■ Program 15 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#15 15. Check positive or negative
def prog15_positive_negative():
"""15. Check positive or negative"""
n = int(input("Enter any number: "))
# if checks the condition; > means greater than
if n > 0:
print("Number is Positive")
else:
# else runs when the condition above is False
print("Number is Negative")
# ■■■ Program 16 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#16 16. Check even or odd
def prog16_even_odd():
"""16. Check even or odd"""
n = int(input("Enter any number: "))
# '%' is modulus (remainder); n%2==0 means no remainder Even
# Ternary (one-line if-else): value_if_true if condition else value_if_false
print("Number is", "Even" if n % 2 == 0 else "Odd")
# ■■■ Program 17 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#17 17. Maximum of two numbers
def prog17_max_two():
"""17. Maximum of two numbers"""
a = int(input("Enter a: "))
b = int(input("Enter b: "))
# Built-in max() returns the largest of given values
print(max(a, b), "is maximum")
# ■■■ Program 18 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#18 18. Minimum of two numbers
def prog18_min_two():
"""18. Minimum of two numbers"""
a = int(input("Enter a: "))
b = int(input("Enter b: "))
# Built-in min() returns the smallest of given values
print(min(a, b), "is minimum")
# ■■■ Program 19 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#19 19. Maximum of three numbers
def prog19_max_three():
"""19. Maximum of three numbers"""
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 8
a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))
# max() can take any number of arguments
print(max(a, b, c), "is maximum")
# ■■■ Program 20 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#20 20. Add bonus based on salary
def prog20_salary_bonus():
"""20. Add bonus based on salary"""
sal = int(input("Enter salary: "))
# If salary > 5000 add 200, else add 500 (using augmented assignment +=)
sal += 200 if sal > 5000 else 500
print("Increased salary =", sal)
# ■■■ Program 21 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#21 21. Increase percentage
def prog21_percentage():
"""21. Increase percentage"""
per = float(input("Enter percentage: "))
# If percentage > 70, increase by 20%, else increase by 50%
# per * 0.20 = 20% of per
per += per * 0.20 if per > 70 else per * 0.50
print(f"Increased Percentage = {per:.2f}")
# ■■■ Program 22 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#22 22. Increase salary based on gender
def prog22_gender_salary():
"""22. Increase salary based on gender"""
ch = input("Enter gender (m/f): ")
sal = int(input("Enter salary: "))
# .lower() converts input to lowercase so 'M' and 'm' both work
sal += 400 if [Link]() == 'm' else 900
print("Increased Salary =", sal)
# ■■■ Program 23 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#23 23. If positive, check even or odd
def prog23_positive_even_odd():
"""23. If positive, check even or odd"""
n = int(input("Enter any number: "))
# Nested if: outer checks sign, inner checks even/odd
if n > 0:
print("Number is Positive")
# Inner if checks divisibility by 2
print("Number is", "Even" if n % 2 == 0 else "Odd")
else:
print("Number is Negative")
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 9
# ■■■ Program 24 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#24 24. Print 1 to 10 using for loop
def prog24_for_loop():
"""24. Print 1 to 10 using for loop"""
# range(1, 11) generates numbers 1,2,3,...,10 (11 is excluded)
for i in range(1, 11):
# end=" " prints a space after each number instead of new line
print(i, end=" ")
print() # Moves cursor to next line after all numbers are printed
# ■■■ Program 25 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#25 25. Print 1 to 10 using while loop
def prog25_while_loop():
"""25. Print 1 to 10 using while loop"""
i = 1 # Initialize counter to 1
while i <= 10: # Loop runs as long as i is 10
print(i, end=" ")
i += 1 # Increment counter; without this, infinite loop occurs
print() # New line after loop
# ■■■ Program 26 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#26 26. Sum of 1 to N
def prog26_sum_1_to_n():
"""26. Sum of 1 to N"""
n = int(input("Enter N: "))
# sum() adds all values; range(1, n+1) generates 1 to n inclusive
print("Sum =", sum(range(1, n + 1)))
# ■■■ Program 27 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#27 27. Multiplication table
def prog27_multiplication_table():
"""27. Multiplication table"""
n = int(input("Enter number: "))
# Loop from 1 to 10 to print each row of table
for i in range(1, 11):
# f-string formats the output: n x i = result
print(f"{n} x {i} = {n*i}")
# ■■■ Program 28 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#28 28. Factorial of a number
def prog28_factorial():
"""28. Factorial of a number"""
n = int(input("Enter number: "))
fact = 1 # Start with 1 (identity for multiplication)
# Multiply fact by each number from 1 to n
for i in range(1, n + 1):
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 10
fact *= i # Same as: fact = fact * i
print("Factorial =", fact)
# ■■■ Program 29 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#29 29. Fibonacci series up to N terms
def prog29_fibonacci():
"""29. Fibonacci series up to N terms"""
n = int(input("Enter number of terms: "))
a, b = 0, 1 # First two Fibonacci numbers
for _ in range(n): # '_' used when loop variable is not needed
print(a, end=" ") # Print current Fibonacci number
a, b = b, a + b # Move forward: next = current + previous
print()
# ■■■ Program 30 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#30 30. Check whether number is prime
def prog30_prime():
"""30. Check whether number is prime"""
n = int(input("Enter number: "))
# Numbers less than 2 (0 and 1) are not prime by definition
if n < 2:
print("Not Prime")
return # 'return' exits the function immediately
# Only check divisors up to n (efficient – no need to go further)
for i in range(2, int([Link](n)) + 1):
if n % i == 0: # If any divisor found, not prime
print("Not Prime")
return
# If loop completes without finding a divisor, it's prime
print("Prime")
# ■■■ Program 31 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#31 31. Check Armstrong number
def prog31_armstrong():
"""31. Check Armstrong number"""
# Armstrong: sum of each digit raised to power (number of digits) == number
# Example: 153 = 1³ + 5³ + 3³ = 153 ✓
n = int(input("Enter number: "))
tmp = n # Keep a copy to extract digits
total = 0 # Accumulator for sum of powered digits
digits = len(str(n)) # Count total digits (e.g. 153 3 digits)
while tmp: # Loop until tmp becomes 0
total += (tmp % 10) ** digits # Extract last digit, raise to power, add
tmp //= 10 # Remove last digit from tmp
# If sum equals original number, it's Armstrong
print("Armstrong" if total == n else "Not Armstrong")
# ■■■ Program 32 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 11
#32 32. Reverse a number
def prog32_reverse():
"""32. Reverse a number"""
n = int(input("Enter number: "))
rev = 0 # Will store reversed number
tmp = n # Work with a copy so original n is preserved
while tmp:
# Extract last digit with %10, append it to rev
rev = rev * 10 + tmp % 10
tmp //= 10 # Remove last digit
print("Reversed number =", rev)
# ■■■ Program 33 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#33 33. Sum of digits
def prog33_sum_digits():
"""33. Sum of digits"""
n = int(input("Enter number: "))
# abs() makes negative numbers positive before converting to string
# str() converts number to string so we can loop over each character
# int(d) converts each character digit back to integer for addition
print("Sum of digits =", sum(int(d) for d in str(abs(n))))
# ■■■ Program 34 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#34 34. Check palindrome number
def prog34_palindrome():
"""34. Check palindrome number"""
n = int(input("Enter number: "))
# [::-1] reverses the string; int() converts back to number
rev = int(str(n)[::-1])
# If original equals reversed, it's a palindrome (e.g. 121, 1331)
print("Palindrome" if n == rev else "Not Palindrome")
# ■■■ Program 35 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#35 35. Simple calculator using if-elif (like switch)
def prog35_switch_calculator():
"""35. Simple calculator using if-elif (like switch)"""
a = float(input("Enter first number: ")) # First operand
op = input("Enter operator (+, -, *, /): ") # Operator symbol
b = float(input("Enter second number: ")) # Second operand
# elif = "else if"; only one block runs based on operator
if op == '+':
print("Result =", a + b)
elif op == '-':
print("Result =", a - b)
elif op == '*':
print("Result =", a * b)
elif op == '/':
# Inline check to prevent division by zero
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 12
print("Result =", a / b if b != 0 else "Error: Divide by zero")
else:
print("Invalid operator")
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 13
SECTION 3 – PATTERNS
# ■■■ Program 36 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#36 36. Right-angle triangle star pattern
def prog36_star_right_triangle():
"""36. Right-angle triangle star pattern"""
n = int(input("Enter rows: "))
# Row 1 gets 1 star, row 2 gets 2 stars, …, row n gets n stars
for i in range(1, n + 1):
# "* " * i repeats the string i times (e.g. i=3 "* * * ")
print("* " * i)
# ■■■ Program 37 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#37 37. Inverted star triangle
def prog37_inverted_star():
"""37. Inverted star triangle"""
n = int(input("Enter rows: "))
# range(n, 0, -1) counts DOWN from n to 1 (step = -1)
for i in range(n, 0, -1):
print("* " * i) # Stars decrease each row
# ■■■ Program 38 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#38 38. Star pyramid
def prog38_pyramid():
"""38. Star pyramid"""
n = int(input("Enter rows: "))
for i in range(1, n + 1):
# Leading spaces make it look like a pyramid (centred)
# (n-i) spaces before the stars; stars increase each row
print(" " * (n - i) + "* " * i)
# ■■■ Program 39 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#39 39. Number right triangle
def prog39_number_triangle():
"""39. Number right triangle"""
n = int(input("Enter rows: "))
for i in range(1, n + 1):
# Inner loop prints numbers 1 to i on same row
for j in range(1, i + 1):
print(j, end=" ") # end=" " keeps numbers on same line
print() # Move to next line after each row
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 14
SECTION 4 – ARRAYS
# ■■■ Program 40 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#40 40. Accept and display 1D array
def prog40_1d_array_input():
"""40. Accept and display 1D array"""
n = int(input("Enter size of array: "))
# List comprehension: builds a list by taking n integer inputs
# for i in range(n) loops n times; each loop asks for one element
arr = [int(input(f"Enter element {i+1}: ")) for i in range(n)]
print("Array:", arr) # Displays the complete list
# ■■■ Program 41 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#41 41. Sum and average of array elements
def prog41_sum_array():
"""41. Sum and average of array elements"""
n = int(input("Enter size: "))
# f"a[{i}]:" shows index label like a[0]:, a[1]:, etc.
arr = [int(input(f"a[{i}]: ")) for i in range(n)]
print("Sum =", sum(arr)) # sum() adds all elements
print(f"Average = {sum(arr)/n:.2f}") # Average = Total / Count
# ■■■ Program 42 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#42 42. Maximum element in array
def prog42_max_array():
"""42. Maximum element in array"""
n = int(input("Enter size: "))
arr = [int(input(f"a[{i}]: ")) for i in range(n)]
# max() finds largest element in the list
print("Maximum =", max(arr))
# ■■■ Program 43 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#43 43. Minimum element in array
def prog43_min_array():
"""43. Minimum element in array"""
n = int(input("Enter size: "))
arr = [int(input(f"a[{i}]: ")) for i in range(n)]
# min() finds smallest element in the list
print("Minimum =", min(arr))
# ■■■ Program 44 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#44 44. Reverse an array
def prog44_reverse_array():
"""44. Reverse an array"""
n = int(input("Enter size: "))
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 15
arr = [int(input(f"a[{i}]: ")) for i in range(n)]
# .reverse() reverses the list in-place (modifies the original list)
[Link]()
print("Reversed array:", arr)
# ■■■ Program 45 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#45 45. Sort array in ascending order
def prog45_sort_array():
"""45. Sort array in ascending order"""
n = int(input("Enter size: "))
arr = [int(input(f"a[{i}]: ")) for i in range(n)]
# .sort() arranges elements from smallest to largest (ascending)
[Link]()
print("Sorted array:", arr)
# ■■■ Program 46 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#46 46. Linear search in array
def prog46_search_array():
"""46. Linear search in array"""
n = int(input("Enter size: "))
arr = [int(input(f"a[{i}]: ")) for i in range(n)]
key = int(input("Enter search element: ")) # Element to find
# 'in' operator checks if key exists anywhere in the list
if key in arr:
# .index() returns position (0-based index) of first occurrence
print(f"Element {key} found at index {[Link](key)}")
else:
print("Element not found")
# ■■■ Program 47 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#47 47. Accept and display 2D matrix
def prog47_2d_matrix():
"""47. Accept and display 2D matrix"""
r = int(input("Enter rows: ")) # Number of rows
c = int(input("Enter columns: ")) # Number of columns
mat = [] # Empty list to store the matrix (list of lists)
for i in range(r):
# Each row is a list of c integers; mat[i][j] style indexing
row = [int(input(f"mat[{i}][{j}]: ")) for j in range(c)]
[Link](row) # Add this row to the matrix
print("Matrix:")
for row in mat:
print(row) # Print each row as a list
# ■■■ Program 48 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#48 48. Addition of two 3x3 matrices
def prog48_matrix_addition():
"""48. Addition of two 3x3 matrices"""
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 16
# Helper function to take 3x3 matrix input
def input_matrix(name):
print(f"Enter {name} matrix (3x3):")
# Nested list comprehension: 3 rows × 3 cols
return [[int(input(f" [{i}][{j}]: ")) for j in range(3)] for i in range(3)]
A = input_matrix("first") # Read first matrix
B = input_matrix("second") # Read second matrix
# Add corresponding elements: C[i][j] = A[i][j] + B[i][j]
C = [[A[i][j] + B[i][j] for j in range(3)] for i in range(3)]
print("Resultant Matrix:")
for row in C:
print(row)
# ■■■ Program 49 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#49 49. Transpose of a matrix
def prog49_matrix_transpose():
"""49. Transpose of a matrix"""
r = int(input("Enter rows: "))
c = int(input("Enter columns: "))
# Read r×c matrix as a 2D list
mat = [[int(input(f"mat[{i}][{j}]: ")) for j in range(c)] for i in range(r)]
print("Transpose:")
# Transpose: swap row and column indices (mat[i][j] mat[j][i])
# Outer loop goes over columns of original (= rows of transpose)
for j in range(c):
# Inner: collect all elements from column j becomes row j in transpose
print([mat[i][j] for i in range(r)])
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 17
SECTION 5 – STRINGS
# ■■■ Program 50 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#50 50. Length of string using len()
def prog50_string_length():
"""50. Length of string using len()"""
s = input("Enter string: ")
# len() returns the number of characters in the string
print("Length =", len(s))
# ■■■ Program 51 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#51 51. Convert string to uppercase
def prog51_string_upper():
"""51. Convert string to uppercase"""
s = input("Enter string: ")
# .upper() converts all lowercase letters to uppercase
print("Uppercase =", [Link]())
# ■■■ Program 52 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#52 52. Convert string to lowercase
def prog52_string_lower():
"""52. Convert string to lowercase"""
s = input("Enter string: ")
# .lower() converts all uppercase letters to lowercase
print("Lowercase =", [Link]())
# ■■■ Program 53 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#53 53. Reverse a string
def prog53_string_reverse():
"""53. Reverse a string"""
s = input("Enter string: ")
# [::-1] is a slice with step -1 reads string backwards
print("Reversed =", s[::-1])
# ■■■ Program 54 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#54 54. Copy one string to another
def prog54_string_copy():
"""54. Copy one string to another"""
a = input("Enter string: ")
# In Python, strings are immutable; assigning copies the reference
b = a
print("Copied string =", b)
# ■■■ Program 55 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 18
#55 55. Compare two strings
def prog55_string_compare():
"""55. Compare two strings"""
a = input("Enter first string: ")
b = input("Enter second string: ")
# '==' compares strings character by character; case-sensitive
print("Strings are equal" if a == b else "Strings are not equal")
# ■■■ Program 56 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#56 56. Compare two strings (case-insensitive)
def prog56_string_compare_ignore():
"""56. Compare two strings (case-insensitive)"""
a = input("Enter first string: ")
b = input("Enter second string: ")
# Convert both to lowercase before comparing ignores case
# Like C's strcmpi()
print("Strings are equal" if [Link]() == [Link]() else "Strings are not equal")
# ■■■ Program 57 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#57 57. Compare first N characters of two strings
def prog57_string_compare_n():
"""57. Compare first N characters of two strings"""
a = input("Enter first string: ")
b = input("Enter second string: ")
n = int(input("Enter N: "))
# a[:n] slices first n characters; compare only those
# Like C's strncmp()
print("Equal" if a[:n] == b[:n] else "Not equal")
# ■■■ Program 58 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#58 58. Check if one string is a substring of another
def prog58_substring():
"""58. Check if one string is a substring of another"""
a = input("Enter main string: ")
b = input("Enter substring to find: ")
# 'in' keyword checks if b appears anywhere inside a
# Like C's strstr()
if b in a:
print(f"'{b}' is a substring of '{a}'")
else:
print("Not a substring")
# ■■■ Program 59 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#59 59. Check if string is palindrome
def prog59_palindrome_string():
"""59. Check if string is palindrome"""
s = input("Enter string: ")
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 19
# Reverse using [::-1]; if same as original, it's a palindrome
# Example: "madam" reversed = "madam" Palindrome
print("Palindrome" if s == s[::-1] else "Not Palindrome")
# ■■■ Program 60 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#60 60. Count vowels and consonants
def prog60_count_vowels():
"""60. Count vowels and consonants"""
# .lower() ensures we check both 'A' and 'a' as vowel
s = input("Enter string: ").lower()
# Generator expression counts characters that are vowels (a,e,i,o,u)
vowels = sum(1 for c in s if c in 'aeiou')
# .isalpha() checks if character is a letter (ignores spaces/numbers)
# A letter that is NOT a vowel is a consonant
consonants = sum(1 for c in s if [Link]() and c not in 'aeiou')
print(f"Vowels = {vowels}, Consonants = {consonants}")
# ■■■ Program 61 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#61 61. Concatenate two strings
def prog61_string_concat():
"""61. Concatenate two strings"""
a = input("Enter first string: ")
b = input("Enter second string: ")
# '+' operator joins two strings end-to-end
# Like C's strcat()
print("Concatenated =", a + b)
# ■■■ Program 62 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#62 62. Length of string without len() (manual count)
def prog62_string_length_manual():
"""62. Length of string without len() (manual count)"""
s = input("Enter string: ")
count = 0 # Counter starts at 0
# for loop iterates over each character in string
# '_' means we don't need the character itself, just count iterations
for _ in s:
count += 1 # Increment count for every character
print("Length =", count)
# ■■■ Program 63 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#63 63. Reverse string without built-in (manual loop)
def prog63_reverse_manual():
"""63. Reverse string without built-in (manual loop)"""
s = input("Enter string: ")
rev = "" # Empty string to build reversed result
# Loop through each character of s
for ch in s:
# Prepend current character to rev builds reverse
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 20
# e.g. "abc": rev = "a" "ba" "cba"
rev = ch + rev
print("Reversed =", rev)
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 21
SECTION 6 – FUNCTIONS
# Helper function: adds two numbers and returns the result
def add(a, b):
return a + b # 'return' sends result back to the caller
# Recursive function: calls itself with a smaller value
def factorial_fn(n):
# Base case: factorial of 0 is 1 (stops the recursion)
if n == 0:
return 1
# Recursive case: n! = n × (n-1)!
return n * factorial_fn(n - 1)
# Recursive Fibonacci: fib(n) = fib(n-1) + fib(n-2)
def fibonacci_fn(n):
# Base cases: fib(0) = 0, fib(1) = 1
if n <= 1:
return n
# Recursive call: sum of two previous terms
return fibonacci_fn(n - 1) + fibonacci_fn(n - 2)
# ■■■ Program 64 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#64 64. Add two numbers using a function
def prog64_function_add():
"""64. Add two numbers using a function"""
a = int(input("Enter a: "))
b = int(input("Enter b: "))
# Call the add() function defined above; it returns a+b
print("Sum =", add(a, b))
# ■■■ Program 65 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#65 65. Factorial using recursion
def prog65_recursive_factorial():
"""65. Factorial using recursion"""
n = int(input("Enter number: "))
# factorial_fn() calls itself repeatedly until n reaches 0
print("Factorial =", factorial_fn(n))
# ■■■ Program 66 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#66 66. Fibonacci using recursion
def prog66_recursive_fibonacci():
"""66. Fibonacci using recursion"""
n = int(input("How many terms: "))
# Print first n Fibonacci numbers (index 0 to n-1)
for i in range(n):
print(fibonacci_fn(i), end=" ") # fibonacci_fn(i) returns i-th term
print()
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 22
# ■■■ Program 67 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#67 67. Swap using function
def prog67_swap_function():
"""67. Swap using function"""
# Inner (nested) function defined inside prog67
def swap(a, b):
return b, a # Returns a tuple with values exchanged
a = int(input("Enter a: "))
b = int(input("Enter b: "))
# Unpack returned tuple into a and b (swap happens here)
a, b = swap(a, b)
print(f"After swap: a={a}, b={b}")
# ■■■ Program 68 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#68 68. Check prime using function
def prog68_prime_function():
"""68. Check prime using function"""
# Inner function returns True if n is prime, else False
def is_prime(n):
if n < 2:
return False # 0 and 1 are not prime
# Check divisibility up to square root of n
for i in range(2, int([Link](n)) + 1):
if n % i == 0:
return False # Found a factor not prime
return True # No factor found prime
n = int(input("Enter number: "))
# Call is_prime() and print result based on return value
print("Prime" if is_prime(n) else "Not Prime")
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 23
SECTION 7 – FILE HANDLING
# ■■■ Program 69 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#69 69. Write data to a file
def prog69_write_file():
"""69. Write data to a file"""
filename = input("Enter filename: ")
data = input("Enter text to write: ")
# open(file, 'w') opens file for WRITING; creates file if not found
# 'with' statement auto-closes file after the block ends
with open(filename, 'w') as f:
[Link](data) # Writes data string into the file
print("Data written successfully.")
# ■■■ Program 70 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#70 70. Read data from a file
def prog70_read_file():
"""70. Read data from a file"""
filename = input("Enter filename: ")
try:
# open(file, 'r') opens file for READING
with open(filename, 'r') as f:
# [Link]() reads entire file content as a single string
print("File content:\n", [Link]())
except FileNotFoundError:
# If file doesn't exist, handle error gracefully
print("File not found.")
# ■■■ Program 71 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#71 71. Append data to a file
def prog71_append_file():
"""71. Append data to a file"""
filename = input("Enter filename: ")
data = input("Enter text to append: ")
# open(file, 'a') opens file for APPENDING (doesn't erase existing content)
with open(filename, 'a') as f:
[Link]("\n" + data) # \n adds a new line before new data
print("Data appended successfully.")
# ■■■ Program 72 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#72 72. Copy one file to another
def prog72_copy_file():
"""72. Copy one file to another"""
src = input("Enter source filename: ")
dest = input("Enter destination filename: ")
try:
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 24
# Open source for reading and destination for writing simultaneously
with open(src, 'r') as s, open(dest, 'w') as d:
[Link]([Link]()) # Read all content from src and write to dest
print("File copied successfully.")
except FileNotFoundError:
print("Source file not found.")
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 25
SECTION 8 – BITWISE OPERATORS
# ■■■ Program 73 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#73 73. Demonstrate all bitwise operators
def prog73_bitwise():
"""73. Demonstrate all bitwise operators"""
a = int(input("Enter a: "))
b = int(input("Enter b: "))
# '&' AND : bit is 1 only if BOTH bits are 1
print(f"AND = {a & b}")
# '|' OR : bit is 1 if EITHER bit is 1
print(f"OR = {a | b}")
# '^' XOR : bit is 1 if bits are DIFFERENT
print(f"XOR = {a ^ b}")
# '~' NOT : flips all bits; result = -(a+1) in Python
print(f"NOT = {~a}")
# '<<' LEFT SHIFT : shifts bits left by 1 multiplies by 2
print(f"LEFT SHIFT a<<1 = {a << 1}")
# '>>' RIGHT SHIFT : shifts bits right by 1 divides by 2
print(f"RIGHT SHIFT a>>1 = {a >> 1}")
# ■■■ Program 74 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#74 74. Set a particular bit
def prog74_set_bit():
"""74. Set a particular bit"""
n = int(input("Enter number: "))
pos = int(input("Enter bit position to set: "))
# (1 << pos) creates a mask with 1 at position pos
# OR with mask forces that bit to become 1 (sets it)
n |= (1 << pos)
print("After setting bit:", n)
# ■■■ Program 75 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#75 75. Clear a particular bit
def prog75_clear_bit():
"""75. Clear a particular bit"""
n = int(input("Enter number: "))
pos = int(input("Enter bit position to clear: "))
# ~(1 << pos) creates mask with 0 at position pos, 1s everywhere else
# AND with mask forces that bit to become 0 (clears it)
n &= ~(1 << pos)
print("After clearing bit:", n)
# ■■■ Program 76 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#76 76. Toggle a particular bit
def prog76_toggle_bit():
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 26
"""76. Toggle a particular bit"""
n = int(input("Enter number: "))
pos = int(input("Enter bit position to toggle: "))
# XOR with 1 at position pos flips that bit: 01 or 10
n ^= (1 << pos)
print("After toggling bit:", n)
# ■■■ Program 77 ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
#77 77. Check if a particular bit is set
def prog77_check_bit():
"""77. Check if a particular bit is set"""
n = int(input("Enter number: "))
pos = int(input("Enter bit position: "))
# AND with mask isolates the bit at pos; non-zero means bit is 1 (SET)
print("Bit is SET" if (n & (1 << pos)) else "Bit is NOT set")
# MAIN MENU – Runs all programs via numbered selection
# Dictionary maps menu number (as string) function to call
MENU = {
# ■■ Basic Programs ■■■■■■■■■■■■■■■■■■
"1": prog1_addition,
"2": prog2_subtraction,
"3": prog3_swap,
"4": prog4_division,
"5": prog5_quadratic,
"6": prog6_ascii,
"7": prog7_square,
"8": prog8_square_root,
"9": prog9_power,
"10": prog10_salary_slip,
"11": prog11_areas,
"12": prog12_f_to_c,
"13": prog13_c_to_f,
"14": prog14_swap_no_third,
# ■■ Control Structures ■■■■■■■■■■■■■■■
"15": prog15_positive_negative,
"16": prog16_even_odd,
"17": prog17_max_two,
"18": prog18_min_two,
"19": prog19_max_three,
"20": prog20_salary_bonus,
"21": prog21_percentage,
"22": prog22_gender_salary,
"23": prog23_positive_even_odd,
"24": prog24_for_loop,
"25": prog25_while_loop,
"26": prog26_sum_1_to_n,
"27": prog27_multiplication_table,
"28": prog28_factorial,
"29": prog29_fibonacci,
"30": prog30_prime,
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 27
"31": prog31_armstrong,
"32": prog32_reverse,
"33": prog33_sum_digits,
"34": prog34_palindrome,
"35": prog35_switch_calculator,
# ■■ Patterns ■■■■■■■■■■■■■■■■■■■■■■■■
"36": prog36_star_right_triangle,
"37": prog37_inverted_star,
"38": prog38_pyramid,
"39": prog39_number_triangle,
# ■■ Arrays ■■■■■■■■■■■■■■■■■■■■■■■■■■
"40": prog40_1d_array_input,
"41": prog41_sum_array,
"42": prog42_max_array,
"43": prog43_min_array,
"44": prog44_reverse_array,
"45": prog45_sort_array,
"46": prog46_search_array,
"47": prog47_2d_matrix,
"48": prog48_matrix_addition,
"49": prog49_matrix_transpose,
# ■■ Strings ■■■■■■■■■■■■■■■■■■■■■■■■■
"50": prog50_string_length,
"51": prog51_string_upper,
"52": prog52_string_lower,
"53": prog53_string_reverse,
"54": prog54_string_copy,
"55": prog55_string_compare,
"56": prog56_string_compare_ignore,
"57": prog57_string_compare_n,
"58": prog58_substring,
"59": prog59_palindrome_string,
"60": prog60_count_vowels,
"61": prog61_string_concat,
"62": prog62_string_length_manual,
"63": prog63_reverse_manual,
# ■■ Functions ■■■■■■■■■■■■■■■■■■■■■■■
"64": prog64_function_add,
"65": prog65_recursive_factorial,
"66": prog66_recursive_fibonacci,
"67": prog67_swap_function,
"68": prog68_prime_function,
# ■■ File Handling ■■■■■■■■■■■■■■■■■■■
"69": prog69_write_file,
"70": prog70_read_file,
"71": prog71_append_file,
"72": prog72_copy_file,
# ■■ Bitwise Operators ■■■■■■■■■■■■■■■
"73": prog73_bitwise,
"74": prog74_set_bit,
"75": prog75_clear_bit,
"76": prog76_toggle_bit,
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020
DiSHA Computer Institute – Python Programs with Comments Page 28
"77": prog77_check_bit,
}
def print_menu():
"""Displays numbered section-wise menu of all programs"""
print("\n" + "="*55)
print(" DiSHA Python Programs – Menu")
print("="*55)
# Each section maps to a range of program numbers
sections = {
"Basic Programs": range(1, 15),
"Control Structures": range(15, 36),
"Patterns": range(36, 40),
"Arrays": range(40, 50),
"Strings": range(50, 64),
"Functions": range(64, 69),
"File Handling": range(69, 73),
"Bitwise Operators": range(73, 78),
}
for section, rng in [Link]():
print(f"\n [{section}]") # Print section heading
for n in rng:
fn = [Link](str(n)) # Look up function by number
if fn:
# fn. doc retrieves the docstring of the function
print(f" {n:>3}. {fn. doc }")
print("\n 0. Exit")
print("="*55)
# ■■■ Entry Point ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
# ' name == " main "' is True only when file is run directly
# (not when imported as a module); standard Python best practice
if name == " main ":
while True: # Infinite loop; broken by 'break'
print_menu() # Show menu every iteration
choice = input("\nEnter program number to run: ").strip()
if choice == "0":
print("Goodbye!")
break # Exit the while loop program ends
elif choice in MENU:
# Print header showing which program is running
print(f"\n--- Program {choice}: {MENU[choice]. doc } ---")
try:
MENU[choice]() # Call the selected function
except Exception as e:
# Catch any runtime error and display it cleanly
print(f"Error: {e}")
else:
print("Invalid choice. Please try again.")
Savitribai Phule Pune University | [Link]. Computer Science | NEP 2020