Data Types and Structures#

Exercise 1: Variables#

  1. Assign the value 42 to a variable named my_var and print it.

  2. Assign the string "Hello, World!" to a variable named greeting and print it.

  3. Create two variables, a and b, assign them values 10 and 20, and save their sum to a variable called c. Print their sum.

  4. Write a comment for (3) explaining what your “algorithm” does.

# 1
my_var = 42
print(my_var)

# 2
greeting = "Hello, World!"
print(greeting)

# 3: Calculate the sum of a and b and store it in c
a = 10
b = 20
c = a + b
print(c)
42
Hello, World!
30

Exercise 2: Types#

The Python built-in type() will return the type of the variable given to it.

  1. Create a variable x and assign it a float value. Check the type of x using the type() function.

  2. Create a variable y and assign it a string value. Print the type of y and its length using the len() function.

  3. Verify that a multiplication of two integers returns another int, while a division returns a float.

  4. Why do do you think that Python changes the result of a division into type float?

# 1
x = 3.14
print(type(x))

# 2
y = "Hello"
print(f"{y} has type: {type(y)} and length: {len(y)}")

# 3
a = 1
b = 2

c = a * b
print(type(c))

d = a / b
print(type(d))

# 4
# The multiplication of two integer number will always be an integer number
# The division of two integer numbers can often become a float (e.g.: 1 / 2) and thus Python will always return a float
<class 'float'>
Hello has type: <class 'str'> and length: 5
<class 'int'>
<class 'float'>

Exercise 3: Strings#

You previously learned about functions like .lower() or .replace() which allow you to modify strings. But what about counting? Lets for example take the word Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch, which is a town in Wales. Can you find a function that lets you count the number of times the combination of two subsequent L’s (e.g. “ll”) appear in that word? See if you can guess how the function could be called and used. Use the internet for help if necessary.

  1. Count the number of time two subsequent L’s occur in the town name. Save the result to a new variable and print its value.

  2. The correct answer should be 5. If your result is different, check the string to see where you might have missed something.

town = "Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch"

# 1. Counnt the number of "ll"
ll_count = town.count("ll")
print("The number of 'll' occurrences:", ll_count)

# 2. Correct the count
# The reason is tha that the first "L" is capitalized. If we first convert the town to lowercase, the count will be 5
town = town.lower()
ll_count = town.count("ll")
print("The correct number of 'll' occurrences:", ll_count)
The number of 'll' occurrences: 4
The correct number of 'll' occurrences: 5

Exercise 4: Booleans#

Some integer values are equivalent to Python Boolean values.

  1. Use the equality (==) operator to find the integer which is equivalent to True.

  2. Use the equality (==) operator to find the integer which is equivalent to False.

# Exercise 4

# 1. 1 is equal to True
print(1 == True)

# 2. 0 is equal to False
print(0 == False)
True
True

Exercise 5: Lists#

  1. Create a list named fruits containing "apple", "banana", and "cherry". Add "orange" to the list and print the result.

  2. Remove "banana" from the fruits list and print the updated list.

# 1. Create a list and add "orange" to it
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(f"List after adding 'orange': {fruits}")

# 2. Remove "banana" from the list
fruits.remove("banana")
print(f"List after removing 'banana': {fruits}")
List after adding 'orange': ['apple', 'banana', 'cherry', 'orange']
List after removing 'banana': ['apple', 'cherry', 'orange']

Exercise 6: More lists#

You previously learned about the .append() function for adding a new item to the end of a list. You can also add two lists together by using the plus (+) operator. Given the lists provided below, can you:

  1. Create a new list which combines list1 and list2?

  2. Create a new list that has the items [6, 5, 1, 2, 3] by only using indexing operations and functions associated with lists?

Hint: Lists come with more functions like .extend() or .reverse(). You can find a full list in the Python documentation.

list1 = [1, 2, 3]
list2 = [4, 5, 6]

# 1. Create a new list combining list1 and list2
combined_list = list1 + list2
print(f"Combined list: {combined_list}")

# 2. Create a new list with [6, 5, 1, 2, 3]
list2.reverse()
new_list = list2[:2]
new_list.extend(list1)
print(f"New list: {new_list}")
Combined list: [1, 2, 3, 4, 5, 6]
New list: [6, 5, 1, 2, 3]

Exercise 7: Indexing#

You previousy learned how to access specific elements of a list by enclosing an index in square brackets (first_item = my_list[0]). A useful feature in Python is that you can also start indexing from the back of a list by using negative numbers (last_item = my_list[-1]). Experiment with this for a bit and then answer/implement the following questions:

  1. What is the negative number index for the last item in the list?

  2. What is the negative number index for the first item in the list?

  3. Can you write code that would use a negative number to index the first item in the list, without advance knowledge of its length? Hint: A function introduced in the Strings section of the might be useful here.

my_list = ["Hello", 1, 3.14, True, 5, 1234, "Goodbye"]

# 1
print(my_list[-1]) # The negative index of the last element is -1

# 2
print(my_list[-7]) # It is -7 because the list has 7 elements

# 3
first_item = my_list[-len(my_list)]
print(first_item)
Goodbye
Hello
Hello

Exercise 8: Dictionaries#

Below you can see a dictionary containing the price of different fruits.

  1. Add another fruit to the dictionary. This fruit should have several different prices associated with it, organized as a list

  2. Access the second price in this list in a single line of code and save it to a variable called second_price

  3. Print the newly added fruit and its the second price like so: “The second price of <your_fruit> is <second_price> €”.

Hint: You can use the previously introduced f-strings for printing

fruit_prices = {
    "apple": 0.5,
    "banana": 0.2,
}

# 1. Add another fruit with a list of prices
fruit_prices["orange"] = [0.3, 0.4, 0.35]
print(fruit_prices)

# 2. Access the second price of "orange"
second_price = fruit_prices["orange"][1]

# 3. Print the result using an f-string
print(f"The second price of orange is {second_price} €")
{'apple': 0.5, 'banana': 0.2, 'orange': [0.3, 0.4, 0.35]}
The second price of orange is 0.4 €

Exercise 9: Conditionals#

Can you rewrite the code below by only using one if, one elif, and one else statement to improve readability?

points = 12

if points > 10:
    print("Points are more than 10.")
elif points == 10:
    print("Points are exactly 10.")
else:
    print("Points are less than 10.")
Points are more than 10.

Exercise 10: Loops#

You are provided with a list of integers called numbers. Your task is to:

  1. Write a for loop which calculate the sum of all items in the list. Print the result.

  2. Again count the sum of elements, but exclude the item at index 3.

  3. Write a for loop to count how many numbers in the list are even. Print the count.

Hints:

  • You might find using a counting variable useful for all three exercises.

  • You can use the enumerate() function and the != operator if you work with indices in a loop.

  • The modulo % operator will give you the remainder of a division. So the expression number % 2 == 0 will be True if number is even (there is no remainder), or else it will be False (there is a remainder).

numbers = [10, 15, 8, 23, 42, 4, 16, 9, 7, 30]

# 1. Sum of all elements
total_sum = 0

for num in numbers:
    total_sum += num

print(f"The sum of all elements is {total_sum}")

# 2. Exclude item at index 3 from summation
total_sum = 0

for i, num in enumerate(numbers):
    if i != 3:
        total_sum += num

print(f"The sum of all elements except the number at index 3 is {total_sum}")


# 3. Count even numbers
even_count = 0

for num in numbers:
    if num % 2 == 0:
        even_count += 1

print(f"The count of even numbers is {even_count}")
The sum of all elements is 164
The sum of all elements except the number at index 3 is 141
The count of even numbers is 6

Voluntary Exercise 1: Lists and dictionaries combined#

Create a list of dictionaries where each dictionary represents a student. The keys should be "name", "age", and "grades" (a list of three integers). Then write code that prints the name of the student with the highest average grade.

Hint: You might find it helpful to use a for loop (which we will be introduced in detail in the next session)

# List of dictionaries, each representing a student
students = [
    {"name": "John",  "age": 20, "grades": [1, 1, 3]},
    {"name": "Alice", "age": 22, "grades": [2, 3, 2]},
    {"name": "Bob",   "age": 21, "grades": [4, 1, 2]}
]

# Variable to keep track of the student with the highest average grade
highest_avg = 0
top_student = ""

# Loop through each student to calculate their average grade
for student in students:
    average_grade = sum(student["grades"]) / len(student["grades"])
    if average_grade > highest_avg:
        highest_avg = average_grade
        top_student = student["name"]

# Print the name of the student with the highest average grade
print(f"The student with the highest average grade is {top_student} with an average of {highest_avg}.")
The student with the highest average grade is Alice with an average of 2.3333333333333335.

Voluntary Exercise 2: Swapping values#

Can you swap the values of a and b without creating a temporary (thrird) variable?

a = 5
b = 10

# There are multiple ways to swap the values of two variables
# 1. You can use Python's tuple unpacking to swap the values
a, b = b, a
print(f"After swapping: a = {a}, b = {b}")

# 2. You can use clever mathematics to swap values
a = a + b
b = a - b
a = a - b
print(f"Swapping back:  a = {a},  b = {b}")

# However, most of the times it is better to use a simple and clear solution, rather than a clever one :)
After swapping: a = 10, b = 5
Swapping back:  a = 5,  b = 10

Voluntary Exercise 3: More loops#

Please use a loop to iterate through the list of numbers. For each number, determine if it is prime and print whether it is prime or not.

numbers = [2, 3, 4, 5, 10, 11, 15, 17, 18, 23, 29, 30]

# There are many ways to achieve this. One possible solution:
for num in numbers:
    if num > 1:
        is_prime = True
        for i in range(2, num):
            if num % i == 0:
                is_prime = False
                break
        if is_prime:
            print(f"{num} is prime.")
        else:
            print(f"{num} is not prime.")
    else:
        print(f"{num} is not prime.")
2 is prime.
3 is prime.
4 is not prime.
5 is prime.
10 is not prime.
11 is prime.
15 is not prime.
17 is prime.
18 is not prime.
23 is prime.
29 is prime.
30 is not prime.