Topic 0.6
Anatomy of a Python Program
In one line
A Python program is a sequence of statements that run from top to bottom. Indentation (four spaces) is part of the grammar and shows which lines belong together, # starts a comment, and capital and small letters are different.
Think of it like this
An outline with sub-points. In written notes you push sub-points to the right under their heading, and everyone understands they belong to it. Python uses exactly that idea as grammar: lines pushed to the right belong to the line above them that ends with a colon.
Words you'll meet
New words in this topic, in plain English. Come back here whenever one feels fuzzy.
- Statement
- One complete instruction, usually one line.
- Block
- A group of indented lines that belong to the line above them ending in a colon.
- Indentation
- The spaces at the start of a line. Python uses it to decide which block a line is in.
- Comment
- A note starting with
#. Python ignores it; people read it. - Case-sensitive
- Capital and small letters count as different, so
Totalandtotalare different names. - Whitespace
- Spaces, tabs and line breaks.
- Colon
- The
:character. At the end of a line it announces that an indented block follows. - Keyword
- A word with a fixed meaning in Python, such as
if,fororelse. You cannot use keywords as names.
Step by step
01Statements run top to bottom
This program has three statements. Python runs the first, then the second, then the third. The blank line and the comment are skipped.
price = 40 remembers 40 under the name price (a variable, Topic 1.1). * multiplies. Notice the spaces around = and *. They are optional and make the line easier to read.
price = 40
# two items at the same price
total = price * 2
print("Total:", total)02A colon starts a block
An if statement runs some lines only when a condition is true. A condition is a question with a yes or no answer; here temperature > 30 asks "is the temperature greater than 30?". The if line ends with a colon, and the lines it controls are indented by four spaces. Those two indented lines are the block.
The last line is back at the left edge, so it is not part of the block. It runs whatever the temperature is.
temperature = 31
if temperature > 30:
print("It is hot.") # in the block
print("Drink some water.") # in the block
print("Have a good day.") # after the block: always runs03Indentation changes the meaning
Move one line left by four spaces and the program means something else. Below, Drink some water. is no longer inside the if, so it prints on cold days too.
No error appears, because both versions are valid Python. Indentation is not decoration: it is how you tell Python what belongs to what.
temperature = 12
if temperature > 30:
print("It is hot.")
print("Drink some water.") # moved left: now always runs
print("Have a good day.")04Blocks inside blocks
A block can contain another line ending in a colon, which starts a deeper block, indented by four more spaces. Each level of indentation is one level of "belongs to".
In this example for day in ["Sat", "Sun"]: runs its block once for each day in the list. day == "Sun" asks "is day equal to Sun?" (two equals signs ask a question; one equals sign remembers a value).
Read the left edge of the code like a staircase: every step right goes inside something, every step left comes back out.
for day in ["Sat", "Sun"]:
print(day) # level 1: inside the for
if day == "Sun":
print(" Rest day") # level 2: inside the if, inside the for
print("Done") # level 0: after everything05Comments
Everything after a # on a line is ignored. A comment can have its own line or follow code on the same line. A # inside quotes is ordinary text, not a comment.
Programmers also "comment out" a line (put # in front of it) to switch it off for a moment without deleting it.
# Prices include tax, so no tax is added here.
price = 40 # rupees
print("Item #1:", price) # the # inside the quotes is just text
# print("This line is switched off")06Long statements across lines
Inside brackets, a statement may run over as many lines as you like. Use this for long lists and long sums. A comma after the last item is allowed and makes adding another line easier. The square brackets in the second part make a list, a row of values (Phase 4).
Outside brackets, a backslash \ at the very end of a line also continues it, but brackets are the preferred way. Python also allows two statements on one line separated by ;, and you should almost never do that.
total = (10
+ 20
+ 30)
print(total)
names = [
"Asha",
"Ravi",
"Meera",
]
print(names)07Capital letters matter
Name and name are different names. If you store a value as Name and then ask for name, Python says it has never heard of name. Recent versions even suggest the name you probably meant.
By convention, ordinary names in Python are written in small letters with underscores between words, like total_price. Topic 1.1 covers naming.
Name = "Asha"
print(name) # NameError: name 'name' is not defined. Did you mean: 'Name'?Try it yourself
- 1
Move a line in and out
In the first example, set
temperature = 12. Run it. Then remove the four spaces beforeprint("Drink some water.")and run again. Explain the difference in the output in one sentence. - 2
Go one level deeper
In the second example, add a line
print(" Sleep late")so that it prints only on Sunday, straight afterRest day. How many spaces does it need at the start? - 3
Switch a line off
In the third example, put a
#in front ofprint(total)and run it. Then remove the#from the switched-off line and run again.
Code & diagrams
Change 31 to 12 and predict the output before running. Which line still prints?
Expected output
It is hot.
Drink some water.
Have a good day.Count the spaces at the start of each line: 0, 4 or 8. Each level is one more "inside".
Expected output
Sat
Sun
Rest day
DonePython skips comments and blank lines. Inside brackets, one statement can cover several lines.
Expected output
Item #1: 40
60
['Asha', 'Ravi', 'Meera']Break it on purpose
Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.
Break #1
Indent a line for no reason
Put two spaces in front of the second line of a simple program.
print("start")
print("oops")Break #2
Come back to an indentation that doesn't exist
Indent a block by four spaces, then indent the next line by only two.
if True:
print("a")
print("b")Break #3
Forget the colon
Write an if line without the colon at the end.
if 5 > 3
print("yes")Myth vs fact
Myth
Indentation in Python is just for neatness.
Fact
It is grammar. Changing the indentation changes which lines belong to an if or a loop, and so changes what the program does.
Myth
Tabs and spaces are the same thing.
Fact
They are different characters that can look identical. Mixing them in one block gives TabError: inconsistent use of tabs and spaces in indentation. Use four spaces everywhere.
Myth
More comments always make code better.
Fact
A comment that repeats the code (# add 1 to x) is noise and goes stale. Comment the reasons and the surprises; let clear names explain the rest.
Myth
Python needs a main function like Java or C.
Fact
A Python file runs from its first line. The if __name__ == "__main__": pattern you will see later (Topic 6.2) is a convention for files that are also imported, not a requirement.
Pro corner
Extra depth for experienced readers. New to this? Skip it for now and come back later.
- ▸
The tokenizer turns indentation into explicit INDENT and DEDENT tokens before the parser sees the code. That is why an indentation mistake is reported as a syntax-level error before any line of the file runs.
- ▸
Inside brackets, indentation is not significant at all, which is why multi-line lists, calls and expressions can be laid out freely. Formatters such as Ruff (Topic 11.6) apply one consistent layout so that teams never argue about it.
- ▸
A lone string at the top of a file, function or class is a docstring, not a comment: it is stored on the object as
__doc__and shown byhelp(). Triple-quoted strings used to "comment out" code are real expressions that Python evaluates and discards. - ▸
The first line of a script on macOS and Linux is often
#!/usr/bin/env python3, a "shebang" that lets the file be run directly. To Python it is just a comment.
Remember this
- 1
A program is made of statements, normally one per line. There is no semicolon at the end of a line. You also don't need a wrapping
mainfunction (languages such as Java and C require one). Python starts at the first line of the file and works downward. - 2
Indentation is syntax. A line ending in a colon (
:), such as anif(makes a decision) or afor(repeats lines), starts a block: the group of lines it controls. Phase 2 teaches both. The block is every following line that is indented further. The block ends at the first line that returns to the earlier indentation. Other languages mark blocks with{and}; Python uses the spaces themselves. - 3
The standard is four spaces per level. Every line in a block must be indented by exactly the same amount. Don't mix tabs and spaces: they can look identical on screen and Python rejects the mix. Any code editor set up for Python inserts four spaces when you press the Tab key.
- 4
A comment starts with
#and runs to the end of the line. Python ignores it completely; it is a note for human readers. Good comments explain why, not what. Blank lines are also ignored and are used to separate steps visually. - 5
Python is case-sensitive:
name,NameandNAMEare three different names, andprintworks whilePrintdoes not. Spaces inside a line mostly don't matter (2+3and2 + 3are the same); spaces at the start of a line always matter. - 6
A statement can continue over several lines when it is inside brackets:
( ),[ ]or{ }. Python knows the statement isn't finished until the bracket closes. This is the normal way to write a long list or a long calculation readably.
Explain it without notes
How does Python know which lines belong to an if?
What is the difference between a syntax mistake in indentation and a logic mistake in indentation?
What is a comment for, and what makes a good one?
How can one statement be spread over several lines?
Practice
Write a program that sets marks = 82. Only if marks >= 50, it prints Well done! and You passed. (two indented lines under an if). Then it always prints Report finished.
This program has two indentation mistakes. Line 1 is for n in [1, 2, 3]:, which repeats its block once for each number. Line 2 is print(n) with no spaces in front. Line 3 is print("Done") with four spaces in front. Fix the spaces so the program prints 1, 2, 3 and then Done once.
Write a list of five fruit names over five lines inside square brackets, then print the list.
Trade-offs
- ↔
Indentation as syntax. The code you see is the code Python runs: layout cannot lie about structure, and programs look alike across teams. The cost is that copying code from a web page or chat can silently damage the indentation, and you must fix it before it runs.
- ↔
Comments vs clear code. Comments explain intent but can go out of date. Clear names and small functions explain themselves and cannot go stale. Prefer clear code, and comment the why.
Done when you can
Done when you can point to the block of an
iforforand say where it ends.Done when you can predict how moving a line left or right changes a program.
Done when you can explain the three errors: unexpected indent, unindent does not match, expected ':'.
Done when you can write a comment and say what a good comment contains.
Done when you can split a long list over several lines.