0% found this document useful (0 votes)
41 views9 pages

Practical Ans C.S

Uploaded by

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

Practical Ans C.S

Uploaded by

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

QUES 1.

import random

def DiceThrow():
"""
Simulates a dice roll and returns a random number between 1 and 6.
"""
return random.randint(1, 6)

# Example usage:
result = DiceThrow()
print(f"The dice rolled: {result}")

QUES 2.
def ChangeNum(lst):
"""
Modifies the input list by doubling odd values and halving even values.
"""
for i in range(len(lst)):
if lst[i] % 2 == 0:
lst[i] //= 2
else:
lst[i] *= 2

# Given list
L1 = [5, 17, 22, 12, 13, 44, 6, 7]

# Modify the list


ChangeNum(L1)

print("Modified list:", L1)


QUES 3.
def ConvertStr(input_string):
"""
Replaces 'a' with '@' and 's' with '$' in the input string.
"""
converted_string = input_string.replace('a', '@').replace('s', '$')
return converted_string

# Example usage:
original_string = "apple and snakes"
converted_result = ConvertStr(original_string)
print("Converted string:", converted_result)

QUES 4.
def VowelCount(input_string):
"""
Counts the number of vowels, uppercase, and lowercase characters in the input
string.
"""
vowels = "aeiouAEIOU"
num_vowels = input_string.lower().count(vowels)
num_uppercase = sum(1 for char in input_string if char.isupper())
num_lowercase = sum(1 for char in input_string if char.islower())
return num_vowels, num_uppercase, num_lowercase

# Example usage:
user_input = input("Enter a string: ")
vowels, uppercase, lowercase = VowelCount(user_input)
print(f"Vowels: {vowels}, Uppercase: {uppercase}, Lowercase: {lowercase}")
QUES 5.
def CountMeHe(input_string):
"""
Counts the occurrences of the words 'He' and 'Me' in the input string.
"""
# Convert the input string to lowercase for case-insensitive matching
lower_string = input_string.lower()

# Split the string into words


words = lower_string.split()

# Count occurrences of 'he' and 'me'


count_he = words.count('he')
count_me = words.count('me')

return count_he, count_me

# Example usage:
user_input = input("Enter a sentence: ")
he_count, me_count = CountMeHe(user_input)
print(f"'He' occurs {he_count} times, and 'Me' occurs {me_count} times.")

QUES 6.
# Step 1: Create the "story.txt" file
with open("story.txt", "w") as file:
file.write("Early to Bed and early to Rise")

# Step 2: Count occurrences of the word "to"


word_to_count = "to"
with open("story.txt", "r") as file:
content = file.read()
occurrences = content.lower().count(word_to_count)

print(f"Occurrences of the word '{word_to_count}': {occurrences}")


QUES 7.
# Step 1: Create the "school.txt" file
with open("school.txt", "w") as file:
file.write("Welcome to School! This is the revised content.")

# Step 2: Take a backup to "schbkp.txt"


import shutil
shutil.copyfile("school.txt", "schbkp.txt")

# Step 3: Display the content of both files


with open("school.txt", "r") as file:
original_content = file.read()
print("Content of school.txt:")
print(original_content)

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


backup_content = file.read()
print("\nContent of schbkp.txt (backup):")
print(backup_content)

QUES 8.
# Step 1: Create the "Biodata.txt" file
with open("Biodata.txt", "w") as file:
file.write("Mango\nBanana\nApple\nPear\nMelon\nGrapes\nKiwi\n")

# Step 2: Remove lines starting with 'm' and create "biobkp.txt"


with open("Biodata.txt", "r") as infile, open("biobkp.txt", "w") as outfile:
for line in infile:
if not line.startswith("M"):
outfile.write(line)

# Step 3: Display the content of both files


with open("Biodata.txt", "r") as file:
print("Content of Biodata.txt:")
print(file.read())

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


print("\nContent of biobkp.txt:")
print(file.read())
QUES 9.
import pickle

# Create student data (you can modify this as needed)


students = ["Alice", "Bob", "Charlie", "David", "Eve"]

# Write data to the binary file


with open("student.rec", "wb") as file:
pickle.dump(students, file)

# Read data from the binary file


with open("student.rec", "rb") as file:
read_students = pickle.load(file)

# Print the names of students


print("Names of students:")
for student in read_students:
print(student)

QUES 10.
import pickle

def create_centre_file():
"""
Create a binary file "centre.lst" to store exam cities.
"""
exam_cities = []
while True:
city = input("Enter an exam city (or 'q' to quit): ")
if city.lower() == 'q':
break
exam_cities.append(city)

with open("centre.lst", "wb") as file:


pickle.dump(exam_cities, file)
print("Exam cities saved to centre.lst")

def search_exam_center():
"""
Search for an exam center based on user input.
"""
try:
with open("centre.lst", "rb") as file:
exam_cities = pickle.load(file)
search_city = input("Enter an exam city to search: ")
if search_city in exam_cities:
print(f"{search_city} is an exam center.")
else:
print(f"{search_city} is not found in the list of exam cities.")
except FileNotFoundError:
print("The centre.lst file does not exist. Please create it first.")

# Main menu
while True:
print("\n1. Create exam cities file")
print("2. Search for an exam center")
print("3. Quit")
choice = input("Enter your choice (1/2/3): ")

if choice == '1':
create_centre_file()
elif choice == '2':
search_exam_center()
elif choice == '3':
print("Exiting. Goodbye!")
break
else:
print("Invalid choice. Please select 1, 2, or 3.")
QUES 11.
import csv

def write_to_csv(filename, data):


"""
Writes data to a CSV file.
"""
with open(filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["ItemName", "Price"]) # Write header
writer.writerows(data)

def read_from_csv(filename):
"""
Reads data from a CSV file and displays all records.
"""
with open(filename, mode='r') as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
print(f"Item: {row[0]}, Price: {row[1]}")

# Example data (you can modify this)


item_data = [
["Apple", 1.99],
["Banana", 0.79],
["Orange", 2.49],
["Grapes", 3.99]
]

# Write data to "item.csv"


write_to_csv("item.csv", item_data)
print("Data written to item.csv successfully.")

# Read and display all records from "item.csv"


print("\nAll records in item.csv:")
read_from_csv("item.csv")
QUES 12.
import csv

def write_to_csv(filename, data):


"""
Writes data to a CSV file.
"""
with open(filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["ItemName", "Price"]) # Write header
writer.writerows(data)

def search_item_price(filename, item_name):


"""
Searches for the price of the given item name in the CSV file.
"""
try:
with open(filename, mode='r') as file:
reader = csv.DictReader(file)
for row in reader:
if row["ItemName"].lower() == item_name.lower():
return row["Price"]
return "Item not found in the CSV file."
except FileNotFoundError:
return "CSV file 'item.csv' does not exist."

# Example data (you can modify this)


item_data = [
["Apple", "1.99"],
["Banana", "0.79"],
["Orange", "2.49"],
["Grapes", "3.99"]
]

# Write data to "item.csv"


write_to_csv("item.csv", item_data)
print("Data written to item.csv successfully.")

# Ask user for item name


user_item = input("Enter an item name: ")

# Search for the price


result = search_item_price("item.csv", user_item)
print(result)
QUES 13.
import csv

def write_sports_data(filename, data):


"""
Writes sports-related data to a CSV file.
"""
with open(filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["SportsCode", "SportName", "NumPlayers", "Type"]) #
Write header
writer.writerows(data)

def read_sports_data(filename):
"""
Reads data from the CSV file and displays all records.
"""
try:
with open(filename, mode='r') as file:
reader = csv.DictReader(file)
for row in reader:
print(f"Code: {row['SportsCode']}, Name: {row['SportName']},
Players: {row['NumPlayers']}, Type: {row['Type']}")
except FileNotFoundError:
print(f"CSV file '{filename}' does not exist.")

# Example sports data (you can modify this)


sports_data = [
["S001", "Football", "11", "Outdoor"],
["S002", "Basketball", "5", "Indoor"],
["S003", "Tennis", "2", "Outdoor"]
]

# Write data to "sports.csv"


write_sports_data("sports.csv", sports_data)
print("Data written to sports.csv successfully.")

# Read and display all records from "sports.csv"


print("\nAll records in sports.csv:")
read_sports_data("sports.csv")

You might also like