Skip to main content

Python function for calculating Ohm's Law.

# coding=utf-8

def ohms_law(voltage=0, current=0, resistance=0):
    """
    Calculate Ohm's Law.

        E = I * R

    When spelled out, it means `voltage = current * resistance`,
    or `volts = amps * ohms`, or `V = A * Ω`.

        * E = Voltage - Volt (V), Pressure that triggers electron flow
        * I = Current - Ampere, amp (A), Rate of electron flow
        * R = Resistance - Ohm (Ω), Flow inhibitor

    References:

    * https://www.fluke.com/en-us/learn/blog/electrical/what-is-ohms-law
    * https://wikipedia.org/wiki/Ohm%27s_law

    :param voltage: Voltage amount. Set to `0` when calculating voltage.
    :type voltage: float

    :param current: Current amount. Set to `0` when calculating current.
    :type current: float

    :param resistance: Resistance. Set to `0` when calculating resistance.
    :type resistance: float

    :rtype: float
    """
    if voltage == 0:
        # Calculate voltage
        return current * resistance
    elif current == 0:
        # Calculate current
        return voltage / resistance
    elif resistance == 0:
        # Calculate resistance
        return voltage / current
    else:
        return 0


#
# Example usage
#

#
# What is the voltage in the circuit?
# E = I x R = (5A)(8Ω) = 40 V
print("Voltage = (E = I x R)", format(ohms_law(0, 5, 8), ".2f"))

# What is the current in the circuit?
# I = E/R = 12V/6Ω = 2A
print("Current = (I = E/R)", format(ohms_law(12, 0, 6), ".2f"))

# What is the resistance created by the lamp?
# R = E/I = 24V/6A = 4Ω
print("Resistance = (R = E/I)", format(ohms_law(24, 6, 0), ".2f"))