您可以使用循环来自动化输入,将值存储在字典中,然后在最后进行所有数学运算。
import math
units = {'s': 'm', 'u': 'ms^-1', 'v': 'ms^-1', 'a': 'ms^-2', 't': 's'}
variables = ['s', 'u', 'v', 'a', 't']
suvat = dict((k, None) for k in variables)
input_variables = []
def pick_from_list(prompt, L):
while True:
pick = raw_input(prompt % str(L))
if pick in L:
print "You have chosen", pick
return pick
print """Sorry, I didn't understand that, try again. Make sure your spelling is
correct (Case Sensitive), and that you did not inlcude the quotation marks."""
aim = pick_from_list("""Welcome to Mattin's SUVAT Simulator! Choose the value you are
trying to find. You can pick from variables %s""",
variables)
for order in 'first', 'second', 'third':
prompt = 'Please choose which variable to input %s. You can pick from %%s' % order
choices = [k for k in variables if not (k is aim or k in input_variables)]
input_variables.append(pick_from_list(prompt, choices))
for v in input_variables:
while True:
raw_input("""What is the value of %s? Make sure it is in standard
units, however, do not include the unit.""" % v)
try:
suvat[v] = float(val)
print "%s is %s%s" % (v, val, units[v])
break
except:
print "You must enter a number. Don't include units!"
# for readability of the maths, turn dictionary into variables
s, u, v, a, t = [suvat[k] for k in variables]
# (not tested)
if s is None:
if t is None:
t = (v - u) / a
if v is None:
s = u * t + .5 * a * t * t
elif a is None:
s = .5 * (u + v) * t
else:
s = v * t - .5 * a * t * t
if v is None:
if u is None:
u = s / t - .5 * a * t * t
if t is None:
v = math.sqrt(u * u + 2 * a * s)
else:
v = 2 * s / t - u
if u is None:
if a is None:
a = 2 * v / t - s / (t * t)
u = math.sqrt(v * v - 2 * a * s)
if a is None:
a = (v * v - u * u) / (2 * s)
if t is None:
t = (v - u) / a
# turn the set of variables back into a dictionary
solutions = dict(zip(variables, [s, u, v, a, t]))
print 'Solution: %s=%s%s' % (aim, solutions[aim], units[aim])