Sololearn: Learn to Code
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.
29th Sep 2020, 6:05 PM
Rohit
+ 4
RKK 👏👏 CodeShow One more thing 🤔 In case really the R or V or I are 0 Then? If someone knows i and r how will you print v? 🤔 Use sympy in such cases! Do you want a demo?
29th Sep 2020, 7:05 PM
Namit Jain
Namit Jain - avatar
+ 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}')
30th Sep 2020, 2:03 PM
Lothar
Lothar - avatar
+ 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().
29th Sep 2020, 6:29 PM
Lothar
Lothar - avatar
30th Sep 2020, 4:12 AM
Namit Jain
Namit Jain - avatar
+ 1
Just a pointer. You should use float() type conversation instead of int(). Because a lot of this kind of calculation deals with decimal.
29th Sep 2020, 7:46 PM
Light
Light - avatar
+ 1
Input() always return the value in string form So, you should first typecast the input in int or float whatever you want
30th Sep 2020, 1:25 PM
Saurabh Khade
Saurabh Khade - avatar
- 1
Vjryt
1st Oct 2020, 3:11 PM
Romina Primavera Moreno
Romina Primavera Moreno - avatar