Skip to content

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
#!/usr/bin/env python3
"""
Print the square numbers between 1 and 100.
"""


def main():
    squares = find_squares(1, 100)
    print(squares)


def find_squares(lower_bound, upper_bound):
    squares = []
    value = lower_bound
    while value <= upper_bound:
        if is_square(value):
            squares.append(value)
        value += 1
    return squares


def is_square(value):
    for i in range(1, value + 1):
        if i * i == value:
            return True
    return False


if __name__ == '__main__':
    main()
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
#!/usr/bin/env -S Rscript --vanilla
#
# Print the square numbers between 1 and 100.
#


main <- function() {
  squares <- find_squares(1, 100)
  print(squares)
}


find_squares <- function(lower_bound, upper_bound) {
  squares <- c()
  value <- lower_bound
  while (value <= upper_bound) {
    if (is_square(value)) {
      squares <- c(squares, value)
    }
    value <- value + 1
  }
  squares
}


is_square <- function(value) {
  for (i in seq(value)) {
    if (i * i == value) {
      return(TRUE)
    }
  }
  FALSE
}

if (! interactive()) {
  main()
}

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.