Skip to main content

Foundations of Python Programming: Functions First

Section 1.9 To Understand a Program, Change It!

To check your understanding or your predictions, always run the program. This seems like an obvious step a programmer would always make, but it is something that novice programmers too often overlook doing.
To check your understanding about the state of variables before your code snippet runs, add diagnostic print statements that print out the types and values of variables. Sometimes referred to as ’echo prints’, add these print statements just before and after the code snippet you are trying to understand.
x = 4
y = 7
print(x, type(x), y, type(y)) # echo print
y = x + 0.2 ;print(type(y), "y=",y) # diagnostic print on same line
If you made a prediction about the output that will be generated when the code snippet runs, then you can just run the program to see if you are right. If, however, you made a prediction about a change that occurs in the value of a variable, add an extra diagnostic print statement right after the line of code that you think should be changing that variable.
The diagnostic print statements are temporary. Once you have verified that a program is doing what you think it’s doing, you will remove these extra print statements.
Even if you feel that you have a good grasp on the program though, we advise changing it at least a few times to see if you understand how it behaves in different situations. Sometimes you’ll surprise yourself!
When you get any surprises, you will want to revise your understanding or your predictions. If you were wrong about the values or types of variables before the code snippet was run, you may want to revisit your understanding of the previous code. Once you understand how that result came to be, you should make some changes to the program to make sure your new understanding is accurate and what you intend for the algorithm.
You have attempted of activities on this page.