Python
jupyter notebook
google-colab
A notebook (like Jupyter Notebook or Google Colab) is an interactive environment where you can write and execute code in cells.
Unlike traditional code files (.py
in Python, for example), where all the code is executed from top to bottom in a single file, in a notebook you can execute different parts of the code at different times and in any order.
When you execute a cell in a notebook, the code inside that cell is executed and stored in memory. This means that if you define a variable or import a library in one cell, you can use it in another cell without needing to repeat the import or definition.
In one cell, we can import a library like math
:
1import math # We import the math library
Then, in a different cell, we can use math.sqrt()
, even though we haven't rewritten import math
:
1print(math.sqrt(25)) # Works because math is already imported in memory
If we try to use something before executing it, we will get an error.
❌ Typical Error:
1print(math.sqrt(25)) # ERROR: math is not imported yet
✅ Solution
First, execute the cell where we import math
, then execute the cell with print(math.sqrt(25))
.
💡 Key Rule: The code you execute in a cell becomes available throughout the notebook, but only after you execute it.
Follow these steps to better understand how the notebook works:
random
library:1import random
random.randint(1, 10)
:1numero = random.randint(1, 10) 2print("Random number:", numero)
Execute the second cell without having executed the first one. What happens?
Now execute the first cell and then re-execute the second one.
💡 In conclusion, if you execute a cell with an import or a variable, it is stored in the notebook's memory, meaning you can use what you defined in any other cell, as long as you have executed the cell that defined it first. If you close the notebook or restart the kernel, you will lose everything that was in memory and will need to re-execute the necessary cells.