Language structure

A language has words, grammar and meaning

Lexisthe words and symbols the language hasx = 5 $ 2$ is not a Python symbolSyntaxthe order the words must come inx = 5 +a + needs something after itSemanticswhat a correct sentence meansx = '5' + 2well formed, but text + number has no meaningA language has words, grammar and meaning.Python checks the first two before it runs anything, and reports both as a SyntaxError.A semantic error only shows when that line runs, or as a wrong answer with no error at all.

Lexis: the words. Syntax: the order. Semantics: the meaning.

Language structure · Going deeper

Four kinds of error

LevelThe ruleBroken byPython saysLexicalOnly known words and symbolsx = 5 $ 2SyntaxError, before runningSyntacticWords in a valid orderprint('a'SyntaxError, before runningSemanticThe statement must make sense'5' + 2TypeError, when the line runsSemanticIt must do what you meantarea = w + hNothing: the answer is wrongTwo are caught by Python before the program starts. The others are yours to find.A program that runs without an error is not yet a correct program.The exam uses all four words: lexis, syntax, semantics and, for wrong results, logic.

SyntaxError before running. The rest are yours to find.

Running code

A compiler translates first. An interpreter, as it runs.

CompilationSource codethe whole programCompilertranslates all of it, onceMachine code filemade for one platformRunno translator neededInterpretationSource codethe whole programInterpreterreads a statement, runs it, reads the nextRunas it is readA compiler translates first. An interpreter translates as it runs.Python is interpreted. To run a .py file the machine needs Python installed, and the same fileruns on any platform that has it. The price is speed: translation happens on every run.

Compiler: all at once. Interpreter: statement by statement.

Running code · Going deeper

What Python does with your file

Sourcehello.py:plain textCheckthe whole file'ssyntax, firstBytecodecompact steps forPython's machineRunone statementat a timeA syntax error: nothing runsprint('a')print('b'SyntaxErrorA run-time error: the lines before it ranprint('a')print(b)aNameErrorPython checks the whole file before the first line runs.So a missing bracket on the last line stops the first line from printing. A misspelt name isdifferent: it is only found when its line is reached, and everything above it has already happened.

Check all, then run line by line.

Check yourself

print('one')print(two)print('three')

What happens when this runs?

Program structure

Keywords are reserved. Every other name is yours.

ifkeywordcountidentifier>operator3literal:starts a blockcount > 3 is an expression: it works out to a value, True or Falsethe whole line, with its block, is a statement: it does somethingKeywords are reserved. Every other name is yours to choose.if is one of 35 keywords: words with a fixed job that you cannot use as a name. count is anidentifier: a name you made up. print is not a keyword. It is an ordinary name for a function.

Keyword, identifier, expression, statement.

Program structure · Going deeper

The 35 keywords

The 35 keywords of Python. The 24 in colour appear in the PCEP syllabus.FalseNoneTrueandasassertasyncawaitbreakclasscontinuedefdelelifelseexceptfinallyforfromglobalifimportinislambdanonlocalnotorpassraisereturntrywhilewithyieldKeywords are case-sensitive: True is a keyword, true is just a name.Only False, None and True start with a capital. Names such as print, len, int and input arenot keywords, so Python lets you reuse them, and then the original is hidden. Do not.

True, False, None have capitals. print is not one.

Indentation

Indentation is the block

for i in range(3): print(i)print('done')012donefor i in range(3): print(i) print('done')0done1done2doneIndentation is the block.The same three lines, and four spaces decide whether done prints once or three times.A header line ends with a colon. The lines indented under it belong to it, and the firstline back at the old level is outside it.

A colon opens a block. Four spaces put a line in it.

Indentation · Going deeper

Indentation errors

No block after a colonif x > 3:print(x)An indent with no headerx = 1 y = 2Stepping back to no levelif x > 3: print(x) print(y)expected an indented blockunexpected indentunindent does not matchAll three are an IndentationError, and none of the program runs.IndentationError is a kind of SyntaxError, so it is found in the check before the first line.Use four spaces for each level. Never mix tabs and spaces in one file.The amount is your choice, but every line of one block must use the same amount.

IndentationError: nothing runs.

Check yourself

x = 1 y = 2print(x)

What happens when this runs?

Comments

A comment is for the reader. Python skips it.

What you wroteWhat Python runs# price in penceprice = 250 # before tax# price = 300label = '#1 seller'print(price, label)price = 250label = '#1 seller'print(price, label)Output: 250 #1 sellerA comment is for the reader. Python skips it.A # starts a comment that runs to the end of the line. Put one in front of a statementto switch that line off without deleting it. Inside quotes, # is only a character.

# to the end of the line. Not inside quotes.

Comments · Going deeper

Using comments

UseHowExplain whyA short note above the code, on what it is forNote beside a lineAfter the statement, two spaces, then #Disable a linePut # in front of it; remove the # to bring it backSeveral linesA # on every line; Python has no block commentNot a commentA # inside a string literal is textCommenting a line out is the quickest way to test a program without it.An exam question may comment out one line of a loop or an if. Read every line's firstcharacter before you trace.

Explain, note, disable.

Check yourself

n = 10# n = n + 5n = n * 2 # doubleprint(n)

What does this print?

Lesson complete

You finished “How Python reads and runs a program”

Answer the questions along the way to see your score here.

Open in a new tab