Applied Programming/Conditions/Python3

conditions.py edit

"""This program converts a Fahrenheit temperature to Celsius.

Input:
    Fahrenheit temperature

Output:
    Fahrenheit temperature
    Celsius temperature

Example:
    Enter Fahrenheit temperature:
     100
    100.0° Fahrenheit is 37.8° Celsius

References:
    * http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
    * https://wiki.python.org/moin/UsingAssertionsEffectively
    * https://stackoverflow.com/questions/1278705/python-when-i-catch-an-exception-how-do-i-get-the-type-file-and-line-number
    * http://www.mathsisfun.com/temperature-conversion.html

"""

import os
import sys

ABSOLUTE_ZERO = -459.67

def get_fahrenheit():
    """Gets Fahrenheit temperature.

    Args:
        None

    Returns:
        float: Fahrenheit temperature

    Exits:
        ValueError: If Fahrenheit temperature is not a valid float.
        ValueError: If Fahrenheit temperature is below absolute zero.

    """
    try:
        print("Enter Fahrenheit temperature:")
        fahrenheit = input()
        fahrenheit = float(fahrenheit)
        if fahrenheit < ABSOLUTE_ZERO:
            print("Fahrenheit temperature cannot be below absolute zero.")
            print(f"ValueError: {fahrenheit} is invalid."
            os._exit(1)   
        return fahrenheit
    except ValueError:
        print("Fahrenheit temperature must be a floating point value.")
        print(f"ValueError: {fahrenheit} is invalid.")
        os._exit(2)


def fahrenheit_to_celsius(fahrenheit):
    """Converts Fahrenheit temperature to Celsius.

    Args:
        fahrenheit (float): Fahrenheit temperature to be converted

    Returns:
        float: Celsius temperature

    Raises:
        ValueError: If Fahrenheit temperature is not a valid float.
        ValueError: If Fahrenheit temperature is below absolute zero.

    """
    try:
        fahrenheit = float(fahrenheit)
    except ValueError:
        raise ValueError(f"fahrenheit must be a float. Received '{fahrenheit}'")
    except:
        raise

    if fahrenheit < ABSOLUTE_ZERO:
        raise ValueError(f"fahrenheit must not be below absolute zero. Received '{fahrenheit}'")

    TEMPERATURE_DIFFERENCE = 32
    TEMPERATURE_RATIO = 5 / 9
    celsius = (fahrenheit - TEMPERATURE_DIFFERENCE) * TEMPERATURE_RATIO
    return celsius


def display_results(fahrenheit, celsius):
    """Displays Fahrenheit and Celsius temperatures.

    Args:
        fahrenheit (float): Fahrenheit temperature
        celsuis (float): Celsius temperature

    Returns:
        None

    Raises:
        AssertionError: If Fahrenheit temperature is not a valid float.
        AssertionError: If Celsius temperature is not a valid float.

    """
    assert isinstance(fahrenheit, float) or isinstance(fahrenheit, int), \
        "fahrenheit must be a float. Received {type(fahrenheit)}" 
    assert isinstance(celsius, float) or isinstance(celsius, int), \
        "celsius must be a float. Received {type(celsius)}"
    print(f"{fahrenheit}.1f° Fahrenheit is {celsius}.1f° Celsius")
    

def main():
    """Runs the main program logic."""

    try:
        fahrenheit = get_fahrenheit()
        celsius = fahrenheit_to_celsius(fahrenheit)
        display_results(fahrenheit, celsius)
    except:
        print("Unexpected error.")
        print("Error:", sys.exc_info()[1])
        print("File: ", sys.exc_info()[2].tb_frame.f_code.co_filename) 
        print("Line: ", sys.exc_info()[2].tb_lineno)


main()

Try It edit

Copy and paste the code above into one of the following free online development environments or use your own Python3 compiler / interpreter / IDE.

See Also edit