Python中的物理方程 [英] 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)
仅计算 s = v * t
;但是,当我想要 v
的方程式时,请告诉我一个错误.硬编码 v = s/t
给了我正确的结果:
its only calculating s = v*t
; however, when I want the equation of v
if show me an error. Hard coding v = s/t
gives me the correct result:
s=5
t=7
v=s/t
print(v)
我想要一个方程,可以用不同的用户输入求解;也就是说,如果用户输入 v
和 t
,则方程式将返回 s = v * t
,并且如果用户输入了 s
和 t
方程将返回 v = s/v
.
I want an equation that can solve with different user input; that is if user inputs the v
and t
, the equation will return s = v*t
and if the user inputs s
and t
the equation will return v = s/v
.
推荐答案
您可以使用关键字参数:
You could use key word arguments:
def solve_equation(v=None, t=None, s=None):
if v is not None and t is not None:
return v * t # s case
elif s is not None and t: # t not None and not 0
return s / t # v case
else:
raise ValueError #"t should be defined or not zero"
print(solve_equation(v=10, t=2))
print(solve_equation(s=2, t=7))
输出:
20
0.2857142857142857
请注意,如果您使用的是python 2,则必须传递浮点数.
Note that if you are using python 2, floats must be passed.
这篇关于Python中的物理方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!