Python:跟踪For循环的执行 [英] Python: Tracing the Execution of a For Loop
问题描述
我试图跟踪一段包含 for loop
的代码的执行情况,其中包含两个 if条件
。但我需要帮助理解如何在python中执行 for循环
。
I am attempting to trace the execution of a piece of code that contains a for loop
with two if conditionals
. But I need help understanding exactly how for loops
are executed in python.
请考虑以下示例:
numAs = 0
numEs = 0
aStr1 = 'abcdefge'
def someFunc(aString):
1. for i in range(len(aString)):
2. if s[i] == 'a':
3. numAs += 1
4. continue
5. if s[i] == 'e':
6. numEs += 1
7. if numEs > numAs:
8. break
9. print(someFunc(aStr1))
问题:使用 aStr
作为参数在上面的代码中第1行执行多少次?
Question: Using aStr
as a parameter how many times will line 1 execute in the above code?
我的理解是这段代码的第1行: for i in range(len(aString))
,只会被执行一次。第2行和第5行将根据传递的字符串执行多次。当函数遇到 continue
语句时,它会返回到第2行并运行它。请确认或纠正我的想法。
My understanding is that line 1. of this piece of code: for i in range(len(aString))
, will only be executed once. While lines 2 and 5 will be executed multiple times depending on the string that is passed. When the function encounters the continue
statement it goes back to line 2 and runs it. Please confirm or correct my thinking.
谢谢
推荐答案
您的理解代码的作用是正确的。
Your understanding of what the code does is correct.
FWIW,使用 python -m trace -trace some_script很容易跟踪脚本的执行情况.py
或者你可以看到执行行计数 python -m trace --count some_script.py
。
FWIW, it is easy to follow the execution of a script using python -m trace --trace some_script.py
or you can see the execution line counts with python -m trace --count some_script.py
.
例如,后者调用 trace 会产生:
For example, the latter call to trace produces:
1: def someFunc(aString):
global numAs, numEs
1: s = aString
10: for i in range(len(aString)):
9: if s[i] == 'a':
2: numAs += 1
2: continue
7: if s[i] == 'e':
1: numEs += 1
1: if numEs > numAs:
break
1: numAs = 0
1: numEs = 0
1: someFunc('flammable')
这篇关于Python:跟踪For循环的执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!