python 中的调试代码

debugging code in python

我正在编写一些代码来执行此操作: 用 0 到 9 的数字填充一个数组,然后将小于 5 的数字放在数组的末尾。我的代码是这样的:

    print ("give n: ")
    n = int(input())
    a = []
    for i in range(n):
        num = 0
        print ("give a number from 0 to 9 ")
        num = int(input())
        while (num > 9 and num < 0):
            print ("only from 0 to 9")
            num = int(input())
        a.append(num)
    tmp = 0
    for i in range(n):
        if (a[i]<5):
            tmp = a[i]
            a[i] = a[i+1]
            a[i+1] = tmp
    for i in range(n):
        print a[i]

我的问题是,当我 运行 它时,如果我提供任何其他内容,检查数字是否从 0 到 9 的循环将被忽略,它会将它传递给数组,它会给我一个第 16 行错误 (a[i] = a[i+1])。提前致谢!

python 有调试器: https://docs.python.org/3/library/pdb.html 一开始就学习它可能会有用。

用于 Python 中的调试。 添加 import pdb,然后将 pdb.set_trace() 放在您希望调试器中断的位置。