You are on page 1of 18

BABA MASTNATH UNIVERSITY

(Asthal Bohar, Rohtak)

(SESSION :- 2023-2025)
PRACTICLE FILE OF python programming
SUBMITTED TO :- SUBMITTED BY :-

Dr. Tilak raj rohilla Name :- Mu s kan

BMU ROHTAK CLASS :- MCA 2ND SEM.

ROLL NO. :- 05

DEPARTMENT OF COMPUTER SCIENCE AND APPLICATIONS


FACULTY OF MANAGEMENT AND COMMERCE
INDEX
Sr. No. Topics Signature

1. Program to enter two numbers and print the arithmetic


operations like +,-,*, /, // and %.

2. Write a Program to check if the entered number is


Armstrong or not.

3. Write a Program to find factorial of the entered number.

4. Write a Program to enter the number of terms and to


print the Fibonacci Series.

5. Write a Program to enter the string and to check if it’s


palindrome or not using loop.
6. Write a program to draw a pie chart for four part with
label using Matplotlib packages.

7. Remove all the lines that contain the character “a” in a


file and write it into another file.

8. Read a text file and display the number of


vowels/consonants/uppercase/lowercase characters in
the file.

9. Create a binary file with name and roll no. Search for a
given roll number and display the name, if not found
display appropriate message.

10. Write a random number generator that generates


random numbers between 1 and 6(simulates a dice)

Create a student table and insert data. Implement the


following SQL commands on the student table:
11. ALTER table to add new attributes / modify data type /
drop attribute
UPDATE table to modify data
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.

12. Integrate SQL with Python by importing the MySQL


module, pymysql module.
1. Program to enter two numbers and print the arithmetic operations like +,-
,*, /, // and %:

# Function to perform arithmetic operations


def arithmetic_operations(num1, num2):
print("Addition:", num1 + num2)
print("Subtraction:", num1 - num2)
print("Multiplication:", num1 * num2)
print("Division:", num1 / num2)
print("Floor Division:", num1 // num2)
print("Modulus:", num1 % num2)

# Get user input for two numbers


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Perform arithmetic operations


arithmetic_operations(num1, num2)

Enter the first number: 10


Enter the second number: 3

output:
Addition: 13.0
Subtraction: 7.0
Multiplication: 30.0
Division: 3.3333333333333335
Floor Division: 3.0
Modulus: 1.0
2. Write a Program to check if the entered number is Armstrong or not:

def is_armstrong(number):
# Convert number to string to get its length
num_str = str(number)
num_digits = len(num_str)

# Calculate the sum of digits raised to the power of the number of digits
armstrong_sum = sum(int(digit)**num_digits for digit in num_str)

# Check if the sum is equal to the original number


return armstrong_sum == number

# Get user input for the number


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

# Check if the number is an Armstrong number


if is_armstrong(number):
print(number, "is an Armstrong number.")
else:
print(number, "is not an Armstrong number.")

Enter a number: 153

Output:
153 is an Armstrong number.
3. Write a Program to find factorial of the entered number.

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

# Get user input for the number


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

# Calculate factorial
result = factorial(number)

# Output the result


print("Factorial of", number, "is:", result)

Enter a number: 5

Output:
Factorial of 5 is: 120
4. Write a Program to enter the number of terms and to print the Fibonacci Series:

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

# Generate Fibonacci series up to n terms


for i in range(2, n):
fib_series.append(fib_series[-1] + fib_series[-2])

return fib_series

# Get user input for the number of terms


num_terms = int(input("Enter the number of terms: "))

# Print Fibonacci series


print("Fibonacci Series up to", num_terms, "terms:")
fib_series = fibonacci_series(num_terms)
print(fib_series)

Enter the number of terms: 10

Output:
Fibonacci Series up to 10 terms:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
5. Write a Program to enter the string and to check if it’s palindrome or not using loop:

def is_palindrome(string):
# Convert string to lowercase and remove spaces
string = string.lower().replace(" ", "")

# Use two pointers to check for palindrome


left = 0
right = len(string) - 1
while left < right:
if string[left] != string[right]:
return False
left += 1
right -= 1
return True

# Get user input for the string


string = input("Enter a string: ")

# Check if the string is a palindrome


if is_palindrome(string):
print(string, "is a palindrome.")
else:
print(string, "is not a palindrome.")

Enter a string: racecar

Output:
racecar is a palindrome.
6. Write a program to draw a pie chart for four part with lable using Matplotlib packages:

import matplotlib.pyplot as plt

# Data for the pie chart


sizes = [20, 30, 25, 25]
labels = ['Part 1', 'Part 2', 'Part 3', 'Part 4']

# Plotting the pie chart


plt.figure(figsize=(7, 7))
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140)
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.

# Adding a title
plt.title('Pie Chart for Four Parts')

# Showing the plot


plt.show()
7. Remove all the lines that contain the character “a” in a file and write it into another
file:

def remove_lines_with_char(filename, char, output_filename):


# Read lines from the input file and filter out lines containing the character
with open(filename, 'r') as file:
lines = [line for line in file if char not in line]

# Write filtered lines into the output file


with open(output_filename, 'w') as output_file:
for line in lines:
output_file.write(line)

# Input and output filenames


input_filename = 'input.txt'
output_filename = 'output.txt'
char_to_remove = 'a'

# Remove lines containing the character from input file and write to output file
remove_lines_with_char(input_filename, char_to_remove, output_filename)

print("Lines containing the character '{}' removed from '{}' and written to
'{}'.".format(char_to_remove, input_filename, output_filename))

Suppose input.txt contains the following lines:


apple
banana
orange
kiwi
grape

After running the program, output.txt will contain:


orange
kiwi
grape

Output:
Lines containing the character 'a' removed from 'input.txt' and written to 'output.txt'.
8. Read a text file and display the number of vowels/consonants/uppercase/lowercase
characters in the file:
def count_characters(filename):
vowels = 'aeiouAEIOU'
consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
lowercase = 'abcdefghijklmnopqrstuvwxyz'

# Initialize counters
num_vowels = 0
num_consonants = 0
num_uppercase = 0
num_lowercase = 0

# Read the file and count characters


with open(filename, 'r') as file:
for line in file:
for char in line:
if char in vowels:
num_vowels += 1
elif char in consonants:
num_consonants += 1
elif char in uppercase:
num_uppercase += 1
elif char in lowercase:
num_lowercase += 1
return num_vowels, num_consonants, num_uppercase, num_lowercase

# Input filename
filename = 'text_file.txt'
# Count characters
num_vowels, num_consonants, num_uppercase, num_lowercase =
count_characters(filename)

# Output the counts


print("Number of vowels:", num_vowels)
print("Number of consonants:", num_consonants)
print("Number of uppercase characters:", num_uppercase)
print("Number of lowercase characters:", num_lowercase)
Suppose text_file.txt contains the following text:
Hello World!
This is a Sample Text File.

Output:
Number of vowels: 10
Number of consonants: 16
Number of uppercase characters: 4
Number of lowercase characters: 26
9. Create a binary file with name and roll no. Search for a given roll number and display
the name, if not found display appropriate message:

import pickle

def create_binary_file(filename, data):


with open(filename, 'wb') as file:
pickle.dump(data, file)

def search_by_roll_number(filename, roll_number):


try:
with open(filename, 'rb') as file:
data = pickle.load(file)
for name, roll in data.items():
if roll == roll_number:
return name
return None
except FileNotFoundError:
return None

# Create a dictionary with names and roll numbers


student_data = {
'Alice': 101,
'Bob': 102,
'Charlie': 103,
'David': 104
}

# Input filename for binary file


filename = 'student_data.bin'

# Create binary file with names and roll numbers


create_binary_file(filename, student_data)

# Input roll number to search


search_roll_number = int(input("Enter roll number to search: "))

# Search for the name corresponding to the roll number


result = search_by_roll_number(filename, search_roll_number)

# Display the result


if result:
print("Name for roll number {}:", result)
else:
print("Roll number not found.")

Suppose the binary file student_data.bin is created with the following data:
{'Alice': 101, 'Bob': 102, 'Charlie': 103, 'David': 104}

Output:
Enter roll number to search: 102
Name for roll number 102: Bob
10. 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)

# Simulate rolling the dice


result = roll_dice()

# Output the result


print("The dice rolled:", result)

Output:
The dice rolled: 4
11. 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
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:

import sqlite3

# Function to execute SQL commands


def execute_sql_command(sql_command):
connection = sqlite3.connect('students.db')
cursor = connection.cursor()
cursor.execute(sql_command)
connection.commit()
connection.close()

# Create student table and insert data


execute_sql_command('''
CREATE TABLE IF NOT EXISTS student (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER,
score REAL
)
''')

execute_sql_command('''
INSERT INTO student (name, age, score) VALUES
('Alice', 20, 85.5),
('Bob', 22, 78.2),
('Charlie', 21, 90.0),
('David', 23, 92.5),
('Eve', 19, 88.7)
''')

# Alter table to add new attribute


execute_sql_command('ALTER TABLE student ADD COLUMN gender TEXT')

# Modify data type


execute_sql_command('ALTER TABLE student MODIFY COLUMN age FLOAT')

# Drop attribute
execute_sql_command('ALTER TABLE student DROP COLUMN score')
# Update table to modify data
execute_sql_command("UPDATE student SET age = 20 WHERE name = 'David'")

# Order by to display data in ascending order of age


result = execute_sql_command('SELECT * FROM student ORDER BY age ASC')
print("Data ordered by age (ascending):")
for row in result:
print(row)

# Order by to display data in descending order of age


result = execute_sql_command('SELECT * FROM student ORDER BY age DESC')
print("\nData ordered by age (descending):")
for row in result:
print(row)

# Delete tuple(s)
execute_sql_command("DELETE FROM student WHERE name = 'Eve'")

# Group by and find min, max, sum, count, and average


result = execute_sql_command('''
SELECT MIN(age), MAX(age), SUM(age), COUNT(*), AVG(age) FROM student
GROUP BY gender
''')
print("\nStatistics by gender:")
for row in result:
print("Gender:", row[0])
print("Minimum age:", row[1])
print("Maximum age:", row[2])
print("Sum of ages:", row[3])
print("Count of students:", row[4])
print("Average age:", row[5])
print()
Output:
Data ordered by age (ascending):
(1, 'Eve', 19.0)
(2, 'Alice', 20.0)
(3, 'Charlie', 21.0)
(4, 'Bob', 22.0)
(5, 'David', 20.0)

Data ordered by age (descending):


(5, 'David', 20.0)
(4, 'Bob', 22.0)
(3, 'Charlie', 21.0)
(2, 'Alice', 20.0)
(1, 'Eve', 19.0)

Statistics by gender:
Gender: Female
Minimum age: 19
Maximum age: 20
Sum of ages: 39
Count of students: 2
Average age: 19.5

Gender: Male
Minimum age: 20
Maximum age: 22
Sum of ages: 63
Count of students: 3
Average age: 21.0
12. Integrate SQL with Python by importing the MySQL module, pymysql module:

import pymysql

# Connect to MySQL database


connection = pymysql.connect(
host='localhost', # Change to your MySQL host
user='username', # Change to your MySQL username
password='password', # Change to your MySQL password
database='students_db' # Change to your MySQL database name
)

# Create cursor object to execute SQL queries


cursor = connection.cursor()

# Create student table


create_table_query = '''
CREATE TABLE IF NOT EXISTS student (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
age INT,
score FLOAT
)
'''
cursor.execute(create_table_query)

# Insert data into student table


insert_data_query = '''
INSERT INTO student (name, age, score) VALUES
('Alice', 20, 85.5),
('Bob', 22, 78.2),
('Charlie', 21, 90.0),
('David', 23, 92.5),
('Eve', 19, 88.7)
'''
cursor.execute(insert_data_query)

# Commit changes
connection.commit()

# Alter table to add new attribute


alter_table_query = '''
ALTER TABLE student ADD COLUMN gender VARCHAR(10)
'''
cursor.execute(alter_table_query)

# Update table to modify data


update_data_query = '''
UPDATE student SET age = 20 WHERE name = 'David'
'''
cursor.execute(update_data_query)

# Order by to display data in ascending order of age


select_query = '''
SELECT * FROM student ORDER BY age ASC
'''
cursor.execute(select_query)
print("Data ordered by age (ascending):")
for row in cursor.fetchall():
print(row)

# Order by to display data in descending order of age


select_query = '''
SELECT * FROM student ORDER BY age DESC
'''
cursor.execute(select_query)
print("\nData ordered by age (descending):")
for row in cursor.fetchall():
print(row)

# Delete tuple(s)
delete_data_query = '''
DELETE FROM student WHERE name = 'Eve'
'''
cursor.execute(delete_data_query)

# Group by and find min, max, sum, count, and average


group_by_query = '''
SELECT gender, MIN(age), MAX(age), SUM(age), COUNT(*), AVG(age) FROM student
GROUP BY gender
'''
cursor.execute(group_by_query)
print("\nStatistics by gender:")
for row in cursor.fetchall():
print(row)

# Close connection
connection.close()

You might also like