0% found this document useful (0 votes)
31 views

Python Programs

The document contains 12 Python programs covering topics like factorial, Armstrong number, Fibonacci series, palindrome checker, file processing, and stack implementation using lists. Multiple programs demonstrate reading/writing files, taking user input, defining functions, and using basic data structures like lists and stacks.

Uploaded by

fightfortarget25
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Python Programs

The document contains 12 Python programs covering topics like factorial, Armstrong number, Fibonacci series, palindrome checker, file processing, and stack implementation using lists. Multiple programs demonstrate reading/writing files, taking user input, defining functions, and using basic data structures like lists and stacks.

Uploaded by

fightfortarget25
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

PROGRAM -1 : Write a python

program to print factorial of


given number.

def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)

# Input from the user


num = int(input("Enter a number: "))

# Check if the number is non-negative


if num < 0:
print("Factorial is not defined for negative
numbers.")
else:
result = factorial(num)
print(f"The factorial of {num} is: {result}")
PROGRAM -2 : Write a python
program to check if the entered
number is Armstrong number or
not.

def is_armstrong_number(number):
# Convert the number to a string to find its length
num_str = str(number)
num_digits = len(num_str)

# Calculate the sum of each digit raised to the


power of the number of digits
total = sum(int(digit) ** num_digits for digit in
num_str)

# Check if the total is equal to the original number


return total == number

# Input from the user


num = int(input("Enter a number: "))

# Check if the number is an Armstrong number


if is_armstrong_number(num):
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")
PROGRAM -3 : Write a python
program to read a text file line
by line and display each word
separated by a # .

# Function to read a text file line by line and


display each word separated by a #
def display_words(filename):
try:
with open(filename, 'r') as file:
# Read each line in the file
for line in file:
# Split the line into words
words = line.split()

# Display each word separated by a #


formatted_line = "#".join(words)
print(formatted_line)

except FileNotFoundError:
print(f"The file '{filename}' was not found.")

# Input the filename from the user


file_name = input("Enter the name of the text
file: ")

# Call the function to display words separated


by #
display_words(file_name)
PROGRAM -4 : Write a python
program to print Fibonacci
series upto n terms.

def fibonacci_series(n):
fib_series = [0, 1] # Initialize the series with the
first two terms

while len(fib_series) < n:


next_term = fib_series[-1] + fib_series[-2]
fib_series.append(next_term)

return fib_series

# Input from the user


n = int(input("Enter the number of terms for the
Fibonacci series: "))

# Check if n is non-negative
if n <= 0:
print("Please enter a positive integer.")
else:
result = fibonacci_series(n)
print(f"The Fibonacci series up to {n} terms is:
{result}")
PROGRAM -5 : Write a python
program to print factors of a
given number excluding 1 &
itself..

def print_factors_excluding_ends(number):
factors = []

# Loop from 2 to the square root of the


number
for i in range(2, int(number**0.5) + 1):
# Check if i is a factor of the number
if number % i == 0:
factors.append(i)
# If the factor is not equal to the
corresponding factor on the other side of the
square root
if i != number // i:
factors.append(number // i)

# Sort the factors


factors.sort()

return factors
# Input from the user
num = int(input("Enter a number: "))

# Check if the number is positive


if num <= 0:
print("Please enter a positive integer.")
else:
result = print_factors_excluding_ends(num)
print(f"The factors of {num} (excluding 1 and
itself) are: {result}")
PROGRAM -6 : Read a text file
and display the number of
vowels/consonants/upper-
case/lower-case characters in
the file.

def count_characters(file_path):
vowels = "aeiouAEIOU"
consonants =
"bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVW
XYZ"

# Initialize counters
vowel_count = 0
consonant_count = 0
uppercase_count = 0
lowercase_count = 0

try:
with open(file_path, 'r') as file:
content = file.read()

for char in content:


if char.isalpha():
if char in vowels:
vowel_count += 1
elif char in consonants:
consonant_count += 1

if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1

except FileNotFoundError:
print(f"The file '{file_path}' was not found.")
return

print("Character counts:")
print(f"Vowels: {vowel_count}")
print(f"Consonants: {consonant_count}")
print(f"Uppercase characters:
{uppercase_count}")
print(f"Lowercase characters:
{lowercase_count}")

# Input the filename from the user


file_path = input("Enter the path of the text file:
")

# Call the function to count characters


count_characters(file_path)
PROGRAM -7 : Write a random
number generator that
generates random numbers
between 1 and 6 (Simulates a
dice).
import random

def roll_dice():
return random.randint(1, 6)

# Input from the user (optional)


num_rolls = int(input("Enter the number of
times you want to roll the dice: "))

# Roll the dice and display the results


for _ in range(num_rolls):
result = roll_dice()
print(f"You rolled a {result}")
PROGRAM -8 : Write a python
program to check whether a
string is palindrome or not
using stack.

class Stack:
def _init_(self):
self.items = []

def is_empty(self):
return len(self.items) == 0

def push(self, item):


self.items.append(item)

def pop(self):
if not self.is_empty():
return self.items.pop()

def peek(self):
if not self.is_empty():
return self.items[-1]
def is_palindrome(input_string):
stack = Stack()

# Push each character onto the stack


for char in input_string:
stack.push(char)

# Pop each character from the stack and


compare with the original string
reversed_string = ""
while not stack.is_empty():
reversed_string += stack.pop()

return input_string == reversed_string

# Input from the user


user_input = input("Enter a string: ")

# Check if the string is a palindrome


if is_palindrome(user_input):
print(f"{user_input} is a palindrome.")
else:
print(f"{user_input} is not a palindrome.")
PROGRAM -9 : Remove all the
lines that contain the character
'a' in a file and write it to
another file.

def remove_lines_with_a(input_file, output_file):


try:
with open(input_file, 'r') as file:
lines = file.readlines()

# Remove lines containing the character 'a'


modified_lines = [line for line in lines if 'a'
not in line]

with open(output_file, 'w') as file:


file.writelines(modified_lines)

print(f"Lines containing 'a' removed. Output


written to {output_file}

except FileNotFoundError:
print(f"The file '{input_file}' was not found.")

# Input file and output file names from the user


input_file_name = input("Enter the name of the
input file: ")
output_file_name = input("Enter the name of
the output file: ")

# Call the function to remove lines containing 'a'


remove_lines_with_a(input_file_name,
output_file_name}
PROGRAM -10 : Write a python
program to remove all lines
that contains the character ‘a’
in a file & write it to another
file.

def remove_lines_with_a(input_file, output_file):


try:
with open(input_file, 'r') as file:
lines = file.readlines()

# Remove lines containing the character 'a'


modified_lines = [line for line in lines if 'a'
not in line]

with open(output_file, 'w') as file:


file.writelines(modified_lines)

print(f"Lines containing 'a' removed. Output


written to {output_file}")

except FileNotFoundError:
print(f"The file '{input_file}' was not found.")
# Input file and output file names from the user
input_file_name = input("Enter the name of the
input file: ")
output_file_name = input("Enter the name of
the output file: ")

# Call the function to remove lines containing 'a'


remove_lines_with_a(input_file_name,
output_file_name)
PROGRAM -11 : Write a Python
program to implement a stack
using list.

class Stack:
def _init_(self):
self.items = []

def is_empty(self):
return len(self.items) == 0

def push(self, item):


self.items.append(item)

def pop(self):
if not self.is_empty():
return self.items.pop()

def peek(self):
if not self.is_empty():
return self.items[-1]

def size(self):
return len(self.items)
# Example usage of the stack
stack = Stack()

# Push elements onto the stack


stack.push(1)
stack.push(2)
stack.push(3)

# Display the stack


print("Stack:", stack.items)

# Pop elements from the stack


popped_item = stack.pop()
print(f"Popped item: {popped_item}")

# Display the stack after popping


print("Stack after popping:", stack.items)

# Peek at the top of the stack


top_item = stack.peek()
print(f"Top item: {top_item}")

# Check if the stack is empty


print(f"Is the stack empty? {stack.is_empty()}")

# Get the size of the stack


print(f"Size of the stack: {stack.size()}")
PROGRAM -12 : Create a binary
file with name and roll number.
Search for a given roll number
and display the name, if not
found display appropriate
message.

class Stack:
def _init_(self):
self.items = []

def is_empty(self):
return len(self.items) == 0

def push(self, item):


self.items.append(item)

def pop(self):
if not self.is_empty():
return self.items.pop()

def peek(self):
if not self.is_empty():
return self.items[-1]

def is_palindrome(input_string):
stack = Stack()

# Push each character onto the stack


for char in input_string:
stack.push(char)

# Pop each character from the stack and


compare with the original string
reversed_string = ""
while not stack.is_empty():
reversed_string += stack.pop()

return input_string == reversed_string

# Input from the user


user_input = input("Enter a string: ")

# Check if the string is a palindrome


if is_palindrome(user_input):
print(f"{user_input} is a palindrome.")
else:
print(f"{user_input} is not a palindrome.")
PROGRAM -13 : Write a python
program to check whether a
string is palindrome or not.

def is_palindrome(input_string):
# Convert the input string to lowercase and
remove spaces
cleaned_string =
''.join(input_string.lower().split())

# Compare the cleaned string with its reverse


return cleaned_string == cleaned_string[::-1]

# Input from the user


user_input = input("Enter a string: ")

# Check if the string is a palindrome


if is_palindrome(user_input):
print(f"{user_input} is a palindrome.")
else:
print(f"{user_input} is not a palindrome.")
PROGRAM -14 : Create a CSV
file by entering user-id and
password, read and search the
password for given user-id.

import csv

def write_to_csv(file_name, data):


with open(file_name, 'w', newline='') as
csv_file:
csv_writer = csv.writer(csv_file)

# Write header
csv_writer.writerow(['user_id', 'password'])

# Write data
csv_writer.writerows(data)

print(f"CSV file '{file_name}' created


successfully.")

def search_password(file_name, target_user_id):


with open(file_name, 'r') as csv_file:
csv_reader = csv.reader(csv_file)
# Skip header
next(csv_reader, None)

for row in csv_reader:


user_id, password = row

if user_id == target_user_id:
return password

return None # User-id not found

# Example data: (user_id, password)


user_data = [("user1", "password1"), ("user2",
"password2"), ("user3", "password3")]

# CSV file name


csv_file_name = "user_credentials.csv"

# Write data to the CSV file


write_to_csv(csv_file_name, user_data)

# Input user_id to search


search_user_id = input("Enter user_id to search:
")

# Search for the password and display the result


result_password =
search_password(csv_file_name, search_user_id)

if result_password is not None:


print(f"Password for user_id
'{search_user_id}': {result_password}")
else:
print(f"User_id '{search_user_id}' not found.")
PROGRAM -15 : Create a binary
file with roll number, name and
marks. Input a roll number and
update the marks.

import struct

def write_binary_file(file_name, data):


with open(file_name, 'wb') as file:
for roll_number, name, marks in data:
packed_data = struct.pack('I20s f',
roll_number, name.encode('utf-8'), marks)
file.write(packed_data)

def update_marks(file_name,
target_roll_number, new_marks):
with open(file_name, 'rb+') as file:
record_size = struct.calcsize('I20s f')

while True:
data = file.read(record_size)

if not data:
break # End of file reached
current_roll_number, current_name,
current_marks = struct.unpack('I20s f', data)
decoded_name =
current_name.decode('utf-8').rstrip('\x00') #
Decode and remove null characters

if current_roll_number ==
target_roll_number:
# Move the file pointer back to update
the marks
file.seek(-record_size, 1)
updated_data = struct.pack('I20s f',
current_roll_number, current_name, new_marks)
file.write(updated_data)
break # Exit the loop after updating

print(f"Marks updated for Roll Number


{target_roll_number}.")

# Example data: (roll_number, name, marks)


student_data = [(101, "Alice", 85.5), (102, "Bob",
92.0), (103, "Charlie", 78.5)]

# Create a binary file


file_name = "student_records.bin"
write_binary_file(file_name, student_data)
# Input roll number and new marks to update
target_roll = int(input("Enter roll number to
update marks: "))
new_marks = float(input("Enter new marks: "))

# Update marks for the specified roll number


update_marks(file_name, target_roll,
new_marks)
PROGRAM -16 : Create a
database UNIVERSITY & create
table within it.

-- Create the "UNIVERSITY" database (SQLite


syntax)
CREATE DATABASE IF NOT EXISTS UNIVERSITY;

-- Use the "UNIVERSITY" database (SQLite syntax)


USE UNIVERSITY;

-- Create a table named "students" within the


"UNIVERSITY" database (SQLite syntax)
CREATE TABLE IF NOT EXISTS students (
student_id INTEGER PRIMARY KEY,
first_name TEXT,
last_name TEXT,
age INTEGER,
major TEXT
);

-- Create the "UNIVERSITY" database (MySQL


syntax)
CREATE DATABASE IF NOT EXISTS UNIVERSITY;
-- Use the "UNIVERSITY" database (MySQL
syntax)
USE UNIVERSITY;

-- Create a table named "students" within the


"UNIVERSITY" database (MySQL syntax)
CREATE TABLE IF NOT EXISTS students (
student_id INT PRIMARY KEY,
first_name VARCHAR(255),
last_name VARCHAR(255),
age INT,
major VARCHAR(255)
);
PROGRAM -17 : Create a
student table and insert data.
Implement the following SQL
commands on the STUDENT
table: ALTER table to add new
attributes / modify data type /
drop attribute UPDATE table to
modify data.

-- Display data in ascending order of 'age'


SELECT * FROM student ORDER BY age ASC;

-- Display data in descending order of 'major'


SELECT * FROM student ORDER BY major DESC;

-- DELETE to remove a tuple with student_id = 3


DELETE FROM student WHERE student_id = 3;

-- Display data after deletion


SELECT * FROM student;
-- GROUP BY major and find MIN, MAX, SUM,
COUNT, AVG of age
SELECT
major,
MIN(age) AS min_age,
MAX(age) AS max_age,
SUM(age) AS total_age,
COUNT(*) AS total_students,
AVG(age) AS avg_age
FROM student
GROUP BY major;
PROGRAM -18 : ORDER By to
display data in ascending /
descending order DELETE to
remove tuple(s) GROUP BY and
find the min, max, sum, count
and average.

-- Display data in ascending order of 'age'


SELECT * FROM student ORDER BY age ASC;

-- Display data in descending order of 'major'


SELECT * FROM student ORDER BY major DESC;

-- DELETE to remove a tuple with student_id = 3


DELETE FROM student WHERE student_id = 3;

-- Display data after deletion


SELECT * FROM student;

-- GROUP BY major and find MIN, MAX, SUM,


COUNT, AVG of age
SELECT
major,
MIN(age) AS min_age,
MAX(age) AS max_age,
SUM(age) AS total_age,
COUNT(*) AS total_students,
AVG(age) AS avg_age
FROM student
GROUP BY major;
PROGRAM -19 :DELETE
database & remove all tables
from Database.

-- Drop all tables in the database


DROP TABLE IF EXISTS student;

-- Drop the "student" table (if exists)


DROP TABLE IF EXISTS student;

-- Drop the "UNIVERSITY" database (if exists)


-- Note: Some database systems may not support
dropping a database using SQL directly.
-- You might need to use database-specific
commands outside SQL, or use a database
management tool.
DROP DATABASE IF EXISTS UNIVERSITY;
PROGRAM -20 :Write a
program to create a database
named SCHOOL through
MySQL-Python
Connectivity.

import pymysql

# Connect to MySQL database


connection = pymysql.connect(
host='your_mysql_host',
user='your_username',
password='your_password',
database='your_database_name'
)

# Create a cursor object


cursor = connection.cursor()

# Execute SQL queries


cursor.execute('CREATE TABLE IF NOT EXISTS
users (id INT PRIMARY KEY, name VARCHAR(255),
age INT)')
cursor.execute('INSERT INTO users (name, age)
VALUES (%s, %s)', ('John Doe', 30))

# Commit the changes


connection.commit()

# Query data
cursor.execute('SELECT * FROM users')
rows = cursor.fetchall()
for row in rows:
print(row)

# Close the connection


connection.close()
PROGRAM -21 :Write a program
to insert data given below in
STUDENT table with MySQL-
Python connectivity.

import pymysql

# Replace these values with your MySQL


connection details
host = 'your_mysql_host'
user = 'your_username'
password = 'your_password'
database = 'your_database_name'

# Sample data to insert into the STUDENT table


data_to_insert = [
(1, 'Alice', 'Johnson', 20, 'Computer Science'),
(2, 'Bob', 'Smith', 22, 'Physics'),
(3, 'Charlie', 'Brown', 21, 'Mathematics'),
(4, 'David', 'Lee', 25, 'Physics'),
(5, 'Eva', 'Miller', 23, 'Mathematics')
]

try:
# Connect to MySQL database
connection = pymysql.connect(
host=host,
user=user,
password=password,
database=database
)

# Create a cursor object


cursor = connection.cursor()

# Insert data into the STUDENT table


insert_query = 'INSERT INTO STUDENT
(student_id, first_name, last_name, age, major)
VALUES (%s, %s, %s, %s, %s)'
cursor.executemany(insert_query,
data_to_insert)

# Commit the changes


connection.commit()

print("Data inserted successfully.")

except Exception as e:
print(f"Error: {e}")

finally:
# Close the connection
if connection:
connection.close()
PROGRAM -22 :Write a
program to insert data given
below in TEACHER table with
MySQL-Python
connectivity.

import pymysql

# Replace these values with your MySQL


connection details
host = 'your_mysql_host'
user = 'your_username'
password = 'your_password'
database = 'your_database_name'

# Sample data to insert into the TEACHER table


data_to_insert = [
(101, 'John', 'Math', 'Associate Professor'),
(102, 'Alice', 'Physics', 'Assistant Professor'),
(103, 'Bob', 'Chemistry', 'Professor'),
(104, 'Charlie', 'Biology', 'Lecturer'),
(105, 'David', 'Computer Science', 'Professor')
]

try:
# Connect to MySQL database
connection = pymysql.connect(
host=host,
user=user,
password=password,
database=database
)

# Create a cursor object


cursor = connection.cursor()

# Insert data into the TEACHER table


insert_query = 'INSERT INTO TEACHER
(teacher_id, name, subject, designation) VALUES
(%s, %s, %s, %s)'
cursor.executemany(insert_query,
data_to_insert)

# Commit the changes


connection.commit()

print("Data inserted successfully.")

except Exception as e:
print(f"Error: {e}")

finally:
# Close the connection
if connection:
connection.close()
PROGRAM -23 :Write a
program to fetch all the records
from STUDENT table &
TEACHER table with
MySQL-Python connectivity

import pymysql

# Replace these values with your MySQL


connection details
host = 'your_mysql_host'
user = 'your_username'
password = 'your_password'
database = 'your_database_name'

try:
# Connect to MySQL database
connection = pymysql.connect(
host=host,
user=user,
password=password,
database=database
)

# Create a cursor object


cursor = connection.cursor()

# Fetch all records from the STUDENT table


cursor.execute('SELECT * FROM STUDENT')
student_records = cursor.fetchall()

# Print STUDENT records


print("STUDENT Table:")
for record in student_records:
print(record)

print("\n---------------------------\n")

# Fetch all records from the TEACHER table


cursor.execute('SELECT * FROM TEACHER')
teacher_records = cursor.fetchall()

# Print TEACHER records


print("TEACHER Table:")
for record in teacher_records:
print(record)

except Exception as e:
print(f"Error: {e}")

finally:
# Close the connection
if connection:
connection.close()
PROGRAM -24 :Write a
program to fetch all the records
from STUDENT table who are
reading either XI or XII with
MySQL-Python connectivity.

import pymysql

# Replace these values with your MySQL


connection details
host = 'your_mysql_host'
user = 'your_username'
password = 'your_password'
database = 'your_database_name'

try:
# Connect to MySQL database
connection = pymysql.connect(
host=host,
user=user,
password=password,
database=database
)
# Create a cursor object
cursor = connection.cursor()

# Fetch records from the STUDENT table for


students in XI or XII
cursor.execute('SELECT * FROM STUDENT
WHERE class IN ("XI", "XII")')
student_records = cursor.fetchall()

# Print STUDENT records for XI or XII


print("STUDENT Table - XI or XII:")
for record in student_records:
print(record)

except Exception as e:
print(f"Error: {e}")

finally:
# Close the connection
if connection:
connection.close()
PROGRAM -25 :Write a
program to fetch all the records
from TEACHER table who are
teaching either XI or XII with
MySQL-Python connectivity..

import pymysql

# Replace these values with your MySQL


connection details
host = 'your_mysql_host'
user = 'your_username'
password = 'your_password'
database = 'your_database_name'

try:
# Connect to MySQL database
connection = pymysql.connect(
host=host,
user=user,
password=password,
database=database
)
# Create a cursor object
cursor = connection.cursor()

# Fetch records from the TEACHER table for


teachers teaching in XI or XII
cursor.execute('SELECT * FROM TEACHER
WHERE class IN ("XI", "XII")')
teacher_records = cursor.fetchall()

# Print TEACHER records for XI or XII


print("TEACHER Table - XI or XII:")
for record in teacher_records:
print(record)

except Exception as e:
print(f"Error: {e}")

finally:
# Close the connection
if connection:
connection.close()

You might also like