[go: up one dir, main page]

0% found this document useful (0 votes)
24 views43 pages

CS Practical File Aditya

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views43 pages

CS Practical File Aditya

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

#Write a program to take input from user and check if it is prime or not.

while True:

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

if number <= 1:

print(f"{number} is not a prime number.")

else:

is_prime = True

for i in range(2, int(number ** 0.5) + 1): # Check divisors from 2 to √number

if number % i == 0:

is_prime = False

break

if is_prime:

print(f"{number} is a prime number.")

else:

print(f"{number} is not a prime number.")


Write a program to check a number whether it is palindrome or not.

while True:

number = input("Enter a number : ")

if number.lower() == "exit":

print("Exiting...")

break

if number == number[::-1]:

print(f"{number} is a palindrome.")

else:

print(f"{number} is not a palindrome.")


Write a program to display ASCII code of a character and vice versa

while True:
print("\nChoose an option:")
print("1. Get ASCII code of a character")
print("2. Get character from ASCII code")
print("3. Exit")
choice = input("Enter your choice (1/2/3): ")

if choice == "1":
char = input("Enter a single character: ")
if len(char) == 1:
print(f"The ASCII code of '{char}' is {ord(char)}.")
else:
print("Please enter only one character.")
elif choice == "2":
try:
ascii_code = int(input("Enter an ASCII code (0-127): "))
if 0 <= ascii_code <= 127:
print(f"The character for ASCII code {ascii_code} is '{chr(ascii_code)}'.")
else:
print("Please enter a valid ASCII code between 0 and 127.")
except ValueError:
print("Invalid input. Please enter a number.")
elif choice == "3":
print("Exiting...")
break
else:
print("Invalid choice. Please select 1, 2, or 3.")
Write a program to input numbers in a list and display sum of all elements of it.

numbers = []
count = 0
n = int(input("Enter the number of elements: "))
print("Enter the numbers:")
while count < n:
num = float(input(f"Element {count + 1}: "))
numbers.append(num)
count += 1
total_sum = sum(numbers)
print(f"The sum of all elements in the list {numbers} is: {total_sum}")
Write a program to print Fibonacci series.

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

a, b = 0, 1

print("Fibonacci series:")

if n <= 0:

print("Please enter a positive integer.")

elif n == 1:

print(a)

else:

print(a, b, end=" ")

for _ in range(2, n):

c=a+b

print(c, end=" ")

a, b = b, c
Write a program to calculate the LCM and GCD of two numbers entered by the user

def gcd(a, b):

while b:

a, b = b, a % b

return a

def lcm(a, b):

return abs(a * b) // gcd(a, b)

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

gcd_value = gcd(num1, num2)

lcm_value = lcm(num1, num2)

print(f"The GCD of {num1} and {num2} is: {gcd_value}")

print(f"The LCM of {num1} and {num2} is: {lcm_value}")


Write a program that import the module NUM_GEN created as per previous question and generate
the specific numbers as per user request.

import NUM_GEN

print("\nSelect the type of numbers to generate:")

print("1. Prime Numbers")

print("2. Armstrong Numbers")

print("3. Strong Numbers")

print("4. Perfect Numbers")

print("5. Even Numbers")

print("6. Odd Numbers")

print("7. Composite Numbers")

print("8. Exit")

while True:

choice = int(input("\nEnter your choice (1-8): "))

if choice == 1:

start = int(input("Enter the starting number of the range: "))

end = int(input("Enter the ending number of the range: "))

primes = NUM_GEN.generate_primes(start, end)

print(f"Prime numbers between {start} and {end}: {primes}")

elif choice == 2:

start = int(input("Enter the starting number of the range: "))

end = int(input("Enter the ending number of the range: "))

armstrongs = NUM_GEN.generate_armstrongs(start, end)

print(f"Armstrong numbers between {start} and {end}: {armstrongs}")

elif choice == 3:

start = int(input("Enter the starting number of the range: "))

end = int(input("Enter the ending number of the range: "))

strongs = NUM_GEN.generate_strongs(start, end)

print(f"Strong numbers between {start} and {end}: {strongs}")


elif choice == 4:

start = int(input("Enter the starting number of the range: "))

end = int(input("Enter the ending number of the range: "))

perfects = NUM_GEN.generate_perfects(start, end)

print(f"Perfect numbers between {start} and {end}: {perfects}")

elif choice == 5:

start = int(input("Enter the starting number of the range: "))

end = int(input("Enter the ending number of the range: "))

evens = NUM_GEN.generate_evens(start, end)

print(f"Even numbers between {start} and {end}: {evens}")

elif choice == 6:

start = int(input("Enter the starting number of the range: "))

end = int(input("Enter the ending number of the range: "))

odds = NUM_GEN.generate_odds(start, end)

print(f"Odd numbers between {start} and {end}: {odds}")

elif choice == 7:

start = int(input("Enter the starting number of the range: "))

end = int(input("Enter the ending number of the range: "))

composites = NUM_GEN.generate_composites(start, end)

print(f"Composite numbers between {start} and {end}: {composites}")

elif choice == 8:

print("Exiting the program. Goodbye!")

break

else:

print("Invalid choice, please try again.")


Write a Program to search any word as per user choice in given string/sentence.

sentence = input("Enter a sentence: ")

word = input("Enter the word to search: ")

print(f"The word '{word}' {'is' if word in sentence else 'is not'} in the sentence.")
Write a program to read a text file line by line and display each word separated by '#'.

with open("myfile.txt", "r") as file:

for line in file:

print('#'.join(line.split()))
Write a program to count the number of vowels present in a text file.

vowels = "aeiouAEIOU"

count = 0

with open("cspracticle.txt", "r") as file:

for line in file:

count += sum(1 for char in line if char in vowels)

print(f"Number of vowels: {count}")


Write a program to count number of words in a file.

with open("input.txt", "r") as file:

print(f"Number of words: {sum(len(line.split()) for line in file)}")


Write a program to count the number of times the occurrence of 'is' word in a text
file.

with open("ABC.txt", "r") as file:

text = file.read()

print(f"Occurrences of 'is': {text.split().count('is')}")


Write a program to write those lines which have the character 'p' from one text file to another text
file.

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

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

try:

with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:

for line in infile:

if 'p' in line:

outfile.write(line)

print(f"Lines containing 'p' have been written to '{output_file}'.")

except FileNotFoundError:

print(f"Error: File '{input_file}' not found.")

except Exception as e:

print(f"An error occurred: {e}")


Write a program to read a random line from a text file.

import random

# Input file name

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

try:

# Open the file and read all lines

with open(filename, 'r') as file:

lines = file.readlines()

if lines: # Check if there are lines in the file

random_line = random.choice(lines) # Pick a random line

print("Random line from the file:")

print(random_line.strip())

else:

print("The file is empty.")

except FileNotFoundError:

print(f"Error: File '{filename}' not found.")

except Exception as e:

print(f"An error occurred: {e}")


Write a Program to read the content of file and display the total number of
consonants, uppercase, vowels and lower-case characters.

vowels, consonants, uppercase, lowercase = 0, 0, 0, 0

with open("ABC.txt", "r") as file:

for line in file:

for char in line:

if char.isalpha():

if char in "aeiouAEIOU":

vowels += 1

else:

consonants += 1

if char.isupper():

uppercase += 1

else:

lowercase += 1

print(f"Vowels: {vowels}, Consonants: {consonants}, Uppercase: {uppercase}, Lowercase:


{lowercase}")
Write a program to find the most common word in a file.

from collections import Counter

with open("input.txt", "r") as file:

words = file.read().split()

common_word = Counter(words).most_common(1)[0]

print(f"Most common word: '{common_word[0]}' with {common_word[1]} occurrences")


Create a binary file with name and roll number of student and display the data by reading the file.

import pickle

filename = "student.dat"

try:

with open(filename, 'wb') as file:

name = input("Enter the student's name: ")

roll_number = int(input("Enter the student's roll number: "))

student = {'Name': name, 'Roll Number': roll_number}

pickle.dump(student, file)

print(f"Data written to {filename} successfully.")

except Exception as e:

print(f"An error occurred while writing to the file: {e}")

try:

with open(filename, 'rb') as file:

student_data = pickle.load(file)

print("\nData read from the binary file:")

print(f"Name: {student_data['Name']}")

print(f"Roll Number: {student_data['Roll Number']}")

except Exception as e:

print(f"An error occurred while reading the file: {e}")


Write a program to search a record using its roll number and display the name of
student. If record not found then display appropriate message.

import pickle

filename = "students_with_date.dat"

try:

with open(filename, 'wb') as file:

students = [

{'Roll Number': 101, 'Name': 'Divyanshu', 'Date': '2022-08-15'},

{'Roll Number': 102, 'Name': 'Aditya' , 'Date': '2023-01-10'},

{'Roll Number': 103, 'Name': 'Vansh', 'Date': '2023-05-25'}

for student in students:

pickle.dump(student, file)

print("Sample data has been written to the file.")

except Exception as e:

print(f"An error occurred while adding sample data: {e}")

try:

roll_to_search = int(input("\nEnter the roll number to search: "))

found = False

with open(filename, 'rb') as file:

while True:

try:

student = pickle.load(file)

if student['Roll Number'] == roll_to_search:

print("\nRecord Found:")

print(f"Name: {student['Name']}")

print(f"Roll Number: {student['Roll Number']}")

print(f"Date: {student['Date']}")

found = True

break

except EOFError:
break

if not found:

print("Record not found.")

except FileNotFoundError:

print(f"Error: File '{filename}' not found.")

except Exception as e:

print(f"An error occurred: {e}")


Write a program to update the name of student by using its roll number in a binary
file.

import pickle

filename = "students_with_date.dat"

# Adding sample data (if needed)

try:

# Add sample records for demonstration

with open(filename, 'wb') as file:

students = [

{'Roll Number': 101, 'Name': 'Alice', 'Date': '2022-08-15'},

{'Roll Number': 102, 'Name': 'Bob', 'Date': '2023-01-10'},

{'Roll Number': 103, 'Name': 'Charlie', 'Date': '2023-05-25'}

for student in students:

pickle.dump(student, file)

print("Sample data has been written to the file.")

except Exception as e:

print(f"An error occurred while adding sample data: {e}")

# Updating the name of a student

try:

roll_to_update = int(input("\nEnter the roll number to update: "))

new_name = input("Enter the new name: ")

updated = False

records = []

# Read all records from the file

with open(filename, 'rb') as file:

while True:
try:

student = pickle.load(file)

if student['Roll Number'] == roll_to_update:

student['Name'] = new_name # Update the name

updated = True

records.append(student)

except EOFError:

break

# Write the updated records back to the file

with open(filename, 'wb') as file:

for record in records:

pickle.dump(record, file)

if updated:

print("Record updated successfully.")

else:

print("Record not found.")

except FileNotFoundError:

print(f"Error: File '{filename}' not found.")

except Exception as e:

print(f"An error occurred: {e}")


Write a program to delete a record from binary file.

import pickle

filename = "students_with_dates.dat"

try:

with open(filename, 'wb') as file:

students = [

{'Roll Number': 101, 'Name': 'vansh', 'Date': '2022-08-15'},

{'Roll Number': 102, 'Name': 'Krish', 'Date': '2023-01-10'},

{'Roll Number': 103, 'Name': 'aditya', 'Date': '2023-05-25'}

for student in students:

pickle.dump(student, file)

print("Sample data has been written to the file.")

except Exception as e:

print(f"An error occurred while adding sample data: {e}")

try:

roll_to_delete = int(input("\nEnter the roll number to delete: "))

deleted = False

records = []

with open(filename, 'rb') as file:

while True:

try:

student = pickle.load(file)

if student['Roll Number'] == roll_to_delete:

deleted = True

else:

records.append(student)

except EOFError:

break

with open(filename, 'wb') as file:


for record in records:

pickle.dump(record, file)

if deleted:

print("Record deleted successfully.")

else:

print("Record not found.")

except FileNotFoundError:

print(f"Error: File '{filename}' not found.")

except Exception as e:

print(f"An error occurred: {e}")


Write a program to read data from a csv file and write data to a csv file.

import csv

# Reading data from a CSV file

input_file = "input_data.csv"

try:

print("Reading data from the CSV file:")

with open(input_file, mode='r') as file:

csv_reader = csv.reader(file)

for row in csv_reader:

print(row) # Each row is a list

except FileNotFoundError:

print(f"Error: File '{input_file}' not found.")

except Exception as e:

print(f"An error occurred while reading the file: {e}")

# Writing data to a CSV file

output_file = "output_data.csv"

data_to_write = [

["Roll Number", "Name", "Marks"],

[101, "Alice", 85],

[102, "Bob", 90],

[103, "Charlie", 78]

try:

print("\nWriting data to the CSV file:")

with open(output_file, mode='w', newline='') as file:

csv_writer = csv.writer(file)

csv_writer.writerows(data_to_write)
print(f"Data written to '{output_file}' successfully.")

except Exception as e:

print(f"An error occurred while writing to the file: {e}")

INPUT

OUTPUT

FILE SAVED
Write a program to create a library in python and import it in a program.

def add(a, b):

return a + b

def subtract(a, b):

return a - b

def multiply(a, b):

return a * b

def divide(a, b):

if b != 0:

return a / b

else:

return "Division by zero is not allowed"

import mymath

def main():

print("Addition:", mymath.add(5, 3))

print("Subtraction:", mymath.subtract(5, 3))

print("Multiplication:", mymath.multiply(5, 3))

print("Division:", mymath.divide(5, 3))

print("Division by zero:", mymath.divide(5, 0))

if _name_ == "_main_":

main()
Write a python program to implement searching methods based on user choice using a list data-
structure. (linear/binary).
Read a text file line by line and display each word separated by a #.

input_file = 'input.txt'

try:

with open(input_file, 'r') as file:

for line in file:

words = line.split() # Split the line into words

print('#'.join(words)) # Join words with #

except FileNotFoundError:

print(f"Error: The file '{input_file}' does not exist.")


Remove all the lines that contain the character 'a' in a file and write it to another file.

input_file = 'cspracticle.txt'

output_file = 'output_1.txt'

try:

with open(input_file, 'r') as file:

lines = file.readlines()

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

for line in lines:

if 'a' not in line:

file.write(line)

print(f"Lines without 'a' have been written to '{output_file}'.")

except FileNotFoundError:

print(f"Error: The file '{input_file}' does not exist.")


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.

import pickle

students = [

{'Roll Number': 101, 'Name': 'vansh'},

{'Roll Number': 102, 'Name': 'divyanshu'},

{'Roll Number': 103, 'Name': 'adiya'}

with open('students.dat', 'wb') as file:

pickle.dump(students, file)

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

found = False

with open('students.dat', 'rb') as file:

students = pickle.load(file)

for student in students:

if student['Roll Number'] == search_roll:

print(f"Student Found: {student['Name']}")

found = True

break

if not found:

print("Student not found.")


Create a binary file with roll number, name and marks. Input a roll number and update the marks.

import pickle

# Create and write a binary file with roll number, name, and marks

students = [

{'Roll Number': 101, 'Name': 'Alice', 'Marks': 85},

{'Roll Number': 102, 'Name': 'Bob', 'Marks': 90},

{'Roll Number': 103, 'Name': 'Charlie', 'Marks': 78}

# Write to binary file

with open('students_with_marks.dat', 'wb') as file:

pickle.dump(students, file)

# Update marks based on roll number

roll_to_update = int(input("Enter the roll number to update marks: "))

new_marks = int(input("Enter the new marks: "))

updated = False

with open('students_with_marks.dat', 'rb') as file:

students = pickle.load(file)

# Update the marks if roll number matches

for student in students:

if student['Roll Number'] == roll_to_update:

student['Marks'] = new_marks

updated = True

# Save the updated students back to the file

with open('students_with_marks.dat', 'wb') as file:


pickle.dump(students, file)

if updated:

print(f"Marks updated for roll number {roll_to_update}.")

else:

print(f"Roll number {roll_to_update} not found.")


Write a random number generator that generates random numbers between 1 and 6 (simulates a
dice).

import random

dice_roll = random.randint(1, 6)

print(f"The dice roll result is: {dice_roll}")


Create a CSV file by entering user-id and password, read and search the password for given user id.

import csv

csv_file = 'user_data.csv'

user_data = [

['User ID', 'Password'],

['user1', 'pass123'],

['user2', 'password456'],

['user3', 'qwerty789']

with open(csv_file, mode='w', newline='') as file:

writer = csv.writer(file)

writer.writerows(user_data)

user_id = input("Enter the user ID to search for password: ")

found = False

with open(csv_file, mode='r') as file:

reader = csv.reader(file)

for row in reader:

if row[0] == user_id:

print(f"Password for {user_id}: {row[1]}")

found = True

break

if not found:

print(f"User ID {user_id} not found.")


Create a student table and insert data. Implement the following SQL commands on the
student table:
o ALTER table to add new attributes / modify data type / drop attribute
o UPDATE table to modify data
o ORDER By to display data in ascending / descending order
o DELETE to remove tuple(s)
o GROUP BY and find the min, max, sum, count and average

CREATE TABLE student (


student_id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
grade CHAR(2),
major VARCHAR(50)
);
INSERT INTO student (student_id, name, age, grade, major) VALUES
(1, 'Alice', 20, 'A', 'Mathematics'),
(2, 'Bob', 22, 'B', 'Physics'),
(3, 'Charlie', 23, 'C', 'Chemistry');
ALTER TABLE student ADD COLUMN email VARCHAR(100);
ALTER TABLE student MODIFY COLUMN grade VARCHAR(3);
ALTER TABLE student DROP COLUMN major;
UPDATE student SET age = 21 WHERE student_id = 1;
SELECT * FROM student ORDER BY name ASC;
SELECT * FROM student ORDER BY age DESC;
SELECT * FROM student ORDER BY name ASC;
SELECT * FROM student ORDER BY age DESC;
DELETE FROM student WHERE student_id = 3;
SELECT
MIN(age) AS min_age,
MAX(age) AS max_age,
SUM(age) AS total_age,
COUNT(*) AS count_students,
AVG(age) AS average_age
FROM student
GROUP BY grade;
Write a python MYSQL connectivity program that can create a database named as Comp_Sci.

pip install mysql-connector-python

import mysql.connector

from mysql.connector import Error

try:

connection = mysql.connector.connect(

host='localhost', # Replace with your host

user='your_username', # Replace with your MySQL username

password='your_password' # Replace with your MySQL password

if connection.is_connected():

cursor = connection.cursor()

cursor.execute("CREATE DATABASE Comp_Sci")

print("Database Comp_Sci created successfully.")

except Error as e:

print(f"Error: {e}")

finally:

if connection.is_connected():

cursor.close()

connection.close()

print("MySQL connection is closed.


Write a python MYSQL connectivity program insert record in table students having following fields:

Roll_No Integer

S_Name varchar(20)

S_class char(4)

S_Marks Integer

pip install mysql-connector-python

import mysql.connector

from mysql.connector import Error

try:

connection = mysql.connector.connect(

host='localhost',

user='your_username',

password='your_password',

database='Comp_Sci'

if connection.is_connected():

cursor = connection.cursor()

cursor.execute("""

CREATE TABLE IF NOT EXISTS students (

Roll_No INT PRIMARY KEY,

S_Name VARCHAR(20),

S_class CHAR(4),

S_Marks INT

""")

insert_query = """

INSERT INTO students (Roll_No, S_Name, S_class, S_Marks)

VALUES (%s, %s, %s, %s)

"""
record = (1, 'John Doe', 'XII', 85)

cursor.execute(insert_query, record)

connection.commit()

print("Record inserted successfully into students table.")

except Error as e:

print(f"Error: {e}")

finally:

if connection.is_connected():

cursor.close()

connection.close()

print("MySQL connection is closed.")


Write a python MYSQL connectivity program that can display all records from tables
students from database named as Comp_Sci.

pip install mysql-connector-python

import mysql.connector

from mysql.connector import Error

try:

connection = mysql.connector.connect(

host='localhost', # Replace with your host

user='your_username', # Replace with your MySQL username

password='your_password', # Replace with your MySQL password

database='Comp_Sci' # Database created earlier

if connection.is_connected():

cursor = connection.cursor()

cursor.execute("SELECT * FROM students")

records = cursor.fetchall()

print("Displaying all records from students table:")

for record in records:

print(record)

except Error as e:

print(f"Error: {e}")

finally:

if connection.is_connected():

cursor.close()

connection.close()

print("MySQL connection is closed.")


Write a python MYSQL connectivity program to search a record from tables students from
database named as Comp_Sci on the basis of roll_no.

pip install mysql-connector-python

import mysql.connector

from mysql.connector import Error

try:

connection = mysql.connector.connect(

host='localhost', # Replace with your host

user='your_username', # Replace with your MySQL username

password='your_password', # Replace with your MySQL password

database='Comp_Sci' # Database created earlier

if connection.is_connected():

cursor = connection.cursor()

cursor.execute("SELECT * FROM students")

records = cursor.fetchall()

print("Displaying all records from students table:")

for record in records:

print(record)

except Error as e:

print(f"Error: {e}")

finally:

if connection.is_connected():

cursor.close()

connection.close()

print("MySQL connection is closed.")

You might also like