python - 为什么计算器会崩溃

标签 python python-3.x

我试着做一个计算器作为家庭作业。如果我提供正确的输入,它看起来工作正常。但是,如果我将第一个数字设为空字符串,程序就会崩溃:

TypeError: 'NoneType' object is not subscriptable

为什么会发生这种情况,我该如何解决?

def read_numbers():
    try:
        number1 = float(input("Give first number: "))
        number2 = float(input("Give the second number: "))
        return [number1,number2]
    except ValueError:
        read_numbers()
    except TypeError:
        read_numbers()

def summa():
    numbers = read_numbers()
    return numbers[0]+numbers[1]

command = ""
while command != "q":
    command = input("Give command: ")
    if command == "s":
        print(summa())
    elif command == "q":
        break

最佳答案

您的 read_numbers() 函数并不总是返回任何内容。当函数结束时没有 return 语句时,将返回 None。当您递归时(使用 ValueErrorTypeError,您忘记返回递归调用结果。

你会像这样返回递归调用:

def read_numbers():
    try:
        number1 = float(input("Give first number: "))
        number2 = float(input("Give the second number: "))
        return [number1,number2]
    except (ValueError, TypeError):
        return read_numbers()

我将两个异常合并到一个处理程序中。注意 read_numbers() 调用中的 return;仅仅因为 嵌套 调用返回一个值,并不意味着函数调用本身会自动传递该结果。

但是使用循环会更好:

def read_numbers():
    while True:
        try:
            number1 = float(input("Give first number: "))
            number2 = float(input("Give the second number: "))
            return [number1,number2]
        except ValueError:
            pass  # continue the loop

return 将结束循环和函数。我删除了 TypeError 异常,input() 总是返回一个字符串,而 float() 只会引发 ValueError当传递一个无法解析为 float 的字符串时。 TypeError 仅当参数属于无法转换为 float 的类型时才会引发,例如字典或自定义对象。

关于python - 为什么计算器会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19988438/

相关文章:

python - 使用最小堆数据结构实现单遍算法以查找列到列包含

python - 批量保存复杂对象 SQLAlchemy

python - 总结字典的值(value)

python - python 中的记录数据类型等效

linux - 我无法使用导入命令

python - 如何在 python 的 socket recv 方法上设置超时?

python - 如何以完全相同的方式对两个列表(相互引用)进行排序

python - 几个大嵌套循环的小循环 vs 小嵌套循环的大循环性能?

linux - 在 virtualenv 中使用 escpos 时的权限

Python 无法为 dlib Ubuntu 构建轮子