python-3.x 代码发生了什么(我正在做一个二次方程求解器)?[duplicate]

h43kikqp  于 2022-11-19  发布在  Python
关注(0)|答案(1)|浏览(120)

此问题在此处已有答案

Asking the user for input until they give a valid response(22个答案)
昨天关闭。

print("ax^2 + bx + c = 0")

def ask_a():
    a = int(input("""Please enter a:
a = """))
    if a == 0:  
        print("Please input the correct number! \n")
        a = int(input("""Please enter a:
a = """))
    else:
        try:
            a == int(a)
            print(f"a = {a}")
        except ValueError:
            print("Please input the correct number! \n")
            a = int(input("""Please enter a:
a = """))

a =  ask_a()

错误消息:

Traceback (most recent call last):
  File "c:\Users\jbtua\OneDrive\Desktop\wut is this\Personal Folder\Programming Projects\Python\blank.py", line 19, in <module>
    a =  ask_a()
  File "c:\Users\jbtua\OneDrive\Desktop\wut is this\Personal Folder\Programming Projects\Python\blank.py", line 4, in ask_a
    a = int(input("""Please enter a:
ValueError: invalid literal for int() with base 10: 'a'

我仍然不知道这是什么原因。

pcww981p

pcww981p1#

print("ax^2 + bx + c = 0")

def ask_a():
    a = input("""Please enter a: a = """)
    if a == 0:  
        print("Please input the correct number! \n")
        a = int(input("""Please enter a: a = """))
    else:
        try:
            a == int(a)
            print(f"a = {a}")
        except ValueError:
            print("Please input the correct number! \n")
            # a = int(input("""Please enter a: a = """))

a =  ask_a()

要处理异常,您不希望在a = input("""Please enter a: a = """)步骤生成错误
更好的方法:

def ask_a():
    flag = False
    while not flag:
        try:
            a = input("""Please enter a: a = """)
            a = float(a)
        except:
            continue
        else:
            if float(a) != 0.0:
                flag = True
                a = float(a)
            else:
                continue

    return a
a =  ask_a()

相关问题