Week 3 - Exercises

Exercise 1 - First module

This week we are going to write a module and import some functions from it.

For the code below to work, you need to do the following:

  1. Create a file called mymodule.py and put it in the same folder as this notebook. It me be easiest to do this in Spyder.

  2. Write the three functions that are to be imported from mymodule. Note that these are the three scripts from the first week, but they will need to be implemented in the module as functions.

The desired output is as follows. First, we play the number guessing game, which should return the secret number at the end. Then, we check whether that number is a prime number. Finally, we pretend that the number is a temperature in degrees Fahrenheit and report the equivalent in Celsius.

There are many ways to approach this problem, but the output should look something like below.

[1]:
from mymodule import (
    guess_the_number,
    check_prime_number,
    fahrenheit_to_celsius
)

# Play the number guessing game
number = guess_the_number()

# Check whether the secret number is a prime
check_prime_number(number)

# If the number was a temperature in degrees Fahrenheit,
# report the equivalent in Celsisus
fahrenheit_to_celsius(number)
Let's play a guessing game!

Enter any whole number between 1 and 100:  50
Too low
Enter number again:  75
Too low
Enter number again:  90
Too high!
Enter number again:  83
Too high!
Enter number again:  82
Too high!
Enter number again:  81
Too high!
Enter number again:  80
Too high!
Enter number again:  78
You guessed it right!!

Checking to see if 78 is a prime number.
        Testing for 2
78 is divisible by 2, so it is not a prime number.
78 degrees fahrenheit is equivalent to 25.56 degrees celsius.

module.py

[ ]:
"""A small module with some functions we have been working on."""

import random


def guess_the_number():
    """Play a number guessing game.

    Returns
    -------
    number : int
        The correct number.

    """
    # Generate a random number between 1 and 101
    number = random.randrange(1, 101)

    print("Let's play a guessing game!\n")

    # Ask the user to have a guess
    guess = int(float(input("Enter any whole number between 1 and 100: ")))

    # Keep asking until the guess is right
    while number != guess:
        if guess < number:
            print("Too low")
            guess = int(input("Enter number again: "))
        elif guess > number:
            print("Too high!")
            guess = int(input("Enter number again: "))
        else:
            break

    # Tell user they guessed right
    print("You guessed it right!!\n")

    # Return the number
    return number


def check_prime_number(number):
    """Check if a number is prime.

    Parameters
    ----------
    number : int
        The number to check (must be an integer).

    Returns
    -------
    None

    """
    # Throw an error if number is not an integer
    if not isinstance(number, int):
        raise TypeError(f"check_prime_number expects int, but got {type(number)}")

    # Print out some feedback
    print(f"Checking to see if {number} is a prime number.")

    # Define a flag variable
    is_prime = False

    # Prime numbers are greater than 1
    if number > 1:
        # Check for factors
        for i in range(2, number):
            print("\tTesting for " + str(i))
            if (number % i) == 0:
                # If factor is found, set flag to True
                is_prime = True
                # Break out of loop
                break

    if not is_prime:
        print(f"{number} is a prime number.")
    else:
        print(f"{number} is divisible by {i}, so it is not a prime number.")

    return None


def fahrenheit_to_celsius(temp):
    """Convert Fahrenheit to Celsius.

    Parameters
    ----------
    temp : int or float
        Temperature in Fahrenheit.

    Returns
    -------
    celsius : float
        Equivalent temperature in Celsius.

    """
    # Throw an error if number is not integer or floating point
    if not isinstance(temp, (int, float)):
        raise TypeError(
            f"fahrenheit_to_celsius expects int or float, got {type(temp)}"
        )

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

    print(
        f"{temp} degrees fahrenheit is equivalent to {celsius} degrees celsius."
    )

    return None