Python:让这段代码更紧凑?

标签 python python-2.7 while-loop physics performance

我怎样才能摆脱这段代码中过多的重复?

代码: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/

相关文章:

python - 排序 OrderedDict 不起作用

python - 在 Pepper 的平板电脑上显示 QiChat 输入和输出

python - 如何检测键盘输入以使用 python 播放声音?

python - 如何在python中调整base64编码图像的大小

regex - Python 使用正则表达式替换短代码

c++ - 而大于负数则不起作用

c++ - 使用回调函数打破 while 循环的最佳方法是什么?

python - 如何限制 tkinter 列表框中的选择数量?

python - 如何? : Setting up Bokeh w/Redis Backend

python - 要求用户输入数字并输出总和以及输入数字的数量的程序