Skip to content

Create ohms_law.py #11736

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions physics/ohms_law.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
def ohms_law(current: float, resistance: float, decimals: int = 1) -> float:
"""
Calculate the voltage when current and resistance data is given using Ohm's Law.

Ohm's Law states that:
V = I * R

Where:
V = Voltage (Volts)
I = Current (Amperes)
R = Resistance (Ohms)

Parameters:
current (float): The current in Amperes (A).
resistance (float): The resistance in Ohms (Ω).
decimals (int): The number of decimal places to round the voltage. Default is 1.

Returns:
float: The calculated voltage in Volts (V).

Examples:
>>> ohms_law(2.0, 5.0)
10.0

>>> ohms_law(1.0, 4.0)
4.0

>>> ohms_law(3, 0.5)
1.5

>>> ohms_law(1.5, 2.0)
3.0

# Test case for invalid input (zero resistance)
>>> ohms_law(2, 0)
Traceback (most recent call last):
...
ValueError: Zero resistance

# Test case for invalid input (zero current)
>>> ohms_law(0, 3)
Traceback (most recent call last):
...
ValueError: Zero current
"""
if current == 0:
raise ValueError("Zero current")
if resistance == 0:
raise ValueError("Zero resistance")

voltage = current * resistance
return round(voltage, decimals)


if __name__ == "__main__":
import doctest

doctest.testmod(verbose=True)