Python程序执行顺序

时间:2017-11-02 16:08:40

标签: python-3.6

#!/usr/bin/env python3

import math

a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))

def quadratic(a, b ,c):
    delta = b**2 - 4*a*c
    if delta < 0:
        print('There is no real root for this equation')
    else:
        x1 = (-b + math.sqrt(delta))/(2*a)
        x2 = (-b - math.sqrt(delta))/(2*a)
        print('The root for this equation are: x1 =', x1, '; x2 =', x2)

    return x1, x2

quadratic(a, b, c)

当我输入a = 3,b = 2,c = 3时,我得到了:

~/file $ ./quadratic.py 
a = 3
b = 2
c = 3
There is no solution for this equation
Traceback (most recent call last):
  File "./quadratic.py", line 19, in <module>
    quadratic(a, b, c)
  File "./quadratic.py", line 17, in quadratic
    return x1, x2
UnboundLocalError: local variable 'x1' referenced before assignment

在我看来,我认为程序应该执行直到打印(&#39;没有真正的根...等式&#39;)然后跳转到该行(返回x1,x2)。 我在python文档中搜索UnboundLocalError。但我没有 在函数外部使用变量x1。所以我无法理解错误 出来。我想也许是一个错误(NameError:name&#39; x1&#39;未定义 )更合理。

0 个答案:

没有答案