Python Program: Reverse a Number and Check for Palindrome
# Function to reverse a number
def reverse_number(n):
"""Reverses the digits of a number."""
reversed_num = 0
while n > 0:
digit = n % 10
reversed_num = reversed_num * 10 + digit
n = n // 10
return reversed_num
# Function to check if a number is a palindrome
def is_palindrome(n):
"""Checks if a number is a palindrome."""
return n == reverse_number(n)
# Main Program
try:
# Taking input from the user
number = int(input("Enter a positive integer: "))
# Calling the reverse_number function
reversed_number = reverse_number(number)
print(f"The reversed number is: {reversed_number}")
# Checking if it's a palindrome
if is_palindrome(number):
print(f"{number} is a palindrome!")
else:
print(f"{number} is NOT a palindrome.")
except ValueError:
print("Please enter a valid positive integer!")
Example Output (Palindrome):
Example Output (Not a Palindrome):
Python Program: Create and Read a CSV File
import csv
# Function to create and write data to a CSV file
def create_csv():
"""Creates a CSV file and writes student data."""
with open('student_data.csv', 'w', newline='') as file:
writer = csv.writer(file)
# Writing the header row
writer.writerow(["Name", "Class", "Roll Number", "Marks"])
# Writing multiple rows of data
writer.writerow(["Alice", "12", 101, 95])
writer.writerow(["Bob", "12", 102, 88])
writer.writerow(["Charlie", "12", 103, 92])
print("CSV file 'student_data.csv' created successfully!")
# Function to read data from the CSV file
def read_csv():
"""Reads data from the CSV file and displays it."""
try:
with open('student_data.csv', 'r') as file:
reader = csv.reader(file)
print("\nStudent Data:")
for row in reader:
print(', '.join(row)) # Print each row in a readable format
except FileNotFoundError:
print("The file does not exist. Please create the CSV first!")
# Main Program
print("Choose an option:")
print("1. Create a CSV File")
print("2. Read the CSV File")
choice = input("Enter your choice (1/2): ")
if choice == '1':
create_csv()
elif choice == '2':
read_csv()
else:
print("Invalid choice. Please enter 1 or 2.")
Output (Creating the CSV File):
Output (Reading the CSV File):
Python Program: Stack Implementation Using a List
# Class to implement a Stack
class Stack:
def __init__(self):
self.stack = [] # Initialize an empty list to act as the stack
# Push operation to add an element to the stack
def push(self, element):
self.stack.append(element)
print(f"{element} pushed to stack!")
# Pop operation to remove the top element from the stack
def pop(self):
if not self.is_empty():
removed_element = self.stack.pop()
print(f"Popped element: {removed_element}")
return removed_element
else:
print("Stack Underflow! The stack is empty.")
# Peek operation to view the top element without removing it
def peek(self):
if not self.is_empty():
print(f"Top element: {self.stack[-1]}")
else:
print("Stack is empty!")
# Check if the stack is empty
def is_empty(self):
return len(self.stack) == 0
# Display the entire stack
def display(self):
if not self.is_empty():
print("Stack elements (top to bottom):", self.stack[::-1])
else:
print("Stack is empty!")
# Main Program
stack = Stack()
while True:
print("\nChoose an operation:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display Stack")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
element = input("Enter the element to push: ")
stack.push(element)
elif choice == '2':
stack.pop()
elif choice == '3':
stack.peek()
elif choice == '4':
stack.display()
elif choice == '5':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice! Please enter a number between 1 and 5.")
Output:
Python Program: File Handling (Write, Read, Append)
# Function to write data to a file
def write_to_file():
with open("sample.txt", "w") as file:
file.write("Hello, this is the first line of the file.\n")
file.write("Python file handling example.\n")
print("Data written to 'sample.txt' successfully!")
# Function to read data from the file
def read_file():
try:
with open("sample.txt", "r") as file:
print("\nReading from 'sample.txt':")
print(file.read())
except FileNotFoundError:
print("The file does not exist. Please write to the file first!")
# Function to append data to the file
def append_to_file():
with open("sample.txt", "a") as file:
file.write("This line was added later using append mode.\n")
print("Data appended to 'sample.txt' successfully!")
# Main Program (Menu-driven)
while True:
print("\nChoose an operation:")
print("1. Write to file")
print("2. Read from file")
print("3. Append to file")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
write_to_file()
elif choice == '2':
read_file()
elif choice == '3':
append_to_file()
elif choice == '4':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice! Please enter a number between 1 and 4.")
Output Writing to a File:
Reading from the File:
Appending Data to the File:
Python Program: Word Count in a File
# Function to count the words in a file
def count_words_in_file():
try:
# Open the file in read mode
with open("sample.txt", "r") as file:
content = file.read()
words = content.split() # Splitting content into words using space as a separator
word_count = len(words)
print(f"\nThe file contains {word_count} words.")
except FileNotFoundError:
print("The file 'sample.txt' does not exist. Please create the file first!")
# Function to create and write to a file for testing
def create_sample_file():
with open("sample.txt", "w") as file:
file.write("This is a simple text file. It has several words.\n")
file.write("Python makes file handling easy!\n")
print("Sample file 'sample.txt' created successfully!")
# Main Program (Menu-Driven)
while True:
print("\nChoose an operation:")
print("1. Create a sample file")
print("2. Count words in the file")
print("3. Exit")
choice = input("Enter your choice (1-3): ")
if choice == '1':
create_sample_file()
elif choice == '2':
count_words_in_file()
elif choice == '3':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice! Please enter a number between 1 and 3.")
Output: Create a File
Count Words in the File
Python Program: String Operations
# Function to reverse a string
def reverse_string(s):
return s[::-1]
# Function to count vowels in a string
def count_vowels(s):
vowels = "aeiouAEIOU"
count = sum(1 for char in s if char in vowels)
return count
# Function to check if a string is a palindrome
def is_palindrome(s):
return s == s[::-1]
# Main Program
while True:
print("\nString Operations Menu:")
print("1. Reverse a string")
print("2. Count vowels in a string")
print("3. Check if a string is a palindrome")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice in ['1', '2', '3']:
user_string = input("Enter a string: ")
if choice == '1':
reversed_str = reverse_string(user_string)
print(f"Reversed String: {reversed_str}")
elif choice == '2':
vowel_count = count_vowels(user_string)
print(f"Number of vowels: {vowel_count}")
elif choice == '3':
if is_palindrome(user_string):
print(f"'{user_string}' is a palindrome!")
else:
print(f"'{user_string}' is NOT a palindrome.")
elif choice == '4':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice! Please enter a number between 1 and 4.")
# Taking input from the user
user_string = input("Enter a string: ")
# Convert the string to uppercase
uppercase_string = user_string.upper()
print(f"Uppercase: {uppercase_string}")
# Convert the string to lowercase
lowercase_string = user_string.lower()
print(f"Lowercase: {lowercase_string}")
# Calculate the length of the string
length_of_string = len(user_string)
print(f"Length of the string: {length_of_string}")
# Replace spaces with hyphens
modified_string = user_string.replace(" ", "-")
print(f"String with spaces replaced by hyphens: {modified_string}")
# Check if the string starts with a specific letter
if user_string.startswith("A"):
print("The string starts with 'A'.")
else:
print("The string does not start with 'A'.")
Output:
Python Program: Dictionary Operations
# Function to display the dictionary
def display_dict(my_dict):
if my_dict:
print("Dictionary content:", my_dict)
else:
print("The dictionary is empty!")
# Function to add a key-value pair to the dictionary
def add_to_dict(my_dict, key, value):
my_dict[key] = value
print(f"Added: {key} -> {value}")
# Function to remove a key from the dictionary
def remove_from_dict(my_dict, key):
if key in my_dict:
del my_dict[key]
print(f"Removed key: {key}")
else:
print(f"Key '{key}' not found!")
# Main Program (Menu-driven)
my_dict = {}
while True:
print("\nDictionary Operations Menu:")
print("1. Add a key-value pair")
print("2. Remove a key")
print("3. Display dictionary")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
key = input("Enter the key: ")
value = input("Enter the value: ")
add_to_dict(my_dict, key, value)
elif choice == '2':
key = input("Enter the key to remove: ")
remove_from_dict(my_dict, key)
elif choice == '3':
display_dict(my_dict)
elif choice == '4':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice! Please enter a number between 1 and 4.")
Output
Python Program: Tuple Operations
# Tuple creation
my_tuple = (10, 20, 30, 40, 50)
# Displaying the tuple
print(f"The tuple is: {my_tuple}")
# Adding an element to the tuple (by creating a new one)
my_tuple = my_tuple + (60,)
print(f"Tuple after adding 60: {my_tuple}")
# Counting occurrences of an element
count_30 = my_tuple.count(30)
print(f"Occurrences of 30: {count_30}")
# Finding the index of an element
index_40 = my_tuple.index(40)
print(f"Index of 40: {index_40}")
Output
Python Program: List Operations
# Creating a list
my_list = [10, 20, 30, 40, 50]
# Displaying the list
print(f"The list is: {my_list}")
# Adding an element to the list
my_list.append(60)
print(f"List after adding 60: {my_list}")
# Removing an element from the list
my_list.remove(30)
print(f"List after removing 30: {my_list}")
# Counting occurrences of an element
count_20 = my_list.count(20)
print(f"Occurrences of 20: {count_20}")
# Finding the index of an element
index_40 = my_list.index(40)
print(f"Index of 40: {index_40}")
Output:
Python Program: Opening and Closing a Binary File
import csv
# Writing binary data to a CSV file
def write_binary_to_csv(file_name):
with open(file_name, mode='wb') as file:
writer = csv.writer(file)
writer.writerow(["Number", "Binary Data"]) # Writing header
# Writing numbers and their binary representation
numbers = [5, 10, 15, 20] # Example numbers
for num in numbers:
binary_data = bin(num)[2:] # Convert number to binary (without '0b')
writer.writerow([num, binary_data])
print("Binary data written successfully!")
# Reading binary data from a CSV file
def read_binary_from_csv(file_name):
with open(file_name, mode='r') as file:
reader = csv.reader(file)
next(reader) # Skip the header row
print("\nReading data from the CSV file:")
# Reading and displaying the data
for row in reader:
print(f"Number: {row[0]}, Binary Data: {row[1]}")
# Main program execution
file_name = "binary_data.csv"
write_binary_to_csv(file_name) # Writing binary data to CSV
read_binary_from_csv(file_name) # Reading binary data from CSV
# Writing to a binary file
def write_binary_file():
with open("data.bin", "wb") as file: # 'wb' means write binary mode
data = [10, 20, 30, 40, 50]
for num in data:
file.write(num.to_bytes(2, 'big')) # Writing numbers as binary data
print("Binary file created and closed successfully!")
# Reading from a binary file
def read_binary_file():
with open("data.bin", "rb") as file: # 'rb' means read binary mode
print("\nReading data from the binary file:")
while byte_data := file.read(2): # Reading 2 bytes at a time
number = int.from_bytes(byte_data, 'big') # Converting bytes back to
integer
print(number)
print("Binary file closed successfully!")
# Main Program Execution
write_binary_file() # Write to binary file
read_binary_file() # Read from binary file
Output
Python Program: Stack with Pop Operation
# Stack implementation using a list
stack = [] # Empty stack
# Function to push an element into the stack
def push(element):
stack.append(element)
print(f"{element} pushed to the stack.")
# Function to pop an element from the stack
def pop():
if not stack:
print("Stack Underflow! The stack is empty.")
else:
element = stack.pop()
print(f"Popped element: {element}")
# Function to display the stack
def display():
if not stack:
print("The stack is empty.")
else:
print(f"Current Stack: {stack}")
# Main Program
push(10)
push(20)
push(30)
display()
# Performing pop operations
pop()
display()
pop()
display()
pop()
display()
# Trying to pop from an empty stack
pop()
Output Example:
Python Program: Stack with Push Operation
# Stack implementation using a list
stack = [] # Empty stack
# Function to push an element into the stack
def push(element):
stack.append(element)
print(f"{element} pushed to the stack.")
# Function to display the stack
def display():
if not stack:
print("The stack is empty.")
else:
print(f"Current Stack: {stack}")
# Main Program
push(10)
push(20)
push(30)
display() # Displaying the stack after pushing elements
Output
Python Program: Exception Handling
# Program to demonstrate exception handling in Python
def divide_numbers():
try:
# Taking user input
num1 = int(input("Enter the numerator: "))
num2 = int(input("Enter the denominator: "))
# Attempting division
result = num1 / num2
print(f"Result: {result}")
# Handling division by zero error
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
# Handling invalid input error
except ValueError:
print("Error: Please enter valid integers.")
# This block always runs
finally:
print("End of the exception handling demonstration.")
# Calling the function
divide_numbers()
Output: Valid Input
Python Program: Using Breakpoints and break Statement
import pdb # Importing the Python Debugger
def find_number(numbers, target):
# Setting a breakpoint for debugging
pdb.set_trace()
for num in numbers:
print(f"Checking number: {num}")
if num == target:
print(f"Target {target} found!")
break # Exits the loop when the target is found
else:
print(f"Target {target} not found in the list.")
# Main Program
numbers_list = [10, 20, 30, 40, 50]
target_number = int(input("Enter a number to search: "))
find_number(numbers_list, target_number)
Output (with breakpoints in action):
Python Program: Traversing a List Using for Loop
# Defining a list of numbers
numbers = [10, 20, 30, 40, 50]
# Traversing the list using a for loop
print("Traversing the list using a for loop:")
for number in numbers:
print(number) # Printing each element in the list
Output
Create a Database and Table
import sqlite3
# Connect to the database (creates one if it doesn't exist)
conn = sqlite3.connect('school.db')
cursor = conn.cursor()
# Create a table named 'students'
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT,
grade INTEGER
)
''')
print("Database and table created successfully!")
conn.commit()
conn.close()
Insert Data into the Table
import sqlite3
conn = sqlite3.connect('school.db')
cursor = conn.cursor()
# Inserting data into the 'students' table
cursor.execute("INSERT INTO students (name, grade) VALUES (?, ?)", ("Alice", 90))
cursor.execute("INSERT INTO students (name, grade) VALUES (?, ?)", ("Bob", 85))
print("Data inserted successfully!")
conn.commit()
conn.close()
Fetch and Display Data from the Table
import sqlite3
conn = sqlite3.connect('school.db')
cursor = conn.cursor()
# Fetch all records from the 'students' table
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
print("Displaying all records:")
for row in rows:
print(row)
conn.close()
Update a Record in the Table
import sqlite3
conn = sqlite3.connect('school.db')
cursor = conn.cursor()
# Updating the grade for a student named "Alice"
cursor.execute("UPDATE students SET grade = ? WHERE name = ?", (95, "Alice"))
print("Record updated successfully!")
conn.commit()
conn.close()
Delete a Record from the Table
import sqlite3
conn = sqlite3.connect('school.db')
cursor = conn.cursor()
# Deleting a record where the student's name is "Bob"
cursor.execute("DELETE FROM students WHERE name = ?", ("Bob",))
print("Record deleted successfully!")
conn.commit()
conn.close()