问题
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.
Please consider the following example:
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))
Question: Using aStr
as a parameter how many times will line 1 execute in the above code?
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.
Thanks
回答1:
Your understanding of what the code does is correct.
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
.
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')
来源:https://stackoverflow.com/questions/8032484/python-tracing-the-execution-of-a-for-loop