When you're trying to understand someone else's code, or figure out why your own code isn't working, it is incredibly useful to understand precisely what happens when each line of your program is run.
This lets you simulate the flow of your program in your head, which makes it clearer how the program behaves.
This is a skill you can get better at with practice.
Here is a small program:
def h(a, b):
result = a + b
return result
print(h(1, 2))
print(h(5, 7))
Let's step through this one line at a time to explain precisely what happens when Python runs the program.
Python starts at the first line. It sees def
which tells it that a function
definition is coming up. Then it sees (a, b)
which tells it that there are
two parameters.
The lines result = a + b
and return result
are not run yet. They are
indented, so Python understands they are part of the definition of h
.
(A definition only creates a function; the code inside the function isn't run before the function is called.)
Then the line print(h(1, 2))
is run. Before Python can know what to print,
it must first evaluate the argument to print
which is h(1, 2)
.
To evaluate h(1, 2)
Python looks up the definition of h
. It assigns the
arguments to the parameters: a = 1
and b = 2
. Then it runs the lines
inside the function body.
This means that Python runs result = a + b
which is result = 1 + 2
which
means that result
will hold the value 3
.
The line return result
will then return 3
, which sends the number 3
outside the function, back to the point where the function was called.
In other words, 3
is the result of the call h(1, 2)
. So 3
goes into
print
and 3
is shown on the screen. And so finally Python is done
running the line print(h(1, 2))
.
The next line is print(h(5, 7))
. Again, h(5, 7)
must be evaluated first.
So Python sets a = 5, b = 7
and runs the code inside the body of h
. This
calculates result = a + b
which is result = 5 + 7
which is result = 12
.
Then 12
is returned. So h(5, 7)
returns 12
, which becomes the argument
to print
and is thus shown on the screen.
That's a lot of words. But an experienced programmer can mentally step through the code in perhaps five or ten seconds and understand precisely what happens. It's simply a matter of practicing.