在终端干净地处理用户输入而不崩溃

1 投票
5 回答
6826 浏览
提问于 2025-04-17 16:41

我有一个简单的项目要做。这是我目前写的代码,运行得很好。但是如果有人输入一个字母或者不认识的符号,程序就会崩溃。我要怎么做才能让这个程序更稳健,如果输入了错误的内容就显示或者打印一条提示信息呢?

def excercise5():

    print("Programming Excercise 5")
    print("This program calculates the cost of an order.")
    pound = eval(input("Enter the weight in pounds: "))
    shippingCost = (0.86 * pound) + 1.50
    coffee = (10.50 * pound) + shippingCost
    if pound == 1:
        print(pound,"pound of coffee costs $", coffee)
    else:
        print(pound,"pounds of coffee costs $", coffee)
    print()

excercise5()

5 个回答

0

使用异常处理

在Python中,如果有人给你不合法的输入,程序不会崩溃,而是会抛出一个异常。你可以捕捉这些异常并处理它们,而不是让Python直接退出程序。

在这种情况下,因为你只想要一个浮点数,所以其实不应该使用eval();这个函数会接受很多不同的输入,并且会抛出很多不同的异常。

你应该使用float()函数,它只会在你输入不正确时抛出一个ValueError。然后你可以捕捉这个错误并显示一个错误信息:

try:
    pound = float(input("Enter the weight in pounds: "))
except ValueError:
    print('Not a valid number!')
    return
0

把这段代码放在一个 try/except 结构里

def excercise5():
    print("Programming Excercise 5")
    print("This program calculates the cost of an order.")
    pound = eval(input("Enter the weight in pounds: "))
    try:
        shippingCost = (0.86 * pound) + 1.50
        coffee = (10.50 * pound) + shippingCost
        if pound == 1:
            print(pound,"pound of coffee costs $", coffee)
        else:
            print(pound,"pounds of coffee costs $", coffee)
    except ValueError:
        print("Please Enter a valid number")
    print()

我想说明一下:没有办法让代码完全“无错误”,就像子弹防护是不可能的,足够大的子弹可以穿透任何东西,代码也是一样。你能做的就是写出好的代码。编程中没有什么是绝对的。

5

我建议不要使用 eval。从安全的角度来看,这样做不好。你可以直接把数据转换成你想要的类型:

pound = float(input("Enter the weight in pounds: "))

为了处理无效的输入:

try:
    pound = float(input("Enter the weight in pounds: "))
except ValueError:
    print('Invalid input.')
    return
# the rest of the code

或者:

try:
    pound = float(input("Enter the weight in pounds: "))
except ValueError:
    print('Invalid input.')
else:
    # the rest of the code

你也可以把输入放在一个无限循环里,直到成功转换为止:

while True:
    try:
        pound = float(input("Enter the weight in pounds: "))
    except ValueError:
        print('Invalid input. Try again.')
    else:
        break
# do the rest with `pound`

撰写回答