如何查看 Python 中每个函数行的结果

how do I see the outcomes of each function line In Python

我正在尝试弄清楚如何查看 python 代码中每一行的效果,因为我正在阅读其他人的代码并想知道 python 中每一行的工作原理。例如,我有以下代码,想检查这段代码的每一行产生了什么。

有人可以帮我实现这个吗?

代码

def ValidParentheses(s):
    stack = []
    for i in s:
        if i == '(':
            stack.append(i)
        elif i == ')':
            if len(stack) == 0:
                return False
            else:
                stack.pop()
    if len(stack) == 0:
        return True
    else:
        return False

s = '())'
print(ValidParentheses(s))

结果:错误


好吧,您可以通过两种方式做到这一点:

  1. 您可以将简单的 print 添加到 istack 以查看它们在每个循环迭代中的位置,例如:
def ValidParentheses(s):
    stack = []
    for i in s:
        print(f'{i=} {stack=}')         # Just added this line
        if i == '(':
            stack.append(i)
        elif i == ')':
            if len(stack) == 0:
                return False
            else:
                stack.pop()
    if len(stack) == 0:
        return True
    else:
        return False

s = '())'
print(ValidParentheses(s))

输出将是:

i='(' stack=[]
i=')' stack=['(']
i=')' stack=[]
False
  1. 您可以使用调试器和多个断点来随时停止并查看每个变量在当前时间保存的内容。您可以使用 Pycharm 上的一个,这是非常推荐的,或者任何其他 IDE 适用于 python。只需写下 IDE 名称和“调试器”和 youtube,您就会看到很多教程。