ADVERTISEMENT

Google Collab How to show value of assignments?

The short answer is: you can not show output of assignments in Colab.

Your confusion comes from how Google Colab works. The original script is meant to run in IPython. But Colab is not a regular IPython. When you run IPython shell, your %config InteractiveShell.ast_node_interactivity options are (citing documentation)

‘all’, ‘last’, ‘last_expr’ , ‘last_expr_or_assign’ or ‘none’, specifying which nodes should be run interactively (displaying output from expressions). ‘last_expr’ will run the last node interactively only if it is an expression (i.e. expressions in loops or other blocks are not displayed) ‘last_expr_or_assign’ will run the last expression or the last assignment. Other values for this parameter will raise a ValueError.

all will display all the variables, but not the assignments, for example

x = 5
x
y = 7
y

Out[]:
5
7

The differences between the options become more significant when you want to display variables in the loop.

In Colab your options are restricted to ['all', 'last', 'last_expr', 'none']. If you select all, the result for the above cell will be

Out[]:
57

Summarizing all that, there is no way of showing the result of assignment in Colab. Your only option (AFAIK) is to add the variable you want to see to the cell where it is assigned (which is similar to regular print):

meter = UNITS.meter
second = UNITS.second
a = 9.8 * meter / second**2
a

Google Colab has not yet been upgraded to the latest IPython version- if you explicitly upgrade with

!pip install -U ipython 

then last_expr_or_assign will work.