2. Operators#

Solutions to exercises#

Exercise 2.1.#

If a specific hotel charges €90 per night, how much do guests need to pay if they want to book a room for three nights?

tariff = 90
total_costs = 3*90
print(total_costs)

Exercise 2.2.#

Try to debug the code in the cell below. Why does Python report an error? What can we do to perform the calculation?

## The first operand was a string, while the second operand is an integer

print( 149+1 )
150

Exercise 2.3.#

Declare three numerical variables with arbitrary values. What is the average of these three values?

a = 7
b = 6
c = 9

average = ( a + b + c ) / 3
print(average)
7.333333333333333

Exercise 2.4.#

Write code that calculates and prints the number of seconds in seven days. Try to print the result as a sentence, e.g., “Seven days last X seconds.” where X is the result of the calculation.

seconds_in_minute = 60 
minutes_in_hour = 60 
hours_in_day = 24

seconds_in_day = seconds_in_minute * minutes_in_hour * hours_in_day

print( 'Seven days last ' + str( 7 * seconds_in_day ) + ' seconds.' )

Exercise 2.5.#

The variables a, b and c in the cell below have all been assigned value 0. Reassign values to these variables in such as way that the four boolean expressions that follow are ALL evaluated as True.

## You need to make sure that a is higher than b, 
# and that c is lower than and not equal to a

a = 5
b = 7
c = 3

print( a < b )
print( b > c )
print( c < a and b > a )
print( b == c or b >= a )
True
True
True
True

Exercise 2.6.#

Given an exchange rate of 1.2408 (euros to American dollars), how many dollars can you buy for 150 euros? Use the in-built round() function to ensure that the floating point number that results from the calculation is shown as an actual amount, indicating the number of cents. The first parameter of round() is the number to be rounded, and the second number is the number of digits beyond the decimal point.

exchangeRate = 1.2408

euros = 150
dollars = exchangeRate * euros
print(f'{ euros } euros are worth { round(dollars, 2) } dollars.')

Exercise 2.7.#

Debug the code below. The code does not contain a syntax error but a semantic error. Do you understand what happens in the code as given?

nr_weeks = "4"
print( f"Number of days in 4 weeks: {7*4}" )
# Multiplying a string by a number repeats the string that number of times
# Remove the quotes to make the value a true number
nr_weeks = 4
print( f"Number of days in 4 weeks: {7*4}" )