Python Programs Collection
Complete set of 20 Python programs with outputs
Program 1: Basic Calculator ([Link])
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
add = a + b
sub = a - b
mul = a * b
div = a / b
print("Addition =", add)
print("Subtraction =", sub)
print("Multiplication =", mul)
print("Division =", div)
Expected Output:
Enter first number: 10
Enter second number: 5
Addition = 15.0
Subtraction = 5.0
Multiplication = 50.0
Division = 2.0
Program 2: Perfect Number Check ([Link])
num = int(input("Enter a number: "))
sum = 0
for i in range(1, num):
if num % i == 0:
sum = sum + i
if sum == num:
print(num, "is a Perfect Number.")
else:
print(num, "is not a Perfect Number.")
Expected Output:
Enter a number: 28
28 is a Perfect Number.
Enter a number: 12
Page 1
Python Programs Collection
Complete set of 20 Python programs with outputs
12 is not a Perfect Number.
Program 3: Armstrong Number Check ([Link])
num = int(input("Enter a number: "))
n = len(str(num))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** n
temp //= 10
if num == sum:
print(num, "is an Armstrong number")
else:
print(num, "is not an Armstrong number")
Expected Output:
Enter a number: 153
153 is an Armstrong number
Enter a number: 123
123 is not an Armstrong number
Program 4: Factorial Calculation ([Link])
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, num + 1):
factorial = factorial * i
print("The factorial of", num, "is", factorial)
Expected Output:
Enter a number: 5
Page 2
Python Programs Collection
Complete set of 20 Python programs with outputs
The factorial of 5 is 120
Enter a number: 0
The factorial of 0 is 1
Enter a number: -3
Factorial does not exist for negative numbers
Program 5: Fibonacci Series ([Link])
n = int(input("Enter the number of terms: "))
a = 0
b = 1
print("Fibonacci Series:")
if n <= 0:
print("Please enter a positive number")
elif n == 1:
print(a)
else:
print(a, b, end=" ")
for i in range(2, n):
c = a + b
print(c, end=" ")
a = b
b = c
Expected Output:
Enter the number of terms: 8
Fibonacci Series:
0 1 1 2 3 5 8 13
Page 3
Python Programs Collection
Complete set of 20 Python programs with outputs
Program 6: Palindrome Check ([Link])
string = input("Enter a string: ")
reverse = ""
for i in range(len(string) - 1, -1, -1):
reverse = reverse + string[i]
if string == reverse:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Expected Output:
Enter a string: radar
The string is a palindrome.
Enter a string: hello
The string is not a palindrome.
Program 7: Count Words Starting with Vowels ([Link])
text = input("Enter a string: ")
words = [Link]()
count = 0
vowels = "AEIOUaeiou"
for word in words:
if word[0] in vowels:
count += 1
print("Number of words starting with vowels:", count)
Expected Output:
Enter a string: Apple and orange are fruits
Number of words starting with vowels: 3
Program 8: File Processing ([Link])
file = open("[Link]", "r")
vowels = "AEIOUaeiou"
Page 4
Python Programs Collection
Complete set of 20 Python programs with outputs
print("Lines that do not start with a vowel:\n")
for line in file:
line = [Link]()
if line != "" and line[0] not in vowels:
print(line)
[Link]()
Expected Output:
Lines that do not start with a vowel:
This is line 1
Python programming
Hello world
Sample text
Program 9: File Copy with Filter ([Link])
source = open("[Link]", "r") # open file in read mode
destination = open("[Link]", "w") # open file in write mode
for line in source:
if 'a' in line or 'A' in line:
[Link](line)
[Link]()
[Link]()
print("Lines containing 'a' have been copied to [Link] successfully.")
Expected Output:
Lines containing 'a' have been copied to [Link] successfully.
Program 10: Text Analysis ([Link])
file = open("[Link]", "r")
vowels = 0
Page 5
Python Programs Collection
Complete set of 20 Python programs with outputs
consonants = 0
uppercase = 0
lowercase = 0
vowel_letters = "AEIOUaeiou"
for line in file:
for ch in line:
if [Link]():
if ch in vowel_letters:
vowels += 1
else:
consonants += 1
if [Link]():
uppercase += 1
elif [Link]():
lowercase += 1
[Link]()
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)
print("Number of uppercase letters:", uppercase)
print("Number of lowercase letters:", lowercase)
Expected Output:
Number of vowels: 25
Number of consonants: 40
Number of uppercase letters: 5
Number of lowercase letters: 60
Page 6
Python Programs Collection
Complete set of 20 Python programs with outputs
Program 11: Student Records with Pickle ([Link])
import pickle
file= open("[Link]","wb")
n = int(input("Enter number of students: "))
for i in range(n):
roll = int(input("Enter roll number: "))
name = input("Enter name: ")
record = [roll, name]
[Link](record,file)
[Link]()
print("\nData written to [Link] successfully!\n")
file = open("[Link]", "rb")
found = False
roll_search = int(input("Enter roll number to search: "))
try:
while True:
record = [Link](file)
if record[0] == roll_search:
print("Name of student:", record[1])
found = True
break
except EOFError:
[Link]()
if not found:
print("No student found with roll number:",roll_search)
Expected Output:
Enter number of students: 3
Enter roll number: 101
Enter name: Tarun
Enter roll number: 102
Enter name: Anita
Enter roll number: 103
Enter name: Rohit
Page 7
Python Programs Collection
Complete set of 20 Python programs with outputs
Data written to [Link] successfully!
Enter roll number to search: 102
Name of student: Anita
Program 12: Dice Roll Simulator ([Link])
import random
dice = [Link](1, 6)
print("You rolled:", dice)
Expected Output:
You rolled: 4
You rolled: 6
You rolled: 1
Program 13: Stack Implementation ([Link])
stack = []
while True:
print("\n--- Stack Operations ---")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
choice = int(input("Enter your choice (1-4): "))
if choice == 1:
item = input("Enter element to push: ")
[Link](item)
print(item, "pushed into stack.")
elif choice == 2:
if len(stack) == 0:
print("Stack is empty! cannot pop.")
else:
item = [Link]()
Page 8
Python Programs Collection
Complete set of 20 Python programs with outputs
print(item,"popped from stack.")
elif choice == 3:
if len(stack)==0:
print ("stack is empty.")
else:
print("Current Stack:", stack)
elif choice == 4:
print("Exiting program.")
break
else:
print("Invalid choice! Please enter 1-4.")
Expected Output:
--- Stack Operations ---
1. Push
2. Pop
3. Display
4. Exit
Enter your choice (1-4): 1
Enter element to push: Apple
Apple pushed into stack.
--- Stack Operations ---
1. Push
2. Pop
3. Display
4. Exit
Enter your choice (1-4): 1
Enter element to push: Banana
Banana pushed into stack.
--- Stack Operations ---
1. Push
2. Pop
3. Display
4. Exit
Enter your choice (1-4): 3
Current Stack: ['Apple', 'Banana']
Page 9
Python Programs Collection
Complete set of 20 Python programs with outputs
--- Stack Operations ---
1. Push
2. Pop
3. Display
4. Exit
Enter your choice (1-4): 2
Banana popped from stack.
--- Stack Operations ---
1. Push
2. Pop
3. Display
4. Exit
Enter your choice (1-4): 4
Exiting program.
Page 10
Python Programs Collection
Complete set of 20 Python programs with outputs
Program 14: Find Longest Word ([Link])
file = open("[Link]", "r")
longest_word = ""
max_length = 0
for line in file:
words = [Link]()
for word in words:
if len(word) > max_length:
max_length = len(word)
longest_word = word
[Link]()
print("The longest word is:", longest_word)
print("Length of the word:", max_length)
Expected Output:
The longest word is: programming
Length of the word: 11
Program 15: CSV Employee Data Processing ([Link])
import csv
filename = input("Enter the CSV file name ([Link]): ")
file = open("[Link]", "r")
data = [Link](file)
next(data)
print("Employees having salary less than 30000:\n")
for record in data:
empno = record[0]
ename = record[1]
age = int(record[2])
salary = float(record[3])
Page 11
Python Programs Collection
Complete set of 20 Python programs with outputs
joindate = record[4]
if salary < 30000:
print(ename)
[Link]()
Expected Output:
Enter the CSV file name ([Link]): [Link]
Employees having salary less than 30000:
Rohit Sharma
Priya Gupta
Neha Reddy
Program 16: MySQL Student Table Operations ([Link])
import [Link]
try:
con = [Link](
host="localhost",
user="root",
password="696969",
database="school"
)
cur = [Link]()
print("Connected to database 'school'.")
[Link]("DROP TABLE IF EXISTS student")
print("Old 'student' table dropped (if existed).")
[Link]("""
CREATE TABLE student (
rollno INT PRIMARY KEY,
name VARCHAR(50),
age INT,
marks INT
Page 12
Python Programs Collection
Complete set of 20 Python programs with outputs
);
""")
print("Table 'student' created successfully.")
[Link]("""
INSERT INTO student (rollno, name, age, marks)
VALUES (%s, %s, %s, %s)
""", [
(1, 'Tarun', 17, 88),
(2, 'Anita', 16, 75),
(3, 'Rohit', 18, 92),
(4, 'Simran', 17, 60),
(5, 'Vivek', 16, 85)
])
[Link]()
print("Records inserted successfully.")
[Link]("ALTER TABLE student ADD COLUMN city VARCHAR(30)")
print("Column 'city' added successfully.")
[Link]("UPDATE student SET city='Delhi' WHERE marks > 80")
[Link]()
print("Updated student records successfully.")
print("\nStudents ordered by marks (DESC):")
[Link]("SELECT * FROM student ORDER BY marks DESC")
for row in [Link]():
print(row)
[Link]("DELETE FROM student WHERE marks < 65")
[Link]()
print("\nDeleted students with marks below 65.")
print("\nSummary of student marks:")
[Link]("""
SELECT
COUNT(*) AS Total_Students,
MIN(marks) AS Min_Marks,
MAX(marks) AS Max_Marks,
SUM(marks) AS Total_Marks,
Page 13
Python Programs Collection
Complete set of 20 Python programs with outputs
AVG(marks) AS Avg_Marks
FROM student
""")
for row in [Link]():
print(row)
except [Link] as err:
print("Error:", err)
finally:
if con.is_connected():
[Link]()
[Link]()
print("\nMySQL connection closed.")
Expected Output:
Connected to database 'school'.
Old 'student' table dropped (if existed).
Table 'student' created successfully.
Records inserted successfully.
Column 'city' added successfully.
Updated student records successfully.
Students ordered by marks (DESC):
(3, 'Rohit', 18, 92, 'Delhi')
(1, 'Tarun', 17, 88, 'Delhi')
(5, 'Vivek', 16, 85, 'Delhi')
(2, 'Anita', 16, 75, None)
(4, 'Simran', 17, 60, None)
Deleted students with marks below 65.
Summary of student marks:
(4, 75, 92, 340, 85.0)
Page 14
Python Programs Collection
Complete set of 20 Python programs with outputs
Program 17: Create MySQL Database ([Link])
import [Link]
try:
con = [Link](
host="localhost",
user="root",
password="696969"
)
if con.is_connected():
print("Successfully connected to MySQL Server.")
cur = [Link]()
[Link]("CREATE DATABASE IF NOT EXISTS school")
print("Database 'school' created successfully!")
except [Link] as err:
print("Error:", err)
finally:
if con.is_connected():
[Link]()
[Link]()
print("MySQL connection closed.")
Expected Output:
Successfully connected to MySQL Server.
Database 'school' created successfully!
MySQL connection closed.
Program 18: MySQL - Students with Marks > 75 ([Link])
import [Link]
try:
con = [Link](
host="localhost",
Page 15
Python Programs Collection
Complete set of 20 Python programs with outputs
user="root",
password="696969",
database="school"
)
cur = [Link]()
print("Connected to database 'school'.")
print("\nStudents with Marks Greater than 75:")
print("-" * 70)
query = """
SELECT rollno, stream, name, class, marks
FROM student
WHERE marks > 75
ORDER BY marks DESC
"""
[Link](query)
high_achievers = [Link]()
print(f"{'Roll No':<8} {'Stream':<10} {'Name':<15} {'Class':<6} {'Marks':<6}")
print("-" * 70)
if high_achievers:
for row in high_achievers:
print(f"{row[0]:<8} {row[1]:<10} {row[2]:<15} {row[3]:<6} {row[4]:<6}")
print(f"\nTotal students with marks > 75: {len(high_achievers)}")
else:
print("No students found with marks greater than 75.")
except [Link] as err:
print("Database Error:", err)
finally:
if con.is_connected():
[Link]()
[Link]()
Page 16
Python Programs Collection
Complete set of 20 Python programs with outputs
print("\nMySQL connection closed.")
Expected Output:
Connected to database 'school'.
Students with Marks Greater than 75:
----------------------------------------------------------------------
Roll No Stream Name Class Marks
----------------------------------------------------------------------
3 Science Rohit Kumar 12 92
1 Science Tarun Sharma 12 88
5 Science Vivek Patel 12 85
6 Commerce Priya Gupta 11 78
Total students with marks > 75: 4
MySQL connection closed.
Page 17
Python Programs Collection
Complete set of 20 Python programs with outputs
Program 19: MySQL - Students with Grade 'A' ([Link])
import [Link]
try:
con = [Link](
host="localhost",
user="root",
password="696969",
database="school"
)
cur = [Link]()
print("Connected to database 'school' successfully.")
[Link]("SHOW TABLES LIKE 'student'")
table_exists = [Link]()
if not table_exists:
print("Table 'student' does not exist. Creating table with sample data...")
[Link]("""
CREATE TABLE student (
rollno INT PRIMARY KEY,
name VARCHAR(50),
class INT,
marks INT,
grade VARCHAR(2)
)
""")
print("Table 'student' created successfully.")
[Link]("""
INSERT INTO student (rollno, name, class, marks, grade)
VALUES (%s, %s, %s, %s, %s)
""", [
(1, 'Tarun Sharma', 12, 92, 'A'),
(2, 'Anita Verma', 11, 78, 'B'),
(3, 'Rohit Kumar', 12, 85, 'A'),
Page 18
Python Programs Collection
Complete set of 20 Python programs with outputs
(4, 'Simran Singh', 11, 65, 'C'),
(5, 'Vivek Patel', 12, 95, 'A'),
(6, 'Priya Gupta', 11, 72, 'B'),
(7, 'Raj Malhotra', 12, 88, 'A'),
(8, 'Neha Reddy', 11, 58, 'D')
])
[Link]()
print("Sample records inserted successfully.")
print("\nAll Student Records:")
print("=" * 60)
[Link]("SELECT * FROM student ORDER BY rollno")
all_students = [Link]()
print(f"{'Roll No':<8} {'Name':<15} {'Class':<6} {'Marks':<6} {'Grade':<6}")
print("-" * 60)
for row in all_students:
print(f"{row[0]:<8} {row[1]:<15} {row[2]:<6} {row[3]:<6} {row[4]:<6}")
print("\nStudents with Grade 'A':")
print("=" * 60)
query = """
SELECT rollno, name, class, marks, grade
FROM student
WHERE grade = 'A'
ORDER BY marks DESC
"""
[Link](query)
grade_a_students = [Link]()
print(f"{'Roll No':<8} {'Name':<15} {'Class':<6} {'Marks':<6} {'Grade':<6}")
print("-" * 60)
if grade_a_students:
for row in grade_a_students:
print(f"{row[0]:<8} {row[1]:<15} {row[2]:<6} {row[3]:<6} {row[4]:<6}")
print("\nSummary for Grade 'A' Students:")
Page 19
Python Programs Collection
Complete set of 20 Python programs with outputs
print("-" * 30)
print(f"Total students with grade 'A': {len(grade_a_students)}")
[Link]("SELECT AVG(marks) FROM student WHERE grade = 'A'")
avg_marks = [Link]()[0]
print(f"Average marks: {avg_marks:.2f}")
[Link]("SELECT MAX(marks) FROM student WHERE grade = 'A'")
max_marks = [Link]()[0]
print(f"Highest marks: {max_marks}")
else:
print("No students found with grade 'A'.")
except [Link] as err:
print(f"MySQL Error: {err}")
finally:
if con.is_connected():
[Link]()
[Link]()
print("\nMySQL connection closed.")
Expected Output:
Connected to database 'school' successfully.
All Student Records:
============================================================
Roll No Name Class Marks Grade
------------------------------------------------------------
1 Tarun Sharma 12 92 A
2 Anita Verma 11 78 B
3 Rohit Kumar 12 85 A
4 Simran Singh 11 65 C
5 Vivek Patel 12 95 A
6 Priya Gupta 11 72 B
7 Raj Malhotra 12 88 A
8 Neha Reddy 11 58 D
Page 20
Python Programs Collection
Complete set of 20 Python programs with outputs
Students with Grade 'A':
============================================================
Roll No Name Class Marks Grade
------------------------------------------------------------
5 Vivek Patel 12 95 A
1 Tarun Sharma 12 92 A
7 Raj Malhotra 12 88 A
3 Rohit Kumar 12 85 A
Summary for Grade 'A' Students:
------------------------------
Total students with grade 'A': 4
Average marks: 90.00
Highest marks: 95
MySQL connection closed.
Program 20: MySQL - Total Student Count ([Link])
import [Link]
try:
con = [Link](
host="localhost",
user="root",
password="696969",
database="school"
)
cur = [Link]()
print("Connected to database 'school' successfully.")
[Link]("SELECT COUNT(*) FROM student")
total_count = [Link]()[0]
print(f"\nTOTAL NUMBER OF STUDENTS: {total_count}")
if total_count > 0:
print(f"\nDISPLAYING ALL {total_count} STUDENT RECORDS:")
print("=" * 60)
Page 21
Python Programs Collection
Complete set of 20 Python programs with outputs
[Link]("SELECT * FROM student ORDER BY rollno")
all_students = [Link]()
[Link]("DESCRIBE student")
columns = [col[0] for col in [Link]()]
header = ""
for col in columns:
header += f"{col:<12}"
print(header)
print("-" * 60)
for student in all_students:
row = ""
for value in student:
row += f"{str(value):<12}"
print(row)
else:
print("No students found in the database.")
except [Link] as err:
print(f"MySQL Error: {err}")
finally:
if con.is_connected():
[Link]()
[Link]()
print("\nMySQL connection closed.")
Expected Output:
Connected to database 'school' successfully.
TOTAL NUMBER OF STUDENTS: 8
DISPLAYING ALL 8 STUDENT RECORDS:
============================================================
rollno name class marks grade
Page 22
Python Programs Collection
Complete set of 20 Python programs with outputs
------------------------------------------------------------
1 Tarun Sharma 12 92 A
2 Anita Verma 11 78 B
3 Rohit Kumar 12 85 A
4 Simran Singh 11 65 C
5 Vivek Patel 12 95 A
6 Priya Gupta 11 72 B
7 Raj Malhotra 12 88 A
8 Neha Reddy 11 58 D
MySQL connection closed.
Page 23
Python Programs Collection
Complete set of 20 Python programs with outputs
Programs Summary
PROGRAMS CATEGORIZATION:
1. BASIC PROGRAMS:
- Program 1: Basic Calculator
- Program 4: Factorial Calculation
- Program 5: Fibonacci Series
- Program 12: Dice Roll Simulator
2. NUMBER THEORY:
- Program 2: Perfect Number Check
- Program 3: Armstrong Number Check
3. STRING OPERATIONS:
- Program 6: Palindrome Check
- Program 7: Count Words Starting with Vowels
4. FILE HANDLING:
- Program 8: File Processing
- Program 9: File Copy with Filter
- Program 10: Text Analysis
- Program 14: Find Longest Word
5. DATA STRUCTURES:
- Program 13: Stack Implementation
- Program 11: Student Records with Pickle
6. DATABASE OPERATIONS (MySQL):
- Program 16: Student Table Operations
- Program 17: Create Database
- Program 18: Students with Marks > 75
- Program 19: Students with Grade 'A'
- Program 20: Total Student Count
7. DATA PROCESSING:
- Program 15: CSV Employee Data Processing
Page 24
Python Programs Collection
Complete set of 20 Python programs with outputs
TOTAL PROGRAMS: 20
This collection demonstrates various Python programming concepts including:
- Basic syntax and operations
- Control structures (loops, conditionals)
- Functions and modules
- File I/O operations
- Data structures
- Database connectivity
- Data processing and analysis
Each program includes:
* Complete source code
* Expected output in formatted boxes
* Clear program descriptions
Page 25