Statements and Expressions
Level 1 · What a program is
The two kinds of piece every line of code is made of. What a keyword is, why comments matter, and how to try a line out first.
Course contentsLesson 3 of 18
Level 1 · What a program is
Level 2 · Values and variables
Level 3 · Decisions and loops
Level 4 · Functions
Level 5 · Errors and debugging
Level 6 · Good code habits
After this lesson you can
- Tell a statement from an expression
- Spot a keyword in a line of Python
- Write a comment that helps the next reader
10 mincovers 5 glossary entries
Worth reading first: Hello World in Python
What a statement is, and what an expression is
Code is made of two kinds of piece. A statement is one whole step, such as print("Hi"). An expression is a piece that works out to one value, such as 3 + 4, which works out to 7. Most statements have expressions inside them, the way a sentence has words inside it.
In Python, each statement usually sits on its own line. The program runs them from the top down, one at a time. A line like total = 3 + 4 is a statement. The 3 + 4 part is an expression. Python works out the expression first, then finishes the step.
Some words have a fixed job in the language. These are keywords, such as if, for, while, def and return. Python 3 has 35 of them. You cannot use one as a name for your own things, because Python would not know which job you meant.
A comment is a note for people. In Python it starts with a # sign, and Python skips everything after it on that line. A good comment says why the code does something, not what it does. The code already shows what. Only a person can explain why.
There is a quick way to try a single line. Type python on its own and you get a REPL, which stands for read, evaluate, print, loop. It waits at a >>> sign. Type 3 + 4 and it prints 7 straight away. It is ideal for testing one expression before it goes in a file.
The REPL shows the value of an expression without a print. A script does not. If a script holds the line 3 + 4, Python works it out and then throws it away. Nothing appears. To see a value from a script, wrap it in print.
A common mistake is a comment that repeats the code, like # add 1 above count = count + 1. It adds noise and goes stale when the code changes. Write fewer comments, and make each one say something the code cannot.
>>> 3 + 4
7
>>> total = 3 + 4 # a statement with an expression inside
>>> total
7
>>> if = 5
SyntaxError: invalid syntaxWorked example
The words for this lesson5
Check yourself
Which of these is an expression?
Finished this lesson?
Marking it complete also marks its 5 glossary entries learned, which updates your roadmap and your saved page. 0 are already marked.