为什么以下代码不遵循指定的顺序?

时间:2017-05-07 16:17:08

标签: python while-loop

我希望它说欢迎,请求用户输入(a,b,c),验证用户输入,如果验证返回输入是合理的,则执行a,b,c上的二次公式。我怀疑问题出在while循环中。程序只是欢迎,请求输入然后再说欢迎等等。

from math import sqrt

def quadratic_formula(a,b,c):
    a=float(a)                                      #The quadratic formula
    b=float(b)
    c=float(c)
    x1_numerator = -1*b + sqrt((b**2)-4*(a*c))
    x2_numerator = -1*b - sqrt((b**2)-4*(a*c))
    denominator = 2*a
    x1_solution = x1_numerator/denominator
    x2_solution = x2_numerator/denominator
    print("x= "+str(x1_solution)+" , x= "+str(x2_solution))

def number_check(a,b,c,check):                     #carries out a check 
    a=float(a)
    b=float(b)
    c=float(c)
    if (b**2)-4*a*c < 0:
        print("The values you have entered result in a complex solution. Please check your input.")
        check == False
    else:
        check == True

check = False

while check == False:
    print("Welcome to the Quadratic Equation Calculator!")
    a = input("Please enter the x^2 coefficient: ")
    b = input("Please enter the x coefficient: ")
    c = input("Please enter the constant: ")
    number_check(a,b,c,check)
else:
    quadratic_formula(a,b,c)

1 个答案:

答案 0 :(得分:1)

尝试使用return,而不是尝试修改全局变量。

有一种使用全局变量的方法(请参阅global语句),但此代码不需要它。

检查变量本身并不是必需的,但

def number_check(a,b,c): 
    a=float(a)
    b=float(b)
    c=float(c)
    return (b**2)-4*a*c >= 0  # return the check

while True:
    print("Welcome to the Quadratic Equation Calculator!")
    a = input("Please enter the x^2 coefficient: ")
    b = input("Please enter the x coefficient: ")
    c = input("Please enter the constant: ")
    if not number_check(a,b,c):
        print("The values you have entered result in a complex solution. Please check your input.")
    else:
        break  # getting out of the loop