我怎样才能摆脱这段代码中过多的重复?
代码:http://pastebin.com/13e2nWM9
程序根据用户提供的数据计算运动方程 (SUVAT Equations)。
我指的部分是:
while True:
a = raw_input("What is the value of a? Make sure it is in standard units, however, do not include the unit.")
try:
float(a)
print "a is " + str(a) + " ms^-2"
break
except:
print"You must enter a number. Don't include units!"
这会重复很多次,除了变量“a”和重复 block 时更改的单位。
非常感谢。
最佳答案
这是一个选项,将以下函数定义放在模块的顶部:
def get_float(name, units):
prompt = "What is the value of {0}? Make sure it is in standard units, however, do not include the unit.".format(name)
while True:
val = raw_input(prompt)
try:
val = float(val)
print '{0} is {1} {2}'.format(name, val, units)
return val
except Exception:
print "You must enter a number. Don't include units!"
这是一个如何使用它的示例,以下代码可以替换第 72 行到第 100 行的所有内容:
name_units_pairs = [('v', 'ms^-1'), ('a', 'ms^-2'), ('t', 's'),]
vals = {}
for name, units in name_units_pairs:
vals[name] = get_float(name, units)
u = vals['v'] - vals['a'] * vals['t']
关于Python:让这段代码更紧凑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15960655/