All 1.1 16 min read 10 question quiz 14 exam marks

First Steps: Output, Comments and Errors

Your first program, how to read an error message instead of panicking at it, and the habits that will save you hours later.

Your first program

Python
print("Hello, world!")

That is a complete program. Run it and the text appears.

What each part does

  • print is a function, a built in piece of code that does a job
  • The brackets hold what you are giving it
  • The quotation marks mark the start and end of the text

Printing several things

Python
print("Hello", "world", "again")
print("The answer is", 42)
print("Line one")
print("Line two")

A comma puts a space between items and lets you mix text and numbers freely.

Comments

A comment is a note for humans. Python ignores everything after a #.

Python
# Ask the player for their name
name = input("Name: ")     # input always gives back text

Comment why, not what. count = count + 1 # add one is useless. # skip the header row is worth having.

Your first program: print, a string and a commentA small Python program in a code editor, with its output beside it. The line print, bracket, quote Hello comma world quote, bracket is a function call: print is the function, the brackets hold what it is given, and the text inside the quote marks is a string. After it, a hash starts a comment, which Python ignores and which is there for the people reading the code. Pressing Run makes the program execute from the top, one line at a time, and the output appears in the console: Hi Asha and then Hello, world! The first print shows two things at once, a string and the variable name, separated by a space.hello.py1name = "Asha"2print("Hi", name)3print("Hello, world!")   # a greetingprint()a function thatshows what isin the brackets"text"text goes insidequote marks: itis called a string# commentPython ignores it:a note for peoplereading the codeRunoutputHi AshaHello, world!Python reads your program from the top,one line at a time.1234
  1. print() is a function: it displays whatever is inside the brackets.
  2. Text goes inside quote marks. Text in quotes is called a string.
  3. Anything after a # is a comment. Python ignores it: it is a note for people.
  4. Run it and the output appears. Python works from the top, one line at a time.
Every program starts like this: a command, brackets, and what to show.

Reading error messages

Beginners see a red error and panic. Experienced programmers read it, because it usually says exactly what is wrong and on which line.

  File "main.py", line 4
    print("Hello"
                 ^
SyntaxError: '(' was never closed

That tells you the file, the line, the position and the problem.

The errors you will meet first

ErrorUsual cause
SyntaxErrorA missing bracket, quote or colon
IndentationErrorLines under an if or a loop are not lined up
NameErrorA variable used before it exists, or a typo in its name
TypeErrorMixing incompatible types, such as text plus a number
ValueErrorThe right type but an impossible value, such as int("hello")
ZeroDivisionErrorDividing by zero
The rule that saves the most time

Read the last line of the error first. It names the problem. Then read the line number. Fix that line before looking anywhere else.

Three habits worth building now

  1. Run your code often. After every few lines, not after fifty. Then you know exactly what broke it.
  2. Name things properly. total_score is better than ts every single time.
  3. Print things to check. If you are unsure what a variable holds, print it. This is the single most useful debugging technique there is, and professionals still use it daily.
The three kinds of error: syntax, runtime and logicThe three kinds of programming error, one card each, each with its own bug. A syntax error breaks the rules of the language, like print with an opening bracket that is never closed. The translator cannot understand the line, reports a SyntaxError and the program will not start. A runtime error happens while the program is running: dividing 10 by 0 makes the program start and then crash on that line with a ZeroDivisionError. A logic error is the hardest to find because nothing crashes: the program average equals a plus b divided by 2 runs happily and prints 8.0, when the average of 4 and 8 is 6.0, because division is done before addition. Only testing against the answer you expected finds it.Syntax errora typo in the rules of the languageprint("Hello"resultSyntaxError:'(' was never closedfound how?found before it runs,by the translatorRuntime errorthe program starts, then crashesx = 10 / 0resultZeroDivisionError:division by zerofound how?found while it runs:it stops on that lineLogic errorruns fine, gives a wrong answera, b = 4, 8average = a + b / 2print(average)result8.0(should be 6.0)found how?found only by testing againstthe answer you expected123
  1. Syntax error: the code breaks the rules of the language, so it will not run at all.
  2. Runtime error: the program starts, then crashes when it meets something it cannot do.
  3. Logic error: it runs without complaint but gives the wrong answer, so only testing finds it.
A program that runs is not a program that is right. Test the answers, not only the absence of crashes.

Key terms you must be able to define

Function
A named piece of code that performs a job, such as print.
Argument
A value you give to a function inside its brackets.
String
Text data, written inside quotation marks.
Comment
A note in the code for humans, ignored by Python, starting with a hash.
Syntax error
A mistake in how the code is written, which stops it running at all.
Runtime error
An error that occurs while the program is running, such as dividing by zero.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

DefineFunction
AnswerA named piece of code that performs a job, such as print.
DefineArgument
AnswerA value you give to a function inside its brackets.
DefineString
AnswerText data, written inside quotation marks.
DefineComment
AnswerA note in the code for humans, ignored by Python, starting with a hash.
DefineSyntax error
AnswerA mistake in how the code is written, which stops it running at all.
DefineRuntime error
AnswerAn error that occurs while the program is running, such as dividing by zero.

Reach the top grade on this topic

Getting good at Python early is mostly about habits rather than knowledge.

  • Run your code every few lines so you always know what broke it
  • Read the last line of an error message first, then the line number
  • Use full descriptive variable names from the very beginning
  • Print variables when you are not sure what they contain
  • Comment why you did something, never what the line obviously does

Mistakes that cost marks here

Avoid these
  • Forgetting the quotation marks around text.
  • Forgetting a closing bracket, which produces a syntax error on the following line.
  • Ignoring the error message and just changing things at random.
  • Writing fifty lines before running any of it.
Fun fact

The tradition of making Hello World your first program comes from a 1972 tutorial by Brian Kernighan. Over fifty years later it is still the first thing almost every programmer ever writes.

Knowledge check

0 of 10 answered
1What does print("Hello") do?
2What symbol starts a comment in Python?
3Which error means you used a variable that does not exist?
4What does print("Score", 10) display?
5What kind of error is a missing colon at the end of an if line?
6Which is the best comment?
7What causes a ValueError in int("hello")?
8Why should you run your code frequently?
9What does the last line of an error message tell you?
10Which variable name is best?
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

14 marks
1State the purpose of a comment in a program.2 marks
State

Mark scheme0 / 2
  • LA note for humans reading the code
  • LIgnored by the computer when the program runs
Model answer

A comment is a note written in the code to explain something to a person reading it, such as why a particular approach was taken. It is completely ignored by Python when the program runs, so it has no effect on what the program does.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Explain the difference between a syntax error and a runtime error, giving an example of each.4 marks
Explain

Mark scheme0 / 4
  • LA syntax error breaks the rules of the language
  • LSo the program will not run at all
  • LA runtime error occurs while the program is running
  • LGives valid examples such as a missing bracket and dividing by zero
Model answer

A syntax error is a mistake in the way the code is written, such as a missing closing bracket or a missing colon at the end of an if statement. Because the code does not follow the rules of the language, Python cannot interpret it at all and the program will not run, so the error appears before anything happens. A runtime error occurs in code that is perfectly valid but which fails while it is executing, for example dividing by zero or trying to convert the text hello into a number. The program starts normally and then crashes at the point the problem occurs.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3A student writes print("Hello) and gets an error. Identify the error and correct it.2 marks
Identify

Mark scheme0 / 2
  • LThe closing quotation mark is missing
  • LCorrect code is print("Hello")
Model answer

The string has an opening quotation mark but no closing one, so Python reaches the end of the line still expecting the text to continue and reports a syntax error. The corrected line is print("Hello") with a closing quotation mark before the closing bracket.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4Explain why printing the value of a variable is a useful way to find errors in a program.3 marks
Explain

Mark scheme0 / 3
  • LIt shows what the variable actually contains at that point
  • LThis may be different from what the programmer assumed
  • LIt narrows down which part of the program is wrong
Model answer

Printing a variable shows exactly what it holds at that moment in the program, which is frequently not what the programmer assumed it held. Many bugs come from a variable containing text when a number was expected, or holding a value from an earlier iteration, and these are invisible just by reading the code. By printing values at several points, the programmer can see where the value first becomes wrong, which narrows the problem down to a small section rather than the whole program.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5Write a program that displays your name and your favourite subject on two separate lines, with a comment explaining what it does.3 marks
Write

Mark scheme0 / 3
  • LIncludes a comment
  • LUses print correctly with quotation marks
  • LProduces output on two separate lines
Model answer

# Display some information about me print("My name is Aisha") print("My favourite subject is Computing") The comment on the first line explains the purpose of the program and is ignored when it runs. Each print statement outputs its text and then moves to a new line, so using two separate print statements produces two lines of output.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 14