Are you a Class 11 or 12 student looking for complete Python programs for your CBSE practical file? This post brings you 100+ well-structured Python programs with output — covering everything from basics to advanced concepts like file handling, data structures, functions, Pandas, and mini projects. Whether you’re preparing for school exams, board practicals, or just want to practice and improve, these programs are organized topic-wise to help you learn Python step by step.
1. Hello World program
print("Hello, World!")
2. Display your name, age, class
name = "Vikram"
age = 16
student_class = "11th"
print("Name:", name)
print("Age:", age)
print("Class:", student_class)
3. Add two numbers
a = 10
b = 20
sum = a + b
print("Sum:", sum)
4. Find the square and cube of a number
num = 5
square = num ** 2
cube = num ** 3
print("Square:", square)
print("Cube:", cube)
5. Calculate area of circle, rectangle, triangle
import math
radius = 7
circle_area = math.pi * radius ** 2
print("Area of Circle:", circle_area)
length = 5
width = 3
rectangle_area = length * width
print("Area of Rectangle:", rectangle_area)
base = 10
height = 6
triangle_area = 0.5 * base * height
print("Area of Triangle:", triangle_area)
6. Convert Celsius to Fahrenheit
celsius = 37
fahrenheit = (celsius * 9/5) + 32
print("Fahrenheit:", fahrenheit)
7. Swap two numbers
a = 10
b = 20
a, b = b, a
print("a =", a)
print("b =", b)
8. Find the largest of three numbers
a = 15
b = 25
c = 10
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c
print("Largest number is:", largest)
9. Check if a number is even or odd
num = 9
if num % 2 == 0:
print("Even")
else:
print("Odd")
10. Find ASCII value of a character
char = 'A'
print("ASCII value of", char, "is", ord(char))
11. Check if character is vowel or consonant
ch = 'e'
if ch.lower() in 'aeiou':
print("Vowel")
else:
print("Consonant")
12. Use input() and print() formatting
name = input("Enter your name: ")
marks = float(input("Enter your marks: "))
print(f"Hello {name}, you scored {marks} marks.")
13. Use math functions (sqrt, pow, log)
import math
num = 16
print("Square Root:", math.sqrt(num))
print("2 to the power 3:", math.pow(2, 3))
print("Log base 10 of 1000:", math.log10(1000))
14. Simple calculator using if-elif-else
a = 10
b = 5
operator = input("Enter operator (+, -, *, /): ")
if operator == '+':
print("Result:", a + b)
elif operator == '-':
print("Result:", a - b)
elif operator == '*':
print("Result:", a * b)
elif operator == '/':
print("Result:", a / b)
else:
print("Invalid operator")
15. Check leap year
year = 2024
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a Leap Year")
else:
print(year, "is not a Leap Year")
Conditional & Loops
1. Check prime number
num = 29
is_prime = True
if num <= 1:
is_prime = False
else:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, "is a Prime number")
else:
print(num, "is not a Prime number")
2. Display first 10 natural numbers
for i in range(1, 11):
print(i)
3. Display multiplication table of a number
num = 5
for i in range(1, 11):
print(num, "x", i, "=", num * i)
4. Calculate factorial
num = 5
factorial = 1
for i in range(1, num + 1):
factorial *= i
print("Factorial of", num, "is", factorial)
5. Generate Fibonacci series
n = 10
a, b = 0, 1
for i in range(n):
print(a, end=" ")
a, b = b, a + b
6. Reverse a number
num = 1234
rev = 0
while num > 0:
digit = num % 10
rev = rev * 10 + digit
num //= 10
print("Reversed number is", rev)
7. Palindrome check
num = 121
temp = num
rev = 0
while num > 0:
rev = rev * 10 + num % 10
num //= 10
if temp == rev:
print("Palindrome number")
else:
print("Not a Palindrome")
8. Armstrong number check
num = 153
sum = 0
temp = num
n = len(str(num))
while temp > 0:
digit = temp % 10
sum += digit ** n
temp //= 10
if num == sum:
print("Armstrong number")
else:
print("Not an Armstrong number")
9. Count digits of a number
num = 123456
count = 0
while num > 0:
count += 1
num //= 10
print("Number of digits:", count)
10. Sum of digits
num = 1234
sum = 0
while num > 0:
sum += num % 10
num //= 10
print("Sum of digits:", sum)
Strings
1. Reverse a string
text = "hello"
reversed_text = text[::-1]
print("Reversed string:", reversed_text)
2. Check palindrome string
text = "madam"
if text == text[::-1]:
print("Palindrome string")
else:
print("Not a Palindrome")
3. Count vowels in a string
text = "Hello World"
vowels = 'aeiouAEIOU'
count = 0
for char in text:
if char in vowels:
count += 1
print("Number of vowels:", count)
4. Convert string to uppercase and lowercase
text = "Python Programming"
print("Uppercase:", text.upper())
print("Lowercase:", text.lower())
5. Count characters, words, spaces in a string
text = "Python is fun"
char_count = len(text)
word_count = len(text.split())
space_count = text.count(" ")
print("Characters:", char_count)
print("Words:", word_count)
print("Spaces:", space_count)
6. Find frequency of a character
text = "banana"
char = 'a'
frequency = text.count(char)
print("Frequency of", char, "is", frequency)
7. Replace substring
text = "I like Python"
new_text = text.replace("Python", "Java")
print("Updated string:", new_text)
8. Find longest word in a string
text = "Python Java JavaScript"
words = text.split()
longest = max(words, key=len)
print("Longest word:", longest)
9. Check anagram
str1 = "listen"
str2 = "silent"
if sorted(str1) == sorted(str2):
print("Anagram")
else:
print("Not an Anagram")
10. Remove punctuation from a string
import string
text = "Hello, World!"
cleaned = ""
for char in text:
if char not in string.punctuation:
cleaned += char
print("String without punctuation:", cleaned)
Lists & Tuples
1. Create and display a list
fruits = ["apple", "banana", "mango"]
print("Fruits list:", fruits)
2. Add and remove elements from list
numbers = [10, 20, 30]
numbers.append(40)
numbers.remove(20)
print("Updated list:", numbers)
3. Sort and reverse list
data = [5, 2, 8, 1, 9]
data.sort()
print("Sorted list:", data)
data.reverse()
print("Reversed list:", data)
4. Find max, min, sum of list
marks = [88, 76, 90, 65]
print("Maximum:", max(marks))
print("Minimum:", min(marks))
print("Sum:", sum(marks))
5. Merge two lists
list1 = [1, 2, 3]
list2 = [4, 5]
merged = list1 + list2
print("Merged list:", merged)
6. Check element in list
colors = ["red", "green", "blue"]
if "green" in colors:
print("Green is in the list")
else:
print("Green is not in the list")
7. Count frequency using list
items = ["pen", "pencil", "pen", "eraser", "pen"]
count = items.count("pen")
print("Pen appears", count, "times")
8. Convert list to tuple and vice versa
cities = ["Delhi", "Mumbai", "Chennai"]
cities_tuple = tuple(cities)
print("Tuple:", cities_tuple)
new_list = list(cities_tuple)
print("List:", new_list)
9. Create nested list
students = [["Ankit", 85], ["Riya", 92], ["Aman", 78]]
for student in students:
print("Name:", student[0], "Marks:", student[1])
10. List comprehension example
squares = [x**2 for x in range(1, 6)]
print("Squares:", squares)
Dictionaries & Sets
1. Create a dictionary with student details
student = {"name": "Riya", "age": 17, "class": "11th"}
print("Student details:", student)
2. Add, update, delete dictionary items
student = {"name": "Riya", "age": 17}
student["class"] = "11th"
student["age"] = 18
del student["name"]
print("Updated dictionary:", student)
3. Search key in dictionary
student = {"name": "Riya", "age": 17}
if "age" in student:
print("Key 'age' found")
else:
print("Key 'age' not found")
4. Count frequency of words using dictionary
text = "apple banana apple mango banana apple"
words = text.split()
frequency = {}
for word in words:
frequency[word] = frequency.get(word, 0) + 1
print("Word frequency:", frequency)
5. Merge two dictionaries
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = {**dict1, **dict2}
print("Merged dictionary:", merged)
6. Create and display set
numbers = {1, 2, 3, 4}
print("Set:", numbers)
7. Set operations (union, intersection, difference)
a = {1, 2, 3}
b = {3, 4, 5}
print("Union:", a | b)
print("Intersection:", a & b)
print("Difference:", a - b)
8. Check element in set
fruits = {"apple", "banana", "mango"}
if "banana" in fruits:
print("Banana is in the set")
else:
print("Banana is not in the set")
9. Convert list to set
colors = ["red", "green", "blue", "red"]
color_set = set(colors)
print("Set:", color_set)
10. Remove duplicates using set
nums = [1, 2, 2, 3, 4, 4, 5]
unique = list(set(nums))
print("List without duplicates:", unique)
Class 12 Python Programs
File Handling
1. Read and write a text file
with open("sample.txt", "w") as f:
f.write("This is a sample text file.")
with open("sample.txt", "r") as f:
content = f.read()
print("File content:", content)
2. Count words in a file
with open("sample.txt", "r") as f:
words = f.read().split()
print("Total words:", len(words))
3. Count lines and characters
with open("sample.txt", "r") as f:
lines = f.readlines()
line_count = len(lines)
char_count = sum(len(line) for line in lines)
print("Lines:", line_count)
print("Characters:", char_count)
4. Append text to a file
with open("sample.txt", "a") as f:
f.write("\nThis line is appended.")
with open("sample.txt", "r") as f:
print(f.read())
5. Read file line by line
with open("sample.txt", "r") as f:
for line in f:
print(line.strip())
6. Remove blank lines from file
with open("sample.txt", "r") as f:
lines = f.readlines()
with open("sample.txt", "w") as f:
for line in lines:
if line.strip():
f.write(line)
7. Copy one file to another
with open("sample.txt", "r") as f1:
data = f1.read()
with open("copy.txt", "w") as f2:
f2.write(data)
8. Search for a word in file
word_to_find = "sample"
found = False
with open("sample.txt", "r") as f:
for line in f:
if word_to_find in line:
found = True
break
if found:
print("Word found")
else:
print("Word not found")
9. Replace word in file
with open("sample.txt", "r") as f:
content = f.read()
content = content.replace("sample", "example")
with open("sample.txt", "w") as f:
f.write(content)
10. Display only numeric lines from a file
with open("sample.txt", "r") as f:
for line in f:
if line.strip().isdigit():
print("Numeric line:", line.strip())
Functions & Recursion
1. Function with arguments
def greet(name):
print("Hello", name)
greet("Riya")
2. Recursive factorial function
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print("Factorial:", factorial(5))
3. Recursive Fibonacci
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
for i in range(10):
print(fibonacci(i), end=" ")
4. Function to check prime
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
print("Prime:", is_prime(17))
5. Lambda function usage
square = lambda x: x * x
print("Square:", square(4))
6. Return multiple values
def calculate(a, b):
return a + b, a - b, a * b
add, sub, mul = calculate(10, 5)
print("Add:", add)
print("Subtract:", sub)
print("Multiply:", mul)
7. Function to reverse string
def reverse_string(s):
return s[::-1]
print("Reversed:", reverse_string("hello"))
8. Function to sort list
def sort_list(lst):
return sorted(lst)
print("Sorted list:", sort_list([4, 2, 9, 1]))
9. Function to calculate GCD
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
print("GCD:", gcd(48, 18))
10. Function to find LCM
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def lcm(a, b):
return a * b // gcd(a, b)
print("LCM:", lcm(4, 6))
Data Structures
1. Stack using list
stack = []
stack.append(10)
stack.append(20)
stack.append(30)
print("Stack after push:", stack)
stack.pop()
print("Stack after pop:", stack)
2. Queue using list
queue = []
queue.append(10)
queue.append(20)
queue.append(30)
print("Queue after enqueue:", queue)
queue.pop(0)
print("Queue after dequeue:", queue)
3. Linear search
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
data = [10, 25, 30, 45]
print("Index found at:", linear_search(data, 30))
4. Binary search
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
data = [10, 20, 30, 40, 50]
print("Index found at:", binary_search(data, 30))
5. Bubble sort
data = [64, 34, 25, 12, 22]
n = len(data)
for i in range(n):
for j in range(0, n - i - 1):
if data[j] > data[j + 1]:
data[j], data[j + 1] = data[j + 1], data[j]
print("Sorted list:", data)
6. Selection sort
data = [64, 25, 12, 22, 11]
for i in range(len(data)):
min_index = i
for j in range(i + 1, len(data)):
if data[j] < data[min_index]:
min_index = j
data[i], data[min_index] = data[min_index], data[i]
print("Sorted list:", data)
7. Insertion sort
data = [12, 11, 13, 5, 6]
for i in range(1, len(data)):
key = data[i]
j = i - 1
while j >= 0 and key < data[j]:
data[j + 1] = data[j]
j -= 1
data[j + 1] = key
print("Sorted list:", data)
8. Merge two sorted lists
a = [1, 3, 5]
b = [2, 4, 6]
merged = sorted(a + b)
print("Merged list:", merged)
9. Count even and odd numbers in list
numbers = [1, 2, 3, 4, 5, 6]
even = 0
odd = 0
for num in numbers:
if num % 2 == 0:
even += 1
else:
odd += 1
print("Even:", even)
print("Odd:", odd)
10. Store student marks using dictionary
marks = {"Riya": 85, "Aman": 78, "Kiran": 92}
for name in marks:
print("Name:", name, "Marks:", marks[name])
DataFrame using Pandas (Class 12 only)
Note: Make sure pandas library is installed (
pip install pandas
)
1. Create DataFrame from list
import pandas as pd
data = [["Riya", 85], ["Aman", 78], ["Kiran", 92]]
df = pd.DataFrame(data, columns=["Name", "Marks"])
print(df)
2. Create DataFrame from dictionary
import pandas as pd
data = {"Name": ["Riya", "Aman", "Kiran"], "Marks": [85, 78, 92]}
df = pd.DataFrame(data)
print(df)
3. Read CSV file into DataFrame
import pandas as pd
df = pd.read_csv("students.csv")
print(df)
4. Display column names and data types
print("Column Names:", df.columns)
print("Data Types:")
print(df.dtypes)
5. Select specific columns and rows
print("Only Name column:")
print(df["Name"])
print("First two rows:")
print(df.head(2))
6. Add new column
df["Grade"] = ["B", "C", "A"]
print(df)
7. Delete column
df.drop("Grade", axis=1, inplace=True)
print(df)
8. Filter rows using condition
filtered = df[df["Marks"] > 80]
print("Students with Marks > 80:")
print(filtered)
9. Sort DataFrame
sorted_df = df.sort_values(by="Marks", ascending=False)
print("Sorted by Marks:")
print(sorted_df)
10. Group by a column and calculate mean
data = {"Class": ["11", "12", "11", "12"], "Marks": [85, 90, 78, 88]}
df = pd.DataFrame(data)
grouped = df.groupby("Class")["Marks"].mean()
print("Average marks by class:")
print(grouped)
Miscellaneous/Project Based
1. Student Management System (using dictionary)
students = {}
students["101"] = {"name": "Riya", "class": "11", "marks": 85}
students["102"] = {"name": "Aman", "class": "12", "marks": 78}
for roll, details in students.items():
print("Roll No:", roll)
print("Name:", details["name"])
print("Class:", details["class"])
print("Marks:", details["marks"])
print()
2. Quiz App using if-else
score = 0
ans = input("What is the capital of India? ")
if ans.lower() == "delhi":
score += 1
ans = input("What is 5 + 3? ")
if ans == "8":
score += 1
print("Your Score:", score)
3. Mini Calculator using functions
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
else:
return "Invalid operator"
print("Result:", calculator(10, 5, '+'))
4. Grade generator from marks
marks = int(input("Enter marks: "))
if marks >= 90:
grade = 'A'
elif marks >= 75:
grade = 'B'
elif marks >= 60:
grade = 'C'
elif marks >= 40:
grade = 'D'
else:
grade = 'F'
print("Grade:", grade)
5. Bill calculator (supermarket)
items = {"milk": 40, "bread": 30, "eggs": 60}
total = 0
for item, price in items.items():
qty = int(input("Enter quantity of " + item + ": "))
total += qty * price
print("Total Bill:", total)
6. Simple password checker
password = input("Enter password: ")
if len(password) >= 8 and any(c.isdigit() for c in password) and any(c.isupper() for c in password):
print("Strong password")
else:
print("Weak password")
7. ATM simulation
balance = 1000
pin = "1234"
entered_pin = input("Enter PIN: ")
if entered_pin == pin:
amount = int(input("Enter amount to withdraw: "))
if amount <= balance:
balance -= amount
print("Withdrawn:", amount)
print("Remaining balance:", balance)
else:
print("Insufficient balance")
else:
print("Invalid PIN")
8. Voting eligibility system
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
9. Age calculator
birth_year = int(input("Enter birth year: "))
current_year = 2025
age = current_year - birth_year
print("Your age is:", age)
10. Report card generator
name = input("Enter name: ")
marks1 = int(input("Marks in Math: "))
marks2 = int(input("Marks in Science: "))
marks3 = int(input("Marks in English: "))
total = marks1 + marks2 + marks3
average = total / 3
if average >= 90:
grade = 'A'
elif average >= 75:
grade = 'B'
elif average >= 60:
grade = 'C'
elif average >= 40:
grade = 'D'
else:
grade = 'F'
print("Name:", name)
print("Total:", total)
print("Average:", average)
print("Grade:", grade)
