Solutions Python week 1

Author

Janpieter van der Pol

Exercices Part 2:

1. Create a 4x4 matrix filled with zeros

import numpy as np  # we need numpy for matrices

# Create a 4x4 matrix filled with zeros
matrix = np.zeros((4, 4))

print(matrix)
print(type(matrix))

2. Variable Assignment

my_number = 10
print(my_number)

# Assign a new value (20) to the same variable
my_number = 20
print(my_number)

3 Matrix Operations

3.1

# Add 5 to each element in the matrix
matrix_plus_5 = matrix + 5

print(matrix_plus_5)

3.2

# Matrix multiplication: matrix_plus_5 times matrix_plus_5
matrix_squared = matrix_plus_5 @ matrix_plus_5

print(matrix_squared)

Exercises part 3:

1. Check numeric values

1.1 Assign numeric values to two variables

# Assign numeric values
a = 10
b = 3.5

print(type(text1))
print(type(text2))

1.2 Assign numeric values to two variables

# Assign numeric values
a = "plop"
b = 3.5
a * b
TypeError: can't multiply sequence by non-int of type 'float'

A TypeError means that there is problem with the type of the variables you are using!

1.3

# Start with a number
number_value = 42
print(number_value)
print(type(number_value))  # should be int

# Transform the number into text (string)
text_value = str(number_value)

print(text_value)
print(type(text_value))    # should be str

# Check if number_value is an integer
print(isinstance(number_value, int))   # Expected: True

# Check if text_value is a string
print(isinstance(text_value, str))     # Expected: True

Exercises part 4

4.1

# Create two variables with different values
x = 5
y = 10

# Check if x is not equal to y
result = (x != y)

print(result)

4.2

# Create two variables with any numbers
a = 3
b = 7

# Check if a is equal to b
result = (a == b)

print(result)

4.3

# Set temperature and humidity
temperature = 25   # greater than 20
humidity = 40      # less than 50

# Check both conditions using 'and'
result = (temperature > 20) and (humidity < 50)

print(result)

Exercises part 5

5.1

```python
import random

# Generate a random number between 4 and 87 (can be decimal)
number = random.uniform(4, 87)
print("The generated number is " + str(number))

# Generate a random integer between 1 and 70
integer_number = random.randint(1, 70)
print("The generated integer is " + str(integer_number))

5.2

# Create two variables
a = 8
b = 3

# Calculate sum, difference, and product
sum_ab = a + b
difference_ab = a - b
product_ab = a * b

# Print the results in sentences
print("The sum of a and b is " + str(sum_ab))
print("The difference of a and b is " + str(difference_ab))
print("The product of a and b is " + str(product_ab))

5.3

# Create two numbers
x = 10
y = 7

# Check if x is greater than y
comparison_result = (x > y)

# Print the result in a sentence
print("It is " + str(comparison_result) + " that x is greater than y")