 Is there a problem in my code? | SoloLearn: Learn to code for FREE!

+1

# 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 = input("V: ") i = input("I: ") r = input("R: ") x = ohm_law_cal(v, i) print(x)

+5

#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

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?

+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

CodeShow See this 🙂 https://code.sololearn.com/cGcf0MC0VMIr/?ref=app

+2

thank you RKK and Lothar

+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

thank you Namit Jain and Light

+1

Input() always return the value in string form So, you should first typecast the input in int or float whatever you want

0

Namit Jain if I understane your question the function returns the calculation then the print() statement prints it. Yes I would like a demo on sympy.