如何从用户那里获得输入并在Python中应用计算?

时间:2014-02-01 07:04:37

标签: python

我刚刚开始使用python。

我想从用户那里获得输入并进行计算。

示例:我想通过t =(v sin(theta))/g

获得弹丸运动的时间飞行
import math
print "this program will find time flight of projectile motion"
g = 9.8
##get the velocity and angle
##calculate it
##print time with some text

1 个答案:

答案 0 :(得分:1)

使用raw_input(),请参阅http://docs.python.org/2/library/functions.html#raw_input

import math
v = raw_input("please enter the velocity: ")
theta = raw_input("please enter the theta (i.e. degree of liftoff): ")
v, theta = float(v) , float(theta)
t = (v * math.sin(theta)) / float(9.81)
print "assuming that g = 9.81"
print "projectile motion =", t

使用sys.argv,请参阅http://docs.python.org/2/library/sys.html#sys.argv

import sys, math
if len(sys.argv) == 3 and sys.argv[1].replace(".","").isdigit() and sys.argv[2].replace(".","").isdigit():
    v, theta = float(sys.argv[1]) , float(sys.argv[2])
    t = (v * math.sin(theta)) / float(9.81)
    print "assuming that g = 9.81"
    print "projectile motion =", t
else:
    print "Usage:", "python %s velocity theta" % sys.argv[0]