Function#

Overview#

A function contains a series of code statements for a specific task, and it can be reusable by simply calling it across your code.

The function is the best strategy to organize your program in steps, and it makes your code more readable and easier to debug. Functions bring reuse and modularity to your pogram.

General syntax


def function_name(input_parameter1, input_parameter2,..., input_parameterN):
    # Code block
    # Perform specific task
    # return statement

Definition:

  • def: it tells your program that a function will be created

  • function_name: this is the function name, and it should be simple and descriptive

  • input_parameters: your function can have (or not) several inputs so the block code within your function can execute them using the inputs. Functions can have zero or more parameters.

  • Code block: all code statements are executed everytime you are calling this function

  • return statement: your function can have (or not) results that return is used to pass the results

Examples#

def convert_temperature(value, from_unit, to_unit):
    """
    Converts temperature between Celsius, Fahrenheit, and Kelvin.

    Parameters:
    - value: The temperature value to convert.
    - from_unit: The unit of the input temperature value ('C', 'F', or 'K').
    - to_unit: The unit to convert the temperature value to ('C', 'F', or 'K').

    Returns:
    The converted temperature value.
    """
    if from_unit == to_unit:
        return value

    if from_unit == 'C':
        if to_unit == 'F':
            return (value * 9/5) + 32
        elif to_unit == 'K':
            return value + 273.15
    elif from_unit == 'F':
        if to_unit == 'C':
            return (value - 32) * 5/9
        elif to_unit == 'K':
            return (value + 459.67) * 5/9
    elif from_unit == 'K':
        if to_unit == 'C':
            return value - 273.15
        elif to_unit == 'F':
            return (value * 9/5) - 459.67

    # If the units are not valid or compatible, raise an exception.
    raise ValueError("Invalid or incompatible temperature units.")
# Convert 25 degrees Celsius to Fahrenheit
result = convert_temperature(25, 'C', 'F')
print(result)  # Output: 77.0

# Convert 98.6 degrees Fahrenheit to Celsius
result = convert_temperature(98.6, 'F', 'C')
print(result)  # Output: 37.0

# Convert 0 Kelvin to Celsius
result = convert_temperature(0, 'K', 'C')
print(result)  # Output: -273.15
77.0
37.0
-273.15