Physics Equation In Python
I want to make a program that can calculate physics equation where the user enters different parameters: I know its simple like: v=5 t=7 s=v*t print(s) its only calculating s = v*
Solution 1:
You could use key word arguments:
defsolve_equation(v=None, t=None, s=None):
if v isnotNoneand t isnotNone:
return v * t # s caseelif s isnotNoneand t: # t not None and not 0 return s / t # v caseelse:
raise ValueError #"t should be defined or not zero"print(solve_equation(v=10, t=2))
print(solve_equation(s=2, t=7))
Output:
20
0.2857142857142857
Note that if you are using python 2, floats must be passed.
Solution 2:
Assuming you're talking about the zero acceleration "svt" equations (or even the constant acceleration "suvat" ones, should you have more complex requirements), it's a simple matter of detecting what's unknown, and then filling in the gaps.
The following code provides a function that will do this along with some test code so you can see it in action:
# Returns a 3-tuple containing [displacement(s), velocity(v), time(t)],# based on the existence of at least two of those.# If all three are given, the displacement is adjusted so that the# equation 's = vt' is correct.deffillInSvt(s = None, v = None, t = None):
# Count the unknowns, two or more means no unique solution.
noneCount = sum(x isNonefor x in [s, v, t])
if noneCount > 1: return [None, None, None]
# Solve for single unknown (or adjust s if none).if noneCount == 0or s isNone: return [v*t, v, t]
if v isNone: return [s, s/t, t]
return [s, v, s/v]
# Test code.print(fillInSvt(99,4,6)) # Show case that adjusts s.print(fillInSvt(None,4,6)) # Show cases that fill in unknown.print(fillInSvt(24,None,6))
print(fillInSvt(24,4,None))
print(fillInSvt(24,None,None)) # Show "not enough info" cases.print(fillInSvt(None,4,None))
print(fillInSvt(None,None,6))
print(fillInSvt(None,None,None))
The output shows that the tuple is filled in in all cases where there's a unique solution:
[24, 4, 6]
[24, 4, 6]
[24, 4.0, 6]
[24, 4, 6.0]
[None, None, None]
[None, None, None]
[None, None, None]
[None, None, None]
Solution 3:
I'm not sure if this is what you want, but you could define three separate functions, one for each variable. For example,
defs(v, t):
return v*t
defv(s, t):
return s/t
deft(s, v):
return s/v
Solution 4:
def h2(v,d,t):
title_ar = 'السرعة'
title_en = 'speed'if v=='':
print("v= ","%.2f"% (d/t),"m/s")
elif d=='':
print("d= ","%.2f"% (v*t),"m")
elif t=='':
print("t= ","%.2f"% (d/v),"s")
else:
print("please write all data.")
h2('', 2,6)
h2(70,'',8)
h2(25,3,'')
Post a Comment for "Physics Equation In Python"