Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 5d0f62f

Browse files
authoredOct 4, 2024··
Create ohms_law.py
1 parent 40f65e8 commit 5d0f62f

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
 

‎physics/ohms_law.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
def ohms_law(current: float, resistance: float, decimals: int = 1) -> float:
2+
"""
3+
Calculate the voltage when current and resistance data is given using Ohm's Law.
4+
5+
Ohm's Law states that:
6+
V = I * R
7+
8+
Where:
9+
V = Voltage (Volts)
10+
I = Current (Amperes)
11+
R = Resistance (Ohms)
12+
13+
Parameters:
14+
current (float): The current in Amperes (A).
15+
resistance (float): The resistance in Ohms (Ω).
16+
decimals (int): The number of decimal places to round the voltage. Default is 1.
17+
18+
Returns:
19+
float: The calculated voltage in Volts (V).
20+
21+
Examples:
22+
>>> ohms_law(2.0, 5.0)
23+
10.0
24+
25+
>>> ohms_law(1.0, 4.0)
26+
4.0
27+
28+
>>> ohms_law(3, 0.5)
29+
1.5
30+
31+
>>> ohms_law(1.5, 2.0)
32+
3.0
33+
34+
# Test case for invalid input (zero resistance)
35+
>>> ohms_law(2, 0)
36+
Traceback (most recent call last):
37+
...
38+
ValueError: Zero resistance
39+
40+
# Test case for invalid input (zero current)
41+
>>> ohms_law(0, 3)
42+
Traceback (most recent call last):
43+
...
44+
ValueError: Zero current
45+
"""
46+
if current == 0:
47+
raise ValueError('Zero current')
48+
if resistance == 0:
49+
raise ValueError('Zero resistance')
50+
51+
voltage = current * resistance
52+
return round(voltage, decimals)
53+
54+
55+
if __name__ == "__main__":
56+
import doctest
57+
doctest.testmod(verbose=True)

0 commit comments

Comments
 (0)
Please sign in to comment.