[go: up one dir, main page]

0% found this document useful (0 votes)
25 views14 pages

CTPS-EndSem-QuestionBank - Student

The document contains a comprehensive question bank for a CTPS end exam, covering various programming concepts in Python. It includes tasks related to age categorization, greeting users based on time, password strength evaluation, triangle classification, loops, list comprehensions, tuples, sets, dictionaries, string manipulation, command line arguments, and functions. Each section provides specific programming challenges with example inputs and expected outputs.

Uploaded by

jayanth9b.vhs
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)
25 views14 pages

CTPS-EndSem-QuestionBank - Student

The document contains a comprehensive question bank for a CTPS end exam, covering various programming concepts in Python. It includes tasks related to age categorization, greeting users based on time, password strength evaluation, triangle classification, loops, list comprehensions, tuples, sets, dictionaries, string manipulation, command line arguments, and functions. Each section provides specific programming challenges with example inputs and expected outputs.

Uploaded by

jayanth9b.vhs
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/ 14

CTPS END EXAM QUESTION BANK

Conditions:

1. Write a program that takes a person's age and categorizes them into different age
groups:
 Child: 0 – 12
 Teen: 13 – 19
 Adult: 20 – 64
 Senior: 65 and above
Example:
Input: 32
Output: Adult
2. Write a program that greets the user based on the current time:
 Morning (5 AM to 11 AM): "Good morning!"
 Afternoon (12 PM to 5 PM): "Good afternoon!"
 Evening (6 PM to 9 PM): "Good evening!"
 Night (10 PM to 4 AM): "Good night!"
Example:
Input: 10:45 (10:45 AM)
Output: Good morning!
3. Write a program that checks the strength of a password based on its length and
character variety:
 Weak: Less than 6 characters
 Medium: 6 to 10 characters, no special characters
 Strong: More than 10 characters and at least one special character.
Example:
Input: "StrongPass2021!"
Output: Strong
4. Write a program that takes three side lengths as input and classifies the triangle as:
 Equilateral: All sides equal
 Isosceles: Two sides equal
 Scalene: All sides different
Example:
Input: 5, 5, 8
Output: Isosceles
Loops:

1. Create a Python program that asks the user for a number and then finds and displays all
multiples of that number within the range from 1 to 100. Use a loop to print out each
multiple.
2. Write a Python program to print a right-angled triangle pattern using alternating 1s and 0s.
For instance, if n = 5, the output should display rows alternating between 1 and 0.

3. Convert the following while loop into a for loop:


i = 99
while i >= 9:
print(i)
i -= 9
4. Write a Python program to print Floyd's Triangle up to n rows, where the numbers
increment sequentially across each row. For example, if n = 5, the output should look like:

5. Develop a program that simulates a shopping cart where users can input item names and
prices. The program should calculate the total cost of all items in the cart. The loop should
continue until the user types "done", at which point the program should print the total cost
and list of items.
6. Convert the following while loop into a for loop:
i=0
while i < 50:
if i % 2 == 0:
print(i, "is even")
else:
print(i, "is odd")
i += 1
7. Write a Python program that prints a reverse pyramid pattern of numbers. For example, if n
= 5, the output should look like:

8. Design a program that asks the user for an integer between 1 and 100. The program should
allow three attempts to input a valid number and print a success message if valid. If the user
fails to enter a valid number in three tries, print a failure message.
9. Convert the following while loop into a for loop:
list1 = [11, 22, 33, 44, 55]
i=0
while i < len(list1):
if list1[i] == 4:
break
print(list1[i])
i += 1
10. Create a Python program to print a right-aligned pyramid pattern of numbers, where the
base has n numbers. For example, if n = 5, the output should look like:
11. Write a Python program that takes a series of positive integers from the user. Use a loop to
calculate the cumulative product of these numbers. The loop should stop if a negative
number is entered, and the program should print the cumulative product up to that point.
12. Convert the following for loop into a while loop:
for i in range(1, 200):
if i % 5 == 0:
print(f"{i} is divisible by 5")
13. Predict the output of the following code snippet:
string = "hello klu"
vowels = "aeiou"
result = "".join([char.upper() if char in vowels else char for char in string])
print(result)

Lists:

1. Create a Python list comprehension that modifies a list values = [12, 25, 34, 47, 56] by
replacing all even numbers with 0 and all odd numbers with 1. What will be the output?
2. Construct a Python list comprehension that replaces negative values in a list with 0,
while keeping positive numbers unchanged. Given the input [-8, 3, -14, 5], what will be
the output?
3. Write a Python list comprehension to generate a new list containing the squares of the
integers in the list numbers = [15, 25, 35, 45]. What is the expected output?
4. Develop a Python list comprehension that returns a list containing the number of
characters in each string in a list. Given the list ['apple', 'banana', 'cherry'], what will be
the output?
5. Write a Python program that identifies groups of anagrams from the following list of
words: ["listen", "silent", "enlist", "rat", "tar", "art", "top", "pot", "opt"]. What will be the
output when the program groups the anagrams?
Tuples:

1. How can you create a tuple with a single item in Python? What occurs if you create a
tuple with just a comma?

2. Discuss the differences between tuples and lists in Python. How can you transform a list
into a tuple and vice versa?

3. Suppose you are in charge of managing work shifts for a company. You are given a tuple
containing the names of all employees and a set of those currently on duty. Your
program should:
 Find employees not on duty and store their names in a new tuple.
 Calculate the total number of employees and the number of employees on duty.
 Display the percentage of employees currently on duty.
Example Input:
employees = ("Sarah", "James", "Tom", "Nora", "Mike")
on_duty = {"James", "Mike"}
Expected Output:
Not on duty: ('Sarah', 'Tom', 'Nora')
Total number of employees: 5
Number of employees on duty: 2
Percentage of employees on duty: 40.0%
4. You need to build a simple program to track social media engagement. Given a tuple of
user names and a set of followers, your program should:

 Identify users from the tuple who are not following anyone (i.e., not present in the
followers set).
 Create and return a new set of unique followers.
 Count and display how many followers each user has, assuming each user follows
everyone in the tuple.
Example Input:
users = ("Emma", "Lucas", "Sophia")
followers = {"Lucas", "Sophia"}
Expected Output:
Not following anyone: ('Emma',)
Unique followers: {'Lucas', 'Sophia'}
Number of followers per user: {Emma: 0, Lucas: 2, Sophia: 2}
5. As a music playlist manager, you are given a tuple of song titles and a set of songs
already added to the playlist. Your program should:
 Identify which songs from the tuple are not in the playlist and return them in a new
tuple.
 Create a sorted list of the songs in the playlist.
 Count and display the total number of unique songs in the playlist.
Example Input:
song_list = ("Song X", "Song Y", "Song Z", "Song W", "Song V")
playlist = {"Song X", "Song W", "Song V"}
Expected Output:
Not in playlist: ('Song Y', 'Song Z')
Sorted playlist: ['Song W', 'Song V', 'Song X']
Total unique songs in playlist: 3

Sets:

1. Create a Python program that finds the symmetric difference between two sets
(elements that exist in either set, but not in both). How can this be accomplished using
set operations?
2. Given two lists of numbers, use Python sets to find:

 The common numbers (intersection),


 The numbers present only in the first list,
 The numbers present only in the second list,
 A sorted list containing all unique numbers from both lists combined.
Input:
list_a = [10, 20, 30, 40, 50]
list_b = [40, 50, 60, 70, 80]
Expected Output:
Common numbers: {40, 50}
Unique to list_a: {10, 20, 30}
Unique to list_b: {80, 70, 60}
Sorted combined unique numbers: [10, 20, 30, 40, 50, 60, 70, 80]
3. Given a list containing duplicate elements, create a set to remove duplicates and convert
it back to a list. Discuss the effect this has on the order of the elements, using a sample
input and output as an example.
Input:
example_list = [3, 5, 1, 3, 2, 5, 4]
Expected Output:
List after removing duplicates: [1, 2, 3, 4, 5] # The order may not be preserved

Dictionary:

1. Create a Python program that simulates a simple online store's shopping cart. The
program should prompt the user to add products to the cart by entering the product
name and its price. Use a dictionary to store product names as keys and their prices as
values. The user should be able to keep adding products until they type "exit". When the
user types "exit", the program should print all products in the cart with their respective
prices and display the total cost of the items.
Strings:

1. Create a Python script that removes all duplicate characters from a string.
Input: input_string = "programming"
Expected Output: "progamin"
2. Implement a Python program that compresses a string by representing consecutive
duplicate characters as the character followed by the number of occurrences. If the
compressed string is not shorter than the original, return the original string.
Input: input_string = "aaabbcccc"
Expected Output: "a3b2c4"
3. Write a Python program to concatenate two given strings, separated by a space, and
swap the first two characters of each string.
Input: 'hello', 'world'
Expected Output: 'wollo herld'
4. Design a program that converts a string to alternating case (starting with uppercase) but
ignores punctuation and spaces.
Input: "hello, world!"
Expected Output: "HeLlO, wOrLd!"
5. Write a program that takes multiple strings and finds which string has the maximum and
minimum length. If there are multiple strings with the same length, return all of them.
Input: ["tiny", "small", "huge", "large"]
Expected Output:
Maximum length: ["large", ”small”]
Minimum length: ["tiny", ”huge”]
6. How would you reverse the words in a given string without reversing the characters
within each word using a Python script?
Input: "Hello from the other side"
Expected Output: "side other the from Hello"
7. Create a Python program to add 'ing' at the end of a given string (length should be at
least 3). If the string already ends with 'ing', add 'ly' instead. If the string length is less
than 3, leave it unchanged.
Input: 'play'
Expected Output: 'playing'
Input: 'singing'
Expected Output: 'singingly'
8. Write a program that takes multiple strings, concatenates them into a single string, and
returns a sorted string of unique characters.
Input: ["orange", "apple", "banana"]
Expected Output: "aabeglnopr"
9. What will be the output of the following code?
text = "I love programming in Python"
substring = "love"
print(text.count(substring, 5))
10. Write a Python program to find the first appearance of the substrings 'not' and 'poor' in
a given string, and replace the entire substring from 'not' to 'poor' with 'good'.
Input String: 'The movie is not that poor quality'
Expected Output: 'The movie is good quality'
11. Create a Python program that counts the number of "triplets" — sequences of three
identical consecutive characters in a string.
Input: "bbbbaaaacccbbb"
Expected Output: 4 (for "bbb", "aaa", "ccc", "bbb")
12. Write a Python program that counts the frequency of each character across a list of
strings and returns a dictionary with characters as keys and their frequencies as values.
Input: ["book", "cat", "apple"]
Expected Output: {'b': 1, 'o': 2, 'k': 1, 'c': 1, 'a': 2, 't': 1, 'p': 1, 'l': 1, 'e': 1}
13. What will be the output of the following code?
str3 = "PYTHON"
print(str3[1:4], str3[:3], str3[3:], str3[0:-1], str3[:-1])
14. Guess the correct output of the following code snippet:
sentence = "Learning Python is exciting"
reversed_sentence = " ".join([word[::-1] for word in sentence.split()])
print(reversed_sentence)

Command line arguments:

1. Create a Python program that converts a temperature value from Celsius to Fahrenheit
or from Fahrenheit to Celsius based on a unit provided through command line
arguments.
Example Command:
python convert_temp.py 37 C
Expected Output:
37.0 C is 98.6 F
2. Write a Python program that determines if a number passed as a command line
argument is a prime number.
Example Command:
python check_prime.py 47
Expected Output:
47 is a prime number.
3. Develop a Python program that counts the number of vowels and consonants in a string
provided as a command line argument.
Example Command:
python count_chars.py "Python Programming"
Expected Output:
Vowels: 4, Consonants: 14
4. Write a Python program that finds the maximum number from a list of integers provided
as command line arguments.
Example Command:
python find_max.py 5 18 2 42 27
Expected Output:
Maximum number: 42

Functions:

1. Write a function that attempts to modify a character within a string by index (e.g., changing
"world" to "World"). Explain the result and discuss why Python strings do not allow in-place
modification. Provide a Python script to illustrate this behavior.
2. Create a function that accepts a variable number of arguments and returns their total sum.
What happens when the function is called with no arguments? Illustrate with an example.
3. Design a function named attendance_report that takes a dictionary where keys are
employee names and values are lists representing attendance (1 for present, 0 for absent).
The function should:

 Calculate and display the total number of days each employee was present.
 Print the names of employees with the highest attendance.
Example Input:
attendance_data = {
'Mark': [1, 1, 0, 1, 1],
'Sophie': [1, 0, 1, 1, 1],
'Luke': [0, 1, 1, 0, 1],
'Nina': [1, 1, 1, 1, 1]
}
Expected Output:
Mark: 4 days present
Sophie: 4 days present
Luke: 3 days present
Nina: 5 days present
Top Attendees: ['Nina']
4. Explain how Python functions are not traditionally overloaded based on the number of
arguments. How can you achieve similar behavior using default arguments or variable-length
arguments?
5. Create a function that contains a nested function within it. What happens when the inner
function is called? Can it access variables from the outer function? Illustrate this with a
Python code example.
6. Write a function named stock_summary that takes a dictionary as input, where keys are
product names and values are their quantities in stock.
The function should:
 Calculate and return the total quantity of all products.
 Print the product with the highest stock quantity.
Sample Input:
inventory = {
"Apples": 50,
"Oranges": 80,
"Bananas": 120,
"Grapes": 30,
"Peaches": 60
}
Expected Output:
Total quantity of products: 340
Top most stocked product:
Bananas: 120
7. Design a function named performance_report that takes a dictionary where keys are student
names and values are lists of grades.
The function should:
 Print each student’s average grade.
 Print the names of the students with the highest average grade.
Example Input:
student_grades = {
'Emma': [90, 95, 92],
'Lucas': [78, 84, 88],
'Mia': [85, 87, 91],
'Oliver': [88, 89, 86]
}
Expected Output:
Emma's Average: 92.33
Lucas's Average: 83.33
Mia's Average: 87.67
Oliver's Average: 87.67
Top Student: ['Emma']

Abstraction:

1. Create an abstract base class called Worker with abstract methods compute_salary() and
show_info(). Then, create two subclasses, HourlyWorker and FixedSalaryWorker, that
inherit from Worker. Each subclass should implement compute_salary() according to the
type of payment (hourly or fixed salary). Instantiate both HourlyWorker and
FixedSalaryWorker objects and call their methods to calculate and display their salary
details.

Inheritance:

1. Is it possible for a subclass in Python to inherit from multiple parent classes? What is this
feature called? Provide an example that demonstrates multiple inheritance and explains
its behavior.
2. When class Child inherits from class Parent, and an object of Child is created, which
methods and attributes are accessible to that object? Discuss with examples to clarify
how inheritance works.

Overriding:

1. Is it possible for a subclass in Python to override a method from its parent class without
using the super() function? Provide a justification for your answer with examples.
2. Create a base class Figure with a default method compute_area() that returns 0. Derive
two classes, Square and Sphere, from Figure. In Square, include attributes side_length
and override compute_area() to calculate the area of the square. In Sphere, add an
attribute radius and override compute_area() to calculate the surface area of the
sphere. Instantiate both Square and Sphere with sample dimensions and call
compute_area() to display their areas.
3. Design a base class Vehicle with attributes manufacturer and capacity, along with a
method show_details() to display this information. Create two subclasses, Car and Van,
derived from Vehicle. In Car, add an attribute number_of_doors, and in Van, add an
attribute cargo_volume. Override show_details() in both subclasses to display all
relevant details. Create instances of Car and Van and call show_details() to display the
information for each vehicle.
4. Develop a base class Creature with attributes type_of_creature and voice, and a method
make_voice() to print the creature's sound. Create subclasses Fish and Cat derived from
Creature. In Fish, add an attribute can_swim (a boolean) and override make_voice() to
append "Blub!" to the sound. In Cat, include an attribute color and override
make_voice() to add "Meow!" to the sound. Instantiate objects of Fish and Cat and call
make_voice() to showcase their unique voices.
5. What is the outcome if a subclass overrides a method but does not call the superclass
method using super()? Discuss the implications with an example.
6. Create a base class Appliance with attributes brand_name and model_name, and a
method power_on() that prints "Appliance is powered on". Derive two classes,
WashingMachine and Microwave, from Appliance. In WashingMachine, add an attribute
spin_speed, and override power_on() to print "Washing Machine is operational". In
Microwave, include an attribute power_level, and override power_on() to print
"Microwave is heating". Instantiate both WashingMachine and Microwave and call
power_on() to display their respective messages.

Overloading:

1. Create a class named Coordinate to represent a 2D mathematical vector. Implement


operator overloading for the addition operator (+) to enable the addition of two
Coordinate objects. Provide an example demonstrating how to combine two vectors.
Input:
c1 = Coordinate(2, 3)
c2 = Coordinate(4, 5)
Output:
c1: Coordinate(2, 3), c2: Coordinate(4, 5), c3: Coordinate(6, 8)
2. Design a class named Rational to represent fractions. Implement operator overloading
for the division operator (/) to allow dividing two Rational objects.
Example Input:
r1 = Rational(1, 2)
r2 = Rational(3, 4)
result = r1 / r2
Expected Output:
Result of 1/2 divided by 3/4 is 2/3
3. Develop a Location class to represent a point in 2D space. Implement operator
overloading for subtraction (-) to calculate the difference between two points.
Additionally, create a method to compute the distance between two points using the
overloaded subtraction operator.
Example Input:
l1 = Location(1, 2)
l2 = Location(4, 6)
Expected Output:
The distance between Location(1, 2) and Location(4, 6) is 5.00
4. Create a class named Individual with attributes full_name and years. Overload the
comparison operators (<, >, ==) to compare two Individual objects based on their years
(age). Provide Python code to display results of various comparisons.

Call by value vs Call by reference:


1. Imagine a Python function that accepts a catalog (dictionary) as an argument and
modifies it by adding a new item (key-value pair). Discuss how Python's argument-
passing mechanism affects the original catalog defined outside the function. Is this
behavior classified as call-by-value or call-by-reference? Provide an example to illustrate.
2. If a function is called with an inventory (list) as an argument and modifies it within the
function, what happens to the inventory outside the function? What is this concept
called, and why does it occur?
3. Create a function that updates a global counter variable. What happens to the value of
the counter variable outside the function after modification? Provide an explanation
with an appropriate example.
4. Design a function that processes a collection of integers and returns a fresh collection
containing the square of each integer. Explain why a new collection must be created
instead of altering the original one. Provide an implementation and discuss the
reasoning.
5. What distinguishes passing a collection (list) to a function from passing a single value
(integer) in terms of mutability? Demonstrate the difference with an example to clarify
how Python handles mutable and immutable data types.
6. Write a Python function that accepts a score (integer) and a leaderboard (list) as
arguments. Show how Python handles the passing of the score (immutable) and the
leaderboard (mutable) when modified within the function. Explain how this behaviour
illustrates Python's model of variable passing.

Recursion:

1. Create a Python recursive function to compute x y (i.e., x raised to the power of y).
Write a recursive function power(base, exp) that calculates the result of raising a base
number to an exponent.
2. Write a Python recursive function to calculate the factorial of an integer m.
Use the formula m!=m×(m−1)!, with 0!=1. Name the function factorial(num) to compute the
result.
3. What happens when a recursive function lacks a base case? Provide an example.
Explain the potential issue (infinite recursion and stack overflow) and illustrate it with a
function example like infinite_recursion().
4. Develop a Python recursive function to determine the k-th number in the Fibonacci
sequence. Each number in the sequence is the sum of the two preceding numbers. Write a
function named fibonacci(index) to compute the result.
5. Create a Python recursive function to calculate the sum of the digits of a positive integer q.
Name the function sum_digits(number) and implement it to recursively add the digits of the
given number.

Nested Classes:

1. Create a Shop class with a nested Item class. The Shop class should have attributes such
as shop_name and address. The Item class should include attributes like item_id,
item_name, cost, and stock. Implement the following methods: in the Item class, define
adjust_stock(amount) to modify the stock quantity and calculate_total_value() to
compute the total value of the item (cost × stock). In the Shop class, create
add_item(item) to add a new item to the inventory and show_inventory() to list all
available items. Finally, instantiate the Shop class, add multiple items, and demonstrate
updating stock levels and calculating total values.
2. Develop a Television class with a nested PowerSource class. The Television class should
include attributes like brand_name (e.g., "LG"), screen_size (e.g., "50 inches"), and an
instance of the PowerSource class. The PowerSource class should have attributes like
source_type (e.g., "AA" or "AAA") and charge_level (an integer from 0 to 100).
Implement the following methods: in the PowerSource class, define drain(percent) to
reduce the charge level by a specified percentage, ensuring it doesn’t fall below 0, and
get_charge_level() to retrieve the current charge level. In the Television class, add
check_power() to display the charge level and warn if it falls below 20%, and
operate_tv(usage_percent) to simulate using the TV, which decreases the charge level
by the specified percentage and checks the power status. Finally, create an instance of
the Television class, verify the initial charge level, and simulate usage at different
percentages to observe changes.
3. Design a CreditUnion class with a nested MemberAccount class. The CreditUnion class
should have attributes like union_name and address. The MemberAccount class should
have attributes such as account_id, member_name, and account_balance. Implement
the following methods: in the MemberAccount class, create add_funds(amount) to
increase the balance and remove_funds(amount) to decrease the balance, ensuring it
doesn’t drop below zero. In the CreditUnion class, implement
open_account(member_name, starting_balance) to create a new account and
view_account_details(account_id) to retrieve account information. Finally, instantiate
the CreditUnion class, open an account, and demonstrate depositing and withdrawing
funds.
4. Create an Academy class with a nested Learner class. The Academy class should have
attributes like academy_name and city. The Learner class should include attributes like
learner_id, full_name, and scores (a list of grades). Implement the following methods: in
the Learner class, add record_score(score) to append a grade to the learner’s record and
compute_average() to calculate the average score. In the Academy class, create
register_learner(learner_id, full_name) to enroll a new learner and display_learners() to
list all enrolled learners. Finally, create an instance of the Academy class, register
multiple learners, and demonstrate adding grades and computing averages.
Exception Handling:

1. Analyze the following code and determine which type of exception will be raised:
str = "Python"
print(int(str))
2. Analyze the following code and determine which type of exception will be raised:
str1 = 30
str2 = "hi"
print(str1 + str2)
3. Analyze the following code and determine which type of exception will be raised:
List1 = [10, 20, 30]
del list1
print(list1)
4. Analyze the following code and determine which type of exception will be raised:
Numbers_list = [11, 22, 33]
print(numbers_list[5])
5. Write a function divide_safely(num1, num2) that takes two numbers as input and
returns their division result. Implement exception handling to catch any errors that may
occur if num2 is zero, and print an informative message when division by zero is
attempted.
6. Write a function retrieve_value(my_dict, search_key) that attempts to get the value
associated with a given key in a dictionary. Use exception handling to catch a KeyError
and print a message if the key is not found.
7. Write a function access_element(my_list, position) that tries to return the element at
the specified position in a list. Use exception handling to catch an IndexError and print a
message if the position is out of range.
8. Write a function open_and_read_file(file_name) that opens and reads a file. If the file
does not exist, catch the exception and print a message indicating that the file is missing.
Use finally to ensure the file is closed if it is open.

Interfaces:

1. Design an interface StorageSystem with abstract methods store(data) and retrieve(). Create
two classes, CloudStorage and LocalStorage, that inherit from StorageSystem. Implement
the store() and retrieve() methods in each class to simulate storing and retrieving data from
the cloud and local storage, respectively. Create instances of CloudStorage and LocalStorage,
and demonstrate storing and retrieving data using both classes.
2. Discuss the differences between an abstract class and an interface in Python, focusing on
their design, purpose, and use cases, along with examples for clarity.
3. Define an interface PlaybackDevice with abstract methods start(), pause(), and stop(). Create
two classes, MusicPlayer and MoviePlayer, that inherit from PlaybackDevice. Implement the
start(), pause(), and stop() methods in each class to simulate playback functionality for music
and movies. Instantiate both MusicPlayer and MoviePlayer, and demonstrate starting,
pausing, and stopping media playback.
4. Create an interface TransactionProcessor with an abstract method
handle_transaction(amount). Develop two classes, BankCardProcessor and
DigitalWalletProcessor, that inherit from TransactionProcessor. Implement the
handle_transaction() method in each class to simulate processing transactions through a
bank card and a digital wallet. Instantiate BankCardProcessor and DigitalWalletProcessor,
and demonstrate transaction handling using both processors.

Files:

1) Create a Python function count_vowels_in_file(filename) to read lines from a text file (e.g.,
"data.txt"). The function should calculate and display the number of vowels in the file.
Example:
File content (data.txt):
Artificial Intelligence is transforming the world.
Sample Output:
Count of vowels in the file is: 16
2) Create a Python program to count the number of lines in a text file (e.g., "info.txt") and print
the contents of the file line by line.
Example:
File content (info.txt):
Learning Python is fun.
Practice makes perfect.
Keep coding!
Sample Output:
Total lines: 3
Learning Python is fun.
Practice makes perfect.
Keep coding!
3) Create a Python function to read lines from a text file (e.g., "article.txt") and find the number
of occurrences of a specified word (e.g., "AI").
Example:
File content (article.txt):
AI is revolutionizing industries. AI is also enhancing daily life.
People believe AI will shape the future in unimaginable ways.
Sample Output:
Occurrences of 'AI' in the file is: 3
4) Create a Python program to check if the files "source.txt" and "destination.txt" exist. If they
do, copy all contents from "source.txt" to "destination.txt" while skipping even-numbered
lines.
Example:
File content (source.txt):
This is example line 1
This is example line 2
This is example line 3
This is example line 4
This is example line 5
Output File (destination.txt):
This is example line 1
This is example line 3
This is example line 5
5) What is the difference between open("file1.txt", "w") and open("file1.txt", "a")?
6) What is the difference between file.read(10) and file.readline()?
7) Given the code below, will the file inputfile.txt be created if it doesn't exist?
with open("inputfile.txt", "a") as file:
file.write("Hello Wecome to KLU World")
8) What will print(content) output for the given code?
with open("input_file.txt", "w+") as file:
file.write("Hello KLU")
content = file.read()

Threads:

1. Write a Python program that creates two threads: The first thread, increment_thread,
increments a counter from 0 to 10. The second thread, decrement_thread, decrements a
counter from 10 to 0. Synchronize the threads so they alternate execution, ensuring the
steps are printed sequentially.
2. Write a Python program that creates two threads: The first thread, even_sum_thread,
calculates the sum of even numbers from 1 to 100. The second thread, odd_sum_thread,
calculates the sum of odd numbers from 1 to 100. Display both results after the threads have
completed their computations.
3. Write a Python program using threading to perform concurrent computations: Implement a
function compute_squares() to calculate and display the squares of numbers in a list.
Implement a function compute_cubes() to calculate and display the cubes of numbers in the
same list. Run these functions concurrently using threads and display their results.
4. Create a Python program with a shared list resource and two threads: The first thread,
append_first_half, appends numbers 1 to 5 to the list. The second thread,
append_second_half, appends numbers 6 to 10 to the same list. Use a threading lock to
manage access and print the final combined list after both threads have finished execution.

Packages:

1. Create a Python package named number_utilities containing two modules: prime_validation


and factorization. In prime_validation, define a function is_prime_number(n) to check if a
number is prime. In factorization, define a function find_prime_factors(n) to return a list of
prime factors of a given number. Write a program to use these functions to check whether a
number is prime and to find its prime factors.
2. Create a Python package named digit_operations with two modules: sum_module and
count_module. In sum_module, define a function calculate_digit_sum(num) to calculate the
sum of the digits of a number. In count_module, define a function count_digits(num) to
calculate the number of digits in a given number. Write a program to import the modules
from digit_operations and use the functions in these modules.
3. Develop a Python package named temperature_conversion with two modules:
celsius_converter and fahrenheit_converter. In celsius_converter, define a function
fahrenheit_to_celsius(f) to convert a Fahrenheit temperature to Celsius. In
fahrenheit_converter, define a function celsius_to_fahrenheit(c) to convert a Celsius
temperature to Fahrenheit. Write a program to use these functions to convert a
temperature between Fahrenheit and Celsius.
4. Create a Python package named shape_calculations with two modules: circle_utils and
rectangle_utils. In circle_utils, define a function compute_circle_area(radius) to calculate the
area of a circle given its radius. In rectangle_utils, define a function
compute_rectangle_area(length, width) to calculate the area of a rectangle given its length
and width. Write a program to import these functions and calculate the area of a circle and a
rectangle using sample dimensions.

You might also like