Example: Square numbers¶
Square numbers are positive integers that are equal to the square of an integer. Here we have provided example Python and R scripts that print all of the square numbers between 1 and 100:
You can download these scripts to run on your own computer:
Each script contains three functions:
main()
find_squares(lower_bound, upper_bound)
is_square(value)
The diagram below shows how main()
calls find_squares()
, which in turn calls is_square()
many times.
sequenceDiagram
participant M as main()
participant F as find_squares()
participant I as is_square()
activate M
M ->>+ F: lower_bound = 1, upper_bound = 100
Note over F: squares = [ ]
F ->>+ I: value = 1
I ->>- F: True/False
F ->>+ I: value = 2
I ->>- F: True/False
F -->>+ I: ...
I -->>- F: ...
F ->>+ I: value = 100
I ->>- F: True/False
F ->>- M: squares = [...]
Note over M: print(squares)
deactivate M
Source code
square_numbers.py | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
square_numbers.R | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
Stepping through the code¶
These recorded terminal sessions demonstrate how to use Python and R debuggers from the command line. They cover:
- How to define breakpoints;
- How to inspect the current values of variables; and
- How to step through, and over, lines of code.
Manual breakpoints
You can also create breakpoints in your code by calling breakpoint()
in Python, and browser()
in R.
Interactive debugger sessions
If your editor supports running a debugger, use this feature! See these examples for RStudio, PyCharm, Spyder, and VS Code.
Video timeline: