为什么不返回s?

时间:2018-09-19 08:48:05

标签: python

试图使一个函数使用SUVAT方程来计算每个变量,而这些函数没有返回应该已经计算出的值。

def float_input(text: str) -> float:
while True:
    try:
        num = float(input(text))
    except ValueError:
        num = ''
        break
    else:
        return num

print ('Enter the values of the following variables if they have been given')
s = float_input('Displacement')
u = float_input('Initial Velocity')
v = float_input('Final Velocity')
a = float_input('Acceleration')
t = float_input('Time')

def find_s (s, u, v, a, t):
    if s == '':
        if '' not in (v, u, a):
            es = 's = (v^2-u^2)/(2a)'
            s = ((v**2)-(u**2))/(2*a)
        elif '' not in (u, t, a):
            es = 's = ut + 1/2at^2'
            s = (u*t) + (0.5*a*t**2)
        elif '' not in (v, a, t):
            es = 's = vt - 1/2at^2'
            s = (v*t)-(0.5*a*t**2)
        elif '' not in (v, u, t):
            es = 's = t(v+u)/2'
            s = (0.5*(v+u))*t
        return (s, es)
    else:
        es = ''
        return (s, es)

s, es = find_s (s, u, v, a, t)
print (s)

我已经输入了u,v和a的值,这应该表示已计算出s,但是根据计算结果,它会打印'None'而不是s的值,为什么以及如何解决呢? / p>

1 个答案:

答案 0 :(得分:3)

请注意以下行为:

>>> def float_input(text: str) -> float:
        while True:
            try:
                num = float(input(text))
            except ValueError:
                num = ''
                break
            else:
                return num

>>> float_input('Foo: ')
Foo: NotAFloat
>>>

如您所见,即使我没有输入浮点数,float_input函数也会返回。这是因为当您遇到ValueError时,您会从while循环中中断,因此您实际上不会重新执行循环主体。

由于您中断了循环,因此在没有任何内容的循环之后,代码将继续执行,因此不会返回任何内容(None

您可能打算这样写:

>>> def float_input(text: str) -> float:
        while True:
            try:
                return float(input(text))
            except ValueError:
                pass


>>> float_input('Foo: ')
Foo: NotAFloat
Foo: MaybeAFloat?
Foo: 123foo
Foo: 123
123.0

一旦您解决了这一问题,代码的下一个问题当然就是您实际上从未调用过find_s,因此无需进行任何计算。相反,您只需打印“位移”输入的值。

相关问题