Week 2 - Exercises

Exercise 1 - Implementing Euclid’s algorithm

In Week 0 we talked about Euclid’s ancient algorithm for finding the greatest common divisor of two numbers. By now we have covered everything you need to be able to write it in Python! Here it is again in visual format (refer to the presentation slides if the image is not visible).

Euclid’s algorithm

Implement the algorithm in the cell below. The final line should be a print statement that prints the highest common divisor of the numbers A and B.

Hint 1 - You can use the input statement to assign initial values to A and B

Hint 2 - while

[1]:
# Implement Euclid's algorithm here

Exercise 2 - Implement Euclid’s algorithm as a function

Now you have managed to implement Euclid’s algorithm, try doing it as a function. Instead of using the input statement to take input from the user, the numbers A and B should be passed as arguments to a function. You could call the function something like get_highest_common_divisor(A, B).

Don’t forget to include a docstring that provides a brief explanation of the function!

Hint - def

[2]:
# Define function here
[3]:
# Call function here

Exercise 3 - Fahrenheit to Celsius

Previously we used a script to convert Fahrenheit to Celsius. Here it is again.

"""Convert Fahrenheit to Celsius."""

# Ask user to enter a temperature in Fahrenheit
temp = float(input("Enter temperature in Fahrenheit: "))

# Convert to Celsius
celsius = (temp - 32) * (5 / 9)
celsius = round(celsius, 2)

print(f"{temp} degrees Fahrenheit is equal to {celsius} degrees Celsius.")

Try and implement this as a function in the cell below. Rather than taking input from the user and printing the result, the function should take a temperature in Fahrenheit as a single argument and return the temperature in Celsius.

[4]:
# Define function here

[5]:
# Call function here

Exercise 4 - Celsius to Fahrenheit

Write another function that performs the reverse calculation.

\(Fahrenheit = (Celsius * 9/5) + 32\)

[6]:
# Define function here

[7]:
# Call function here