Visualise Python Example 1

Understanding all the details of how an algorithm works can be challenging, and it is helpful to be able to perceive what is happening from multiple angles. One particularly useful tool to help with understanding algorithms is a visualisation which shows you clearly the values of the variables and the relationships between them as you step through a program.

A great example of such a tool for Python is provided online by CS Circles. With this excellent tool, you can either paste your own code into the editor and step through it, or trace some of the interesting example programs provided. These range from very basic to quite advanced and include:

  • Beginner programs
  • Math-Related Fun
  • Object-Oriented Programming:
  • Linked Lists
  • and more…

Basic Example of Tracing Python Code

Check out the visualisation for this simple example program:

x = [1, 2, 3]
y = [4, 5, 6]
z = y
y = x
x = z

x = [1, 2, 3] # a different [1, 2, 3] list!
y = x
x.append(4)
y.append(5)
z = [1, 2, 3, 4, 5] # a different list!
x.append(6)
y.append(7)
y = "hello"


def foo(lst):
    lst.append("hello")
    bar(lst)

def bar(myLst):
    print(myLst)

foo(x)
foo(z)

Visualise Python Example 1

You can see that you get a clear picture of frames and the objects associated with them. Don’t worry if you don’t know what frames and objects are – the picture makes it clear what is happening. The global frame simply means the variables available to the entire program as opposed to local function variables.

Tracing Fizz Buzz in Python Using a Visualisation Tool

As well as showing the variables at play in a program, the visualisation tool highlights the current line in the program as you step through the code. This is very useful for understanding program flow, including what is happening in terms of selection (AKA if...then statements).

Check out the visualization for the classic Fizz Buzz coding challenge:

for i in range(1, 51):
    if i % 3 == 0 and i % 5 == 0:
        print("fizzbuzz")
    elif i % 5 == 0:
        print("buzz")
    elif i % 3 == 0:
        print("fizz")
    else:
        print(i)

BTW, you can even generate a URL for a specific program which you can share with others or use yourself to get back to where you were quickly if you need to. The URL for the program above is here, and contains the entire program encoded as part of itself.

Fizz Buzz Python


This article has shown you a useful online Python code visualisation tool and how you can use it to better understand algorithms written in Python.

Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Join our mailing list

Join our mailing list to receive awesome articles about learning Python and Computer Science in a fun and accessible way, straight to your inbox.