Python 1.2Free video12 minLesson 2 of 6 in Module 1
Run Your First Python Code
Run Python in a notebook and know what happens when a cell executes.
Free sample. Everything in this module opens with a free account.
Watch or read the lesson: Run Your First Python Code
01Your first line of Python
In the previous lesson, you created your first notebook in Google Colab. But you have not written any Python code in it yet.
In this lesson, you will write and run your first few lines of Python, learn how code cells work, and see what happens when Python runs into an error.
There is also something curious to watch out for. Sometimes a cell that was working perfectly well a minute ago suddenly stops working after you restart the notebook. Keep that in mind; this lesson comes back to it near the end.
Hello, world
Open a code cell and type this line:
print("Hello, world!")
To run the code in a cell, you have two options: click the run button next to the cell, or press Shift + Enter. Run it, and the output appears right below the cell:
Hello, world!
That is your first Python program. You write the code, run it, and read the output.
What that line does
Now look at what is actually happening in that one line.
First, there is print. In Python, print is a functionKey termA named piece of code that does one job. print's job is to display a value.: a named, reusable block of code that performs a particular task. The job of the print function is to display values as output.
Next, notice the round brackets, or parentheses, after print. Whatever you put inside those parentheses is passed to the function as an argument. Here the argument is "Hello, world!".
Because Hello, world! is written inside quotation marks, Python treats it as a stringKey termText, written in quotes: "Hello, world!". Its type is str.. A string is simply how Python represents text.
So this one line tells Python to call the print function and display the string "Hello, world!".
Forgetting the quotes
What happens if you remove those quotation marks? Open another code cell and write print(Hello), with no quotes this time:
print(Hello)
What do you think will happen when you run it? Think it through before reading on.
I have a guess. Show meHide the answer
You get an error. A NameError, to be precise:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[2], line 1
----> 1 print(Hello)
NameError: name 'Hello' is not defined
Python tells you that the name Hello is not defined.
Why Python looked for a name
Without the quotes, Python no longer sees Hello as a string. Instead, it treats Hello as a name, and it tries to find something that has been defined with that name. Nothing called Hello has been defined yet, and that is why you get a NameError.
Putting the quotes back tells Python that you mean the text "Hello", rather than a name it should look up.
The execution count
Go back to your first cell for a moment. Next to it, there is a number inside square brackets, like [1]. That is called the execution countKey termThe order in which cells ran: the number in square brackets beside a cell, such as [3]., and it tells you the order in which cells have been executed.
If the print("Hello, world!") cell was the first cell you ran, its execution count is 1. The next cell you run gets 2, and so on. That is also why the error above says Cell In[2]: the print(Hello) cell was the second cell to run.
The execution count is a notebook feature, and it might not seem especially important yet. But remember it, because it will help you understand something interesting about notebooks later in this lesson.
A calculation without print
So far, you have only printed text. But Python can also perform calculations.
Say you have just bought three things at a grocery store. Bread costs 2.25, milk costs 1.25 and eggs cost 3.50, and you want the total. Open a new cell and simply write the sum:
2.25 + 1.25 + 3.5
There is no print this time. So when you run this cell, will Python show the result or not? Think it through before reading on.
I have a guess. Show meHide the answer
You get 7.0, even without print:
7.0
That happens because you are working inside a notebook. When the last line of a code cell is an expression, Jupyter (the notebook system Colab is built on) automatically displays its result. An expression is a piece of code that evaluates to a value. This addition evaluates to 7.0, so that is the value displayed below the cell.
That automatic display is a notebook feature. In a regular Python script, nothing would appear; you would use print() to display the result.
Which Python are you running?
Before going any further, it is worth checking which version of Python you are running. Open another code cell, type import sys, and on the next line type sys.version:
import sys
sys.version
Run the cell, and you will see information about the Python version running in your current Colab session. The first part is the version number. Your text will be a little different from this; what matters is the number at the start, such as 3.12:
'3.12.14 (main, Sep 1 2026, 14:16:52) [Clang 22.1.3 ]'
The exact version can change as Colab updates its environment, but this course uses Python 3 throughout.
AI code suggestions
One more thing before you continue. While you are typing code in Colab, you might notice suggestions appearing in gray. This is Google's AI assistant.
It is a good idea to turn off AI code completion, at least while you are learning the fundamentals. Try writing the code yourself. Make mistakes, fix them, and understand why things work. Once you are comfortable reading and understanding Python, you can absolutely start using AI assistants to speed things up. For now, the focus is on building the foundation.
02Statements
You have written a few lines of Python now, so it is time to look more closely at how Python code is organized.
One of the first terms you will come across is a statement. A statementKey termOne instruction. Python executes a program's statements one at a time, from top to bottom. is an instruction that Python can execute. For example:
bread = 2.25
This cell displays nothing, because it does not end with an expression to show. It is an assignment statement: it assigns the value 2.25 to the name bread. From now on, whenever you use bread in your code, Python can look up the value associated with that name.
Naming the other prices
Do the same for the other items, milk = 1.25 and eggs = 3.5. Then you can write total = bread + milk + eggs, and evaluate total on the last line:
milk = 1.25
eggs = 3.5
total = bread + milk + eggs
total
7.0
Instead of writing the prices directly into the calculation, you are now using names to refer to those values. Variables and assignment get a much closer look in the next lesson. For now, the important idea is what a statement is.
Normally, you write one statement per line, and Python executes the statements in the order you run them.
A statement across several lines
What if a statement becomes really long? Python allows you to split a statement across several physical lines. For example, you can write the calculation inside parentheses, with each item on a separate line:
total = (
bread
+ milk
+ eggs
)
total
7.0
Python understands that the expression continues until the parentheses are closed. So even though the code takes up several lines on the screen, Python treats it as one logical line: a single assignment statement, with the same result as before.
03Comments
Now for another important part of writing readable code: comments.
Here is the thing about programming. When you write code today, it might seem completely obvious what everything does. But come back to that same code a few weeks later, and you may find yourself wondering why you wrote it that way. And if someone else reads your code, they need to understand it too.
That is where comments come in. A commentKey termText after #, skipped when the code runs. A comment over several lines starts each line with its own #. is text you add to your code to explain something.
The hash sign
In Python, a comment starts with a hash sign, #. So above the grocery calculation, you could write a comment saying what the next lines do:
# Calculate the total cost of the three items
total = bread + milk + eggs
total
7.0
The calculation still runs and gives the same result, because Python ignores the comment when it executes the code. The comment is there for the people reading the code, not for the computer.
Comments at the end of a line
You can also put a comment at the end of a line of code:
bread = 2.25 # price of bread
Everything after the hash sign, up to the end of that line, is treated as a comment. Python runs bread = 2.25 and skips the rest.
What if you want to write a longer comment? You can simply use several lines, each starting with a hash sign:
# Calculate the total cost
# of the three grocery items
Triple quoted strings
You might also see text written between three quotation marks in Python code, sometimes spread over several lines. People occasionally call these "multiline comments". But technically, they are not comments. They are multiline strings, and Python evaluates them like any other string. You can see that in a notebook: a triple quoted string on the last line of a cell is displayed as a value, which a comment never is.
"""text"""
'text'
When they are used in certain places, these strings can serve as documentation strings, or docstrings. You will meet those properly when you get to functions. For now, just remember that regular Python comments start with a hash sign.
04The kernel and execution order
Remember the question from the beginning? Why can a cell that worked perfectly well suddenly fail after you restart a notebook?
To understand that, you need to know about something called the kernel. This is an important concept, especially if you are going to use notebooks for data science and machine learning.
When you write code in a notebook, the notebook itself is not what executes your Python code. Instead, the code is sent to a program called the kernelKey termThe program that runs a notebook's cells and keeps the names they create. Restarting it deletes every name.. The kernel is responsible for executing that code and returning the result. It also keeps track of the names and values you have defined. That is its current state.
That is why, once you have run bread = 2.25, another cell can use bread without defining it again: the kernel remembers it.
Restarting the kernel
Now see what happens to that state when you restart the kernel. Suppose you have one cell that defines bread, milk and eggs:
bread = 2.25
milk = 1.25
eggs = 3.50
And another cell that calculates the total:
total = bread + milk + eggs
total
7.0
Everything works. Now restart the kernel. In Colab, you do that from the Runtime menu by choosing Restart session.
Once the session has restarted, do not run the cell that defines the prices. Instead, go directly to the cell that calculates total. The code is still there. You can clearly see bread, milk and eggs defined in the cell above it.
Will the calculation work just because those assignments are still visible? Think it through before reading on.
I have a guess. Show meHide the answer
No. You get an error, a NameError again:
total = bread + milk + eggs
total
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[1], line 1
----> 1 total = bread + milk + eggs
2 total
NameError: name 'bread' is not defined
Python tells you that bread is not defined. Writing code in a cell and executing it are two different things. The assignment has not been run since the restart, so the kernel has no value for bread. Notice also the In[1]: after a restart the execution count starts again from 1.
Reading a traceback
Look at that error message for a moment. This block of information is called a tracebackKey termPython's report of a failed statement. Read it from the bottom: the last line names the error, and the arrow points at the line that failed.. A traceback helps you understand where an error occurred and what caused it.
When you are just starting out, these messages can look a little intimidating, but there is a simple way to approach them:
- Start with the last line. It usually tells you the type of error and gives a description of what went wrong. Here, the last line says
NameErrorand names the missing name:bread. - Then look above it to see which line of code caused the problem. In a notebook, the relevant line is often marked with an arrow,
---->, pointing at the statement that failed.
So even though the error might look complicated at first, it is giving you useful information. Learning to read tracebacks is an important skill throughout this course.
Fixing the order
Back to the notebook. To fix this, run the cell that defines the prices first, then run the calculation again:
bread = 2.25
milk = 1.25
eggs = 3.50
total = bread + milk + eggs
total
7.0
Define the names, then use the names.
Restart and run all
There is an even better habit to develop when you work with notebooks. Before trying it, fix the cell where you deliberately left the quotes out: change print(Hello) to print("Hello"), so that example no longer raises an error.
Now restart the kernel and run all the cells from top to bottom. In Colab, you will find this under Runtime, as the option to restart the session and run all cells. The cells run in order:
print("Hello")
Hello
bread = 2.25
milk = 1.25
eggs = 3.50
total = bread + milk + eggs
total
7.0
This gives you a clean starting point. Every name gets defined in the intended order, and every result is generated from the code that is currently in the notebook.
Why the order matters
Why is that so important? Because notebooks let you run cells in almost any order. You can run the last cell first, go back to the second cell, change something in the middle, and then run another cell. After a while, the state of the kernel might not match what you would expect just by looking at the notebook.
For example, you might change a value in an earlier cell but forget to run it again. Say you edit the definitions cell so that the first line reads bread = 4.25, and do not run it:
bread = 4.25
milk = 1.25
eggs = 3.50
Then you run the calculation:
total = bread + milk + eggs
total
7.0
The notebook shows the new value, 4.25, but the kernel is still using the old one, 2.25, because editing code does not execute it. That can lead to some very confusing results and a lot of wasted time.
Restarting and running all the cells checks whether the current code works in order, without depending on names left over from earlier experiments. After a restart and run all, the definitions cell runs first, with bread = 4.25, and the calculation uses the code you can actually see:
total = bread + milk + eggs
total
9.0
This is also where the execution count becomes useful. It shows the order in which cells were executed: after a restart and run all, the definitions cell shows [1] and the calculation shows [2]. If the counts are all over the place, that is a clue that the cells were not run in the same order they appear on the page.
05Recap and challenge
You can now run code in a notebook, display results with print or as the last expression of a cell, and add comments with the hash sign. You have seen that a statement is one instruction, that you normally write one per line, and that parentheses let one statement span several lines.
When something fails, read the last line of the traceback, then find the statement that caused it.
And remember the distinction this lesson tested: code you can see in the notebook is not the same as code the kernel has executed. The kernel's current state holds only what has actually been run, which is why Restart and run all is such a useful habit.
Your challenge
- Create a new notebook for a trip to the cinema.
- In the first code cell, define the prices of three tickets.
- In the second cell, calculate their total cost.
- Add a comment to every line explaining what that line does.
Next comes a closer look at variables: what actually happens when you write something like bread = 2.25, and how Python keeps track of the objects and names in your program.
Key terms: Run Your First Python Code
The words this lesson introduces, each in one line. The module’s glossary collects them all, and the AI glossary has every term across the courses.
- comment
- Text after
#, skipped when the code runs. A comment over several lines starts each line with its own#. - execution count
- The order in which cells ran: the number in square brackets beside a cell, such as
[3]. - function
- A named piece of code that does one job.
print's job is to display a value. - kernel
- The program that runs a notebook's cells and keeps the names they create. Restarting it deletes every name.
- statement
- One instruction. Python executes a program's statements one at a time, from top to bottom.
- string
- Text, written in quotes:
"Hello, world!". Its type isstr. - traceback
- Python's report of a failed statement. Read it from the bottom: the last line names the error, and the arrow points at the line that failed.
Quiz: Run Your First Python Code
Your first pick on each question is the one that counts. Getting one wrong here is how the lesson sticks.