New course! Every coder should learn Generative AI!
Try a free lesson+ 6
#Is there a problem in my code?
def ohm_law_cal(V=0, I=0, R=0):
if V == 0:
volts = I*R
return volts
elif I == 0:
amps = V/R
return amps
elif R == 0:
ohms = V/I
return ohms
v = int(input("V: "))
i = int(input("I: "))
r = int(input("R: "))
x = ohm_law_cal(v, i)
print(x)
try this.
remember python input is by default of string datatype.
+ 4
I personally find using sympy a bit over-engeneerd. (Please don't misunderstand this - the sample with sympy is very helpfulI.)
But it's a simple calculation, and the code can be shorted by keeping also a good readability.
The code uses a comprehension to read in all values, convert them to int and store them in individual variables. (It could also be done by storing the inpts in a list)
def ohm_law_cal(V=0, I=0, R=0):
if V == 0:
return I * R
elif I == 0:
return V / R
elif R == 0:
return V / I
v, i, r = [int(i) for i in input('V, I, R sep. by comma.:').split(',')]
print(f'{ohm_law_cal(v, i):.2f}')
+ 3
Your code can calculate volts, amps or ohms. Therefore you should pass all 3 variables v, i and r to the function. currently you only pass v and i, and so ohms is set to default = 0 in in function ohm_law_cal().
+ 3
+ 1
Just a pointer.
You should use float() type conversation instead of int(). Because a lot of this kind of calculation deals with decimal.
+ 1
Input() always return the value in string form
So, you should first typecast the input in int or float whatever you want
- 1
Vjryt