CS Practical File Aditya
CS Practical File Aditya
while True:
if number <= 1:
else:
is_prime = True
if number % i == 0:
is_prime = False
break
if is_prime:
else:
while True:
if number.lower() == "exit":
print("Exiting...")
break
if number == number[::-1]:
print(f"{number} is a palindrome.")
else:
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.
a, b = 0, 1
print("Fibonacci series:")
if n <= 0:
elif n == 1:
print(a)
else:
c=a+b
a, b = b, c
Write a program to calculate the LCM and GCD of two numbers entered by the user
while b:
a, b = b, a % b
return a
import NUM_GEN
print("8. Exit")
while True:
if choice == 1:
elif choice == 2:
elif choice == 3:
elif choice == 5:
elif choice == 6:
elif choice == 7:
elif choice == 8:
break
else:
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 '#'.
print('#'.join(line.split()))
Write a program to count the number of vowels present in a text file.
vowels = "aeiouAEIOU"
count = 0
text = file.read()
try:
if 'p' in line:
outfile.write(line)
except FileNotFoundError:
except Exception as e:
import random
try:
lines = file.readlines()
print(random_line.strip())
else:
except FileNotFoundError:
except Exception as e:
if char.isalpha():
if char in "aeiouAEIOU":
vowels += 1
else:
consonants += 1
if char.isupper():
uppercase += 1
else:
lowercase += 1
words = file.read().split()
common_word = Counter(words).most_common(1)[0]
import pickle
filename = "student.dat"
try:
pickle.dump(student, file)
except Exception as e:
try:
student_data = pickle.load(file)
print(f"Name: {student_data['Name']}")
except Exception as e:
import pickle
filename = "students_with_date.dat"
try:
students = [
pickle.dump(student, file)
except Exception as e:
try:
found = False
while True:
try:
student = pickle.load(file)
print("\nRecord Found:")
print(f"Name: {student['Name']}")
print(f"Date: {student['Date']}")
found = True
break
except EOFError:
break
if not found:
except FileNotFoundError:
except Exception as e:
import pickle
filename = "students_with_date.dat"
try:
students = [
pickle.dump(student, file)
except Exception as e:
try:
updated = False
records = []
while True:
try:
student = pickle.load(file)
updated = True
records.append(student)
except EOFError:
break
pickle.dump(record, file)
if updated:
else:
except FileNotFoundError:
except Exception as e:
import pickle
filename = "students_with_dates.dat"
try:
students = [
pickle.dump(student, file)
except Exception as e:
try:
deleted = False
records = []
while True:
try:
student = pickle.load(file)
deleted = True
else:
records.append(student)
except EOFError:
break
pickle.dump(record, file)
if deleted:
else:
except FileNotFoundError:
except Exception as e:
import csv
input_file = "input_data.csv"
try:
csv_reader = csv.reader(file)
except FileNotFoundError:
except Exception as e:
output_file = "output_data.csv"
data_to_write = [
try:
csv_writer = csv.writer(file)
csv_writer.writerows(data_to_write)
print(f"Data written to '{output_file}' successfully.")
except Exception as e:
INPUT
OUTPUT
FILE SAVED
Write a program to create a library in python and import it in a program.
return a + b
return a - b
return a * b
if b != 0:
return a / b
else:
import mymath
def main():
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:
except FileNotFoundError:
input_file = 'cspracticle.txt'
output_file = 'output_1.txt'
try:
lines = file.readlines()
file.write(line)
except FileNotFoundError:
import pickle
students = [
pickle.dump(students, file)
found = False
students = pickle.load(file)
found = True
break
if not found:
import pickle
# Create and write a binary file with roll number, name, and marks
students = [
pickle.dump(students, file)
updated = False
students = pickle.load(file)
student['Marks'] = new_marks
updated = True
if updated:
else:
import random
dice_roll = random.randint(1, 6)
import csv
csv_file = 'user_data.csv'
user_data = [
['user1', 'pass123'],
['user2', 'password456'],
['user3', 'qwerty789']
writer = csv.writer(file)
writer.writerows(user_data)
found = False
reader = csv.reader(file)
if row[0] == user_id:
found = True
break
if not found:
import mysql.connector
try:
connection = mysql.connector.connect(
if connection.is_connected():
cursor = connection.cursor()
except Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
Roll_No Integer
S_Name varchar(20)
S_class char(4)
S_Marks Integer
import mysql.connector
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("""
S_Name VARCHAR(20),
S_class CHAR(4),
S_Marks INT
""")
insert_query = """
"""
record = (1, 'John Doe', 'XII', 85)
cursor.execute(insert_query, record)
connection.commit()
except Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
import mysql.connector
try:
connection = mysql.connector.connect(
if connection.is_connected():
cursor = connection.cursor()
records = cursor.fetchall()
print(record)
except Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
import mysql.connector
try:
connection = mysql.connector.connect(
if connection.is_connected():
cursor = connection.cursor()
records = cursor.fetchall()
print(record)
except Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()