0% found this document useful (0 votes)
11 views

Practice Tasks

Uploaded by

david johnson
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)
11 views

Practice Tasks

Uploaded by

david johnson
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/ 8

Practice Tasks

July 22, 2024

0.1 1 - Control Structures


0.1.1 Task 1: Understanding Conditionals
Objective: Familiarize yourself with if, elif, and else statements.
Instructions: 1. Write a Python function named check_age that takes an integer input repre-
senting age. 2. If the age is less than 18, print “Minor”. 3. If the age is between 18 and 64, print
“Adult”. 4. If the age is 65 or older, print “Senior”.

[1]: def check_age(age):


if age < 18:
print("Minor")
elif 18 <= age < 65:
print("Adult")
else:
print("Senior")

# Example usage
check_age(15) # Output: Minor
check_age(30) # Output: Adult
check_age(70) # Output: Senior

Minor
Adult
Senior

0.1.2 Task 2: Mastering for Loops


Objective: Gain proficiency in iterating over sequences.
Instructions: 1. Create a function called sum_even_numbers that takes a list of integers. 2. Use
a for loop to iterate through the list and sum only the even numbers. 3. Return the sum of the
even numbers.

[2]: def sum_even_numbers(numbers):


total = 0
for number in numbers:
if number % 2 == 0:
total += number
return total

1
# Example usage
print(sum_even_numbers([1, 2, 3, 4, 5, 6])) # Output: 12

12

0.1.3 Task 3: Utilizing while Loops


Objective: Understand the functionality of while loops.
Instructions: 1. Write a function named countdown that takes an integer input n. 2. Use a
while loop to print numbers from n down to 1. 3. After the loop ends, print “Liftoff!”.

[3]: def countdown(n):


while n > 0:
print(n)
n -= 1
print("Liftoff!")

# Example usage
countdown(5)

5
4
3
2
1
Liftoff!

0.1.4 Task 4: Combining Loops and Conditionals


Objective: Practice using loops and conditionals together.
Instructions: 1. Create a function called fizz_buzz that takes an integer n. 2. Use a for loop
to iterate from 1 to n. 3. For multiples of 3, print “Fizz” instead of the number. 4. For multiples
of 5, print “Buzz” instead of the number. 5. For multiples of both 3 and 5, print “FizzBuzz”.

[4]: def fizz_buzz(n):


for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)

# Example usage
fizz_buzz(15)

2
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

0.1.5 Task 5: Understanding Functions and Recursion


Objective: Learn how to write recursive functions.
Instructions: 1. Implement a function named factorial that takes a non-negative integer n. 2.
Use recursion to calculate the factorial of n. 3. Return the factorial value.

[5]: def factorial(n):


if n == 0:
return 1
else:
return n * factorial(n - 1)

# Example usage
print(factorial(5)) # Output: 120

120

0.2 2- Data types


0.2.1 Task 1: Manipulating Strings
Objective: Learn basic string operations.
Instructions: 1. Write a function named string_manipulation that takes a string input. 2.
Perform the following operations on the string: - Convert it to uppercase. - Replace spaces with
underscores. - Count the number of vowels (a, e, i, o, u) in the string. 3. Return the modified
string and the count of vowels as a tuple.

[6]: def string_manipulation(s):


s_upper = s.upper()
s_replaced = s_upper.replace(" ", "_")
vowels = "AEIOU"
vowel_count = sum(1 for char in s_replaced if char in vowels)

3
return s_replaced, vowel_count

# Example usage
print(string_manipulation("Hello World")) # Output: ('HELLO_WORLD', 3)

('HELLO_WORLD', 3)

0.2.2 Task 2: Working with Lists


Objective: Understand list operations and manipulations.
Instructions: 1. Create a function called list_operations that takes a list of integers. 2.
Perform the following operations: - Append the number 42 to the list. - Remove the first occurrence
of the number 2 (if it exists). - Sort the list in ascending order. 3. Return the modified list.

[7]: def list_operations(lst):


lst.append(42)
if 2 in lst:
lst.remove(2)
lst.sort()
return lst

# Example usage
print(list_operations([4, 2, 3, 1, 5])) # Output: [1, 3, 4, 5, 42]

[1, 3, 4, 5, 42]

0.2.3 Task 3: Understanding Tuples


Objective: Learn how to work with immutable data types.
Instructions: 1. Write a function named tuple_operations that takes two tuples. 2. Perform
the following operations: - Concatenate the two tuples. - Find the maximum and minimum values
in the concatenated tuple. 3. Return the concatenated tuple, maximum value, and minimum value
as a tuple.

[8]: def tuple_operations(t1, t2):


concatenated = t1 + t2
max_value = max(concatenated)
min_value = min(concatenated)
return concatenated, max_value, min_value

# Example usage
print(tuple_operations((1, 2, 3), (4, 5, 6))) # Output: ((1, 2, 3, 4, 5, 6),␣
↪6, 1)

((1, 2, 3, 4, 5, 6), 6, 1)

0.2.4 Task 4: Exploring Dictionaries


Objective: Master the basics of dictionaries.

4
Instructions: 1. Implement a function named dictionary_operations that takes a dictionary
and a key-value pair. 2. Perform the following operations: - Add the key-value pair to the dictionary.
- If the key already exists, update its value. - Remove a key called “remove_me” if it exists. 3.
Return the modified dictionary.

[9]: def dictionary_operations(d, key, value):


d[key] = value
if "remove_me" in d:
del d["remove_me"]
return d

# Example usage
print(dictionary_operations({"a": 1, "b": 2}, "c", 3)) # Output: {'a': 1, 'b':␣
↪2, 'c': 3}

print(dictionary_operations({"a": 1, "remove_me": 99}, "a", 10)) # Output:␣


↪{'a': 10}

{'a': 1, 'b': 2, 'c': 3}


{'a': 10}

0.2.5 Task 5: Utilizing Sets


Objective: Understand the use and operations of sets.
Instructions: 1. Write a function named set_operations that takes two sets. 2. Perform the
following operations: - Find the union of the two sets. - Find the intersection of the two sets. -
Find the difference between the first set and the second set. 3. Return the union, intersection, and
difference as a tuple.

[10]: def set_operations(set1, set2):


union_set = set1.union(set2)
intersection_set = set1.intersection(set2)
difference_set = set1.difference(set2)
return union_set, intersection_set, difference_set

# Example usage
print(set_operations({1, 2, 3}, {3, 4, 5})) # Output: ({1, 2, 3, 4, 5}, {3},␣
↪{1, 2})

({1, 2, 3, 4, 5}, {3}, {1, 2})

0.3 3 - Combined
0.3.1 Task 1: Grade Calculator
Objective: Use conditionals, lists, and functions to calculate grades.
Instructions: 1. Write a function named calculate_grade that takes a list of numerical scores.
2. Calculate the average score. 3. Use conditionals to assign a letter grade based on the average
score: - 90-100: “A” - 80-89: “B” - 70-79: “C” - 60-69: “D” - Below 60: “F” 4. Return the letter
grade.

5
[11]: def calculate_grade(scores):
average = sum(scores) / len(scores)
if average >= 90:
return "A"
elif average >= 80:
return "B"
elif average >= 70:
return "C"
elif average >= 60:
return "D"
else:
return "F"

# Example usage
print(calculate_grade([85, 90, 78, 92, 88])) # Output: "B"

0.3.2 Task 2: Student Records


Objective: Use dictionaries, loops, and functions to manage student records.
Instructions: 1. Write a function named add_student that takes a dictionary of student records,
a student name, and a list of scores. 2. Add the student and their scores to the dictionary. 3. Write
another function named average_scores that takes the dictionary and returns a new dictionary
with student names and their average scores.

[12]: def add_student(records, name, scores):


records[name] = scores

def average_scores(records):
averages = {}
for student, scores in records.items():
averages[student] = sum(scores) / len(scores)
return averages

# Example usage
students = {}
add_student(students, "Alice", [90, 85, 88])
add_student(students, "Bob", [70, 75, 80])
print(average_scores(students)) # Output: {'Alice': 87.66666666666667, 'Bob':␣
↪75.0}

{'Alice': 87.66666666666667, 'Bob': 75.0}

0.3.3 Task 3: Word Frequency Counter


Objective: Use strings, dictionaries, and loops to count word frequency.
Instructions: 1. Write a function named word_frequency that takes a string input. 2. Convert

6
the string to lowercase and split it into words. 3. Use a dictionary to count the frequency of each
word. 4. Return the dictionary with word frequencies.

[13]: def word_frequency(text):


words = text.lower().split()
frequency = {}
for word in words:
if word in frequency:
frequency[word] += 1
else:
frequency[word] = 1
return frequency

# Example usage
print(word_frequency("This is a test. This test is only a test.")) # Output:␣
↪{'this': 2, 'is': 2, 'a': 2, 'test.': 2, 'only': 1}

{'this': 2, 'is': 2, 'a': 2, 'test.': 2, 'test': 1, 'only': 1}

0.3.4 Task 4: Shopping Cart


Objective: Use lists, dictionaries, and functions to manage a shopping cart.
Instructions: 1. Write a function named add_to_cart that takes a dictionary representing a cart,
an item name, and its price. 2. Add the item and its price to the cart dictionary. 3. Write another
function named calculate_total that takes the cart dictionary and returns the total price of all
items.

[14]: def add_to_cart(cart, item, price):


if item in cart:
cart[item] += price
else:
cart[item] = price

def calculate_total(cart):
total = sum(cart.values())
return total

# Example usage
cart = {}
add_to_cart(cart, "apple", 1.5)
add_to_cart(cart, "banana", 2.0)
add_to_cart(cart, "apple", 1.5)
print(calculate_total(cart)) # Output: 5.0

5.0

0.3.5 Task 5: Library System


Objective: Use tuples, sets, and functions to manage a library system.

7
Instructions: 1. Write a function named add_book that takes a set representing a library collection
and a tuple representing a book (title, author). 2. Add the book to the collection. 3. Write another
function named find_books_by_author that takes the collection and an author’s name, and returns
a list of books by that author.

[15]: def add_book(collection, book):


collection.add(book)

def find_books_by_author(collection, author):


books_by_author = [book for book in collection if book[1] == author]
return books_by_author

# Example usage
library = set()
add_book(library, ("1984", "George Orwell"))
add_book(library, ("Animal Farm", "George Orwell"))
add_book(library, ("Brave New World", "Aldous Huxley"))
print(find_books_by_author(library, "George Orwell")) # Output: [('1984',␣
↪'George Orwell'), ('Animal Farm', 'George Orwell')]

[('1984', 'George Orwell'), ('Animal Farm', 'George Orwell')]

You might also like