## Blog Detail

### Python Exercises to Check Your Programming Knowledge

• What is the output of the round() function?

```                ```market_share = 12.03298

rounded_market_share = round(market_share, 2)

print(rounded_market_share)``````
• Imagine you are developing a scheduling application that allows users to create events and manage their availability. You have two sets representing the available time slots for two different users: User A and User B. Each set contains the time slots as integers:

user_a_availability = {9, 10, 11, 12}
user_b_availability = {14, 15, 16, 17}

Now, you want to check if there are any overlapping time slots between User A and User B.

```                ```user_a_availability = {9, 10, 11, 12}
user_b_availability = {14, 15, 16, 17}

result = user_a_availability.''(user_b_availability)

print("Are all the time slots available?", result)``````
• Imagine you are building a task management application. You have a dictionary representing a user’s tasks, where the keys are task IDs and the values are the corresponding task descriptions.

Now, let’s say that the user has completed task ID 2 and you want to remove it from the tasks dictionary.

```                ```tasks = {
1: "Complete project proposal",
2: "Review meeting notes",
3: "Submit expense report",
}

• What is the output of this code?

```                ```try:
num = int("\$10")
print(num)
except ValueError:
print("An exception occurred. Invalid conversion to an integer!")``````
• Suppose you are developing a movie recommendation system. You have two sets containing the genres preferred by two different users: User A and User B. Each set represents the genres as strings:

user_a_genres = {“Action”, “Drama”, “Comedy”, “Adventure”}
user_b_genres = {“Comedy”, “Romance”, “Thriller”}

Now, you want to retrieve the combined set of genres liked by both User A and User B.

```                ```user_a_genres = {"Action", "Drama", "Comedy", "Adventure"}
user_b_genres = {"Comedy", "Romance", "Thriller"}

all_genres = user_a_genres.''(user_b_genres)

print(all_genres)``````
• What is the output of this code?

```                ```phone_number = '555-1234'
phone_number_length = len(phone_number)
print(phone_number_length)``````
• Complete the code based on this scenario:

In a classroom, the teacher needs to rank students based on their exam scores. By organizing the list of numerical scores in ascending order , the teacher can determine the top-performing students and reward their academic achievements.

```                ```# List of exam scores
scores = [90, 85, 95, 92, 88]

# Sorting the scores in ascending order
scores.''()

print(scores)``````
• Complete the code based on this scenario:

In a competitive online game, players strive to achieve high scores. By utilizing a method that arranges the numerical scores in descending order , the game platform highlights the top-ranking players, fostering a sense of accomplishment and encouraging healthy competition among gamers.

```                ```# List of player scores
scores = [100, 85, 92, 78, 95]

# Sorting the scores in descending order
scores.sort('')

print(scores)``````
• Retrieve the last item from the tuple by using its index number .

```                ```# Create a tuple
my_tuple = ("Apple", "Banana", "Orange", "Grapes", "Mango")

# Retrieve the last item from the tuple
last_item = my_tuple['']

# Print the last item
print("Last item:", last_item)``````
• Which statement describes a key difference between the following code snippets?

```                ```# Code Snippet 1
with open(file_name, "r") as file:

# Code Snippet 2
file= open(file_name, "r")
file.close()``````
• Rewrite the commented for loop by using list comprehension.

```                ```words = ["apple", "banana", "carrot", "durian"]

'''
word_lengths = []

for word in words:
word_lengths.append(len(word))
'''
word_lengths = ''

print(word_lengths)    # [5, 6, 6, 6]``````
• Imagine you are building a recommendation system for a movie streaming service. You have two sets representing the movie genres preferred by two different users: User A and User B. Each set contains the unique genre names:

user_a_genres = {“action”, “drama”, “thriller”}
user_b_genres = {“action”, “comedy”, “drama”, “romance”, “adventure”}

Now, you want to check if User A’s preferred movie genres are a subset of User B’s preferred movie genres, meaning that all the genres liked by User A are also present in User B’s preferences.

```                ```user_a_genres = {"action", "drama", "thriller"}
user_b_genres = {"action", "comedy", "drama", "romance", "adventure"}

is_subset = user_a_genres.''(user_b_genres)

print(is_subset)``````
• Imagine you are building a student management system for a school. You have a dictionary representing a student’s information, including their name, grade level, and GPA.

Now, let’s say that the student’s GPA has improved to 4.0, and you want to update the value of the ‘gpa’ key in the dictionary.

```                ```student_info = {
"name": "John Doe",
"gpa": 3.8
}

''

print(student_info)``````
• Retrieve John’s major.

```                ```students = [
("John", 20, "Computer Science"),
("Emily", 22, "Mathematics"),
("Michael", 21, "Physics"),
("Sarah", 19, "Biology")
]

john_major = students[0]['']

print(john_major)``````
• Let’s imagine you are building a quiz application, and you have a set of questions for a particular category. Initially, the set contains multiple questions. For instance:

questions = {“Question 1”, “Question 2”, “Question 3”, “Question 4”, “Question 5”}

Now, when a user starts the quiz, you want to randomly retrieve and remove a question from the set.

```                ```questions = {"Question 1", "Question 2", "Question 3", "Question 4", "Question 5"}

random_question = questions.''()

print("Random Question:", random_question)

print("Remained questions: ", questions)``````
• Imagine you are developing a ticketing system for an event. You have two sets representing the attendees who purchased tickets for two different ticket categories: Category A and Category B. Each set contains the attendee names:

category_a_attendees = {“John”, “Alice”, “Michael”, “Sarah”}
category_b_attendees = {“Alice”, “Sarah”, “David”, “Emily”}

Now, you want to identify the attendees who purchased tickets for Category A but not for Category B.

```                ```category_a_attendees = {"John", "Alice", "Michael", "Sarah"}
category_b_attendees = {"Alice", "Sarah", "David", "Emily"}

unique_attendees = category_a_attendees.''(category_b_attendees)

print(unique_attendees)``````
• Which statement correctly describes the required mode for replacing the content of a file?

• Display the most expensive item in the list.

```                ```item_prices = [10.00, 30.00, 20.90, 5.00, 75.00]

most_expensive_item = ''(item_prices)
print(most_expensive_item)``````
• Complete the code based on this scenario:

In a bustling kitchen, a chef is preparing a special dish. To ensure they have all the required ingredients, the chef utilizes a technique that verifies if a particular ingredient is present in the list of available ingredients. This helps maintain the recipe’s integrity and allows the chef to create a delicious and satisfying culinary masterpiece.

```                ```# List of available ingredients
available_ingredients = ['flour', 'sugar', 'eggs', 'butter', 'vanilla extract']

# Ingredient to check
ingredient = 'eggs'

# Checking if the ingredient is present
is_available = ingredient '' available_ingredients

# Displaying the result
if is_available:
print('The ingredient is available!')
else:
print('The ingredient is not available.')``````
• What does the condition of the if statement mean?

```                ```product_code = '100001'

if product_code.isdigit() and len(product_code) == 6:
print("Valid product code.")
else:
print("Invalid product code. Please enter a numeric value.")``````
• What is type casting in Python?

• Consider the following scenario:

You have a text file that contains multiple lines of data. You need to read all the lines from the file and process them.

Which method should you use to accomplish this task?

```                ```file_name = "example.txt"

with open(file_name, "r") as file:
lines = file.''()

for line in lines:
print(line)  # Process each line as needed``````
• Retrieve and print the count of items in the tuple.

```                ```# Create a tuple
my_tuple = ("Apple", "Banana", "Orange", "Grapes", "Mango")

# Get the length of the tuple
tuple_length = ''(my_tuple)

# Print the length of the tuple
print("Length of the tuple:", tuple_length)``````
• To backup a file, it must be available and have enough storage.
Complete the logic based on the criteria.

```                ```is_available = True
has_sufficient_storage = True

can_backup = is_available '' has_sufficient_storage

print(can_backup)``````
• What is the output of this code?

```                ```try:
x = str("123")
except:
print("An exception occurred: Invalid conversion to a string.")
else:
print(x)
``````
• Complete the code based on this scenario

Suppose we have a list of monthly website traffic data for a year, where each item represents the number of visits in a specific month. Now, we need to extract the website traffic data for the first quarter, which includes the months of January, February, and March.

```                ```# List of monthly website traffic data
traffic_data = [5000, 6000, 5500, 7000, 8000, 7500, 9000, 9500, 8500, 10000, 9500, 11000]

# Extract website traffic data for the first quarter (months 1-3)
first_quarter_traffic = traffic_data['']

# Print the website traffic data for the first quarter
print("Website traffic data for the first quarter:")
print(first_quarter_traffic)``````
• What is the output of this program?

```                ```# List of tasks
tasks = ["Update content", "Prepare report", "Call clients",
"Review strategy", "Finalize proposal"]

# Extract prioritized tasks starting from the fourth position

• In a customer relationship management system, you have a list of existing customers who made purchases.
Now, you want to update the list with new customers from a recent marketing campaign. The new customers are stored in another list. How would you extend the existing customer list with the new customers?

```                ```existing_customers = ['Sarah Thompson', 'Daniel Evans', 'Olivia Rodriguez']
new_customers = ['Sophia Lee', 'Matthew Turner']

existing_customers.''(new_customers)``````
• Cast the image_resolution from string to integer.

```                ```image_resolution = '72'

casted_image_resolution = ''(image_resolution)``````
• What is the output of this code?

```                ```a = 2
b = 3
c = 4

d = a + b * c / a - b

print(d)``````
• What is the index of comma?

```                ```sentence = "Hello, world!"

index = sentence.find(",")

print(index)``````
• What is the output of this code?

```                ```def calculate_shipping_cost(weight, destination):
if weight <= 0:
return "Invalid weight"

if destination == "domestic":
shipping_cost = 0.5 * weight
return f"Domestic shipping: \${shipping_cost}"

if destination == "international":
shipping_cost = 1.5 * weight
return f"International shipping: \${shipping_cost}"

return "Invalid destination"

weight = 2.5
destination = "international"
result = calculate_shipping_cost(weight, destination)

print(result)``````
• Use list comprehension to filter students with grade A.

```                ```students = [
{"name": "John", "age": 18, "grade": "A"},
{"name": "Emily", "age": 17, "grade": "B"},
{"name": "Michael", "age": 19, "grade": "A"},
{"name": "Sophia", "age": 18, "grade": "B"},
]

grade_a_students = [student for student in students if '' ]

• What is the output of this code?

```                ```try:
x = int("5.0")
except:
print("An exception occurred!")
else:
x = x * 2
print(x)
finally:
print("Execution completed!")``````
• In a ticket management system, you have a list of unresolved tickets.
A new ticket, 'Ticket 004', has been received. How would you add 'Ticket 004' to the end of the list of unresolved tickets?

```                ```unresolved_tickets = ['Ticket 001', 'Ticket 002', 'Ticket 003']
new_ticket = 'Ticket 004'

unresolved_tickets.''(new_ticket)``````
• Today is cheat day! Clear all the exercises from the list.

```                ```exercises = ["Push-ups", "Sit-ups", "Jumping jacks"]

exercises.''()``````
• In an inventory management system, you have a list of products representing the available inventory.
As customers make purchases, you need to remove the sold products from the list. Additionally, you want to keep track of the last sold product. How would you remove a specific product from the list and retrieve the last sold product?

```                ```# Create a list of products representing the available inventory
inventory = ['Product 1', 'Product 2', 'Product 3', 'Product 4']

# Remove and retrieve the sold product
sold_product = inventory.''(2)

print(sold_product)``````
• What will be printed in the console?

```                ```y = 8
z = 2

print(8 / 2)``````
• In an employee onboarding system, you need to create a list to store the names of newly hired employees.
Initially, the list is empty. As new employees join the company, their names will be added to the list. How would you create an empty list ?

```                ```# Create an empty list to store employee names
newly_hired_employees = ''

# Get the names of three newly hired employees
employee_name_1 = input("Enter the name of the first newly hired employee: ")
employee_name_2 = input("Enter the name of the second newly hired employee: ")
employee_name_3 = input("Enter the name of the third newly hired employee: ")

# Add the employee names to the list
newly_hired_employees.append(employee_name_1)
newly_hired_employees.append(employee_name_2)
newly_hired_employees.append(employee_name_3)

print(newly_hired_employees)``````
• ## Python Exercises for Comprehension

• If you've faced difficulties with these exercises, take a look at Comprehension Module on my Python course.

You can also share 'Python Comprehension' Exercises on your: