Study Guide

Writing Your First Python Programs

How to move from block-based programs to Python: printing, typing in text and numbers, variables, converting with int(), arithmetic, choosing with if, elif and else, and reading the error messages that tell you what went wrong.

Lesson 5.18 Algorithms and Programming

For: Key Stage 3 learners (about ages 11 to 14) who have used a block-based language such as Scratch, or have met variables and IF in pseudocode

Stage: Think

A program made of blocks

In a block-based language such as Scratch, a program is built by snapping coloured blocks together. Here is a small fictional program, described in words. It has three blocks, one under the other:

  1. when green flag clicked starts the program.
  2. ask “What is your name?” and wait shows the question, waits for the player to type, and keeps what was typed in a built-in value called answer.
  3. say (join “Hello, ” (answer)) for 2 seconds makes the sprite say the two pieces of text joined together.

Think it through

A player types Mina. What does the sprite say? Then say how you would change the program so that it also asks for the player’s age and says it back.

Show a model answer

The sprite says “Hello, Mina” (the comma and the space come from the text “Hello, ”). To use the age as well, you would add another ask block, and because answer is replaced each time somebody types, you would keep the name in a variable block before asking the second question. Text-based programs have the same two ideas, joining text and keeping a value somewhere safe, written as words instead of blocks.

Stage: Discover

The same program in words and symbols

A textual language is one where you type the program instead of snapping blocks together. Python is a high-level textual language that is popular for learning and for real work. The program above looks like this in Python:

name = input("What is your name? ")
print("Hello, " + name)

Think it through

Look at the two Python lines beside the three blocks. Which line do you think matches the ask block, and which matches the say block? What do you think the name on the left of the = sign is for?

Show a model answer

The first line matches the ask block: input shows the question and waits for typing. The second matches the say block: print shows text. In the first line, name is a name the programmer chose for a place that keeps what was typed, a variable. In the blocks, the built-in value answer did that job; in Python you choose the name yourself.

Block-based ideaIn PythonWhat it does
ask … and wait, then answername = input("What is your name? ")Shows the question, waits, and stores the typed text in name
say (…)print("Hello")Shows something on the screen
join “Hello, ” and (answer)"Hello, " + nameSticks pieces of text together
set score to 0score = 0Stores a value in a variable
if … then … elseif …: and else:Chooses between instructions

Python reads your program and carries it out one line at a time, from the top.

You can type and run every program in this lesson in any free Python environment, such as an online editor or a copy installed on your computer. You do not need one: every question can be answered by reading the program and working out what it does, on paper, which is also a good way to learn. If you do run a program, check it against your prediction first.

Check your understanding

Which line of Python does the same job as the ask “What is your name?” and wait block, including keeping what was typed?
Show the answer

Answer: C. name = input("What is your name? ")

input is the Python version of ask and wait; the variable on the left is where the answer is kept.

Stage: Predict

Here are three print lines. Nothing else is in the program.

print("Hello")
print(3 + 4)
print("3 + 4")

Think it through

Without running it, predict what the program shows on the screen, line by line. Are all three lines different?

Show what happens

It shows three lines: Hello, then 7, then 3 + 4. Text inside quotation marks is shown exactly as written. Without quotation marks, Python works out the calculation first and shows the answer.

Text in quotation marks is called a string: the characters are kept as they are, and Python never tries to calculate them. A number with no quotation marks is an integer if it is a whole number, such as 7 or -3, and Python can calculate with it.

Which line makes Python show exactly the characters 2 + 5 on the screen?
Show the answer

Answer: B. print("2 + 5")

Quotation marks mean “this is text”. No quotation marks mean “work this out”.

Stage: Explain

Variables: storing a value

In Python a variable is made the moment you first store something in it. There is no DECLARE line:

score = 10
print(score)

shows 10. The single = does not mean “is equal to”. It means “work out the right-hand side, then store the result in the name on the left”. That is the job of ← in pseudocode.

A variable name uses letters, digits and underscores, with no spaces, and does not start with a digit. Capital letters matter: Score and score are two different variables.

Check your understanding

What does this program show?
Show the answer

Answer: D. It shows 15, because the right side is worked out first and then stored.

score = 10
score = score + 5
print(score)

The right-hand side is always worked out first, using the old value, and then the result is stored.

Stage: Predict

What input() gives back

A fictional leisure centre asks for a visitor’s age, then says how old they will be next year.

age = input("How old are you? ")
print("Next year you will be", age + 1)

Think it through

A visitor types 12. Predict what the program shows. Does it show 13, or something else, and why might that be?

Show what happens

It does not show 13. Python stops with an error: TypeError: can only concatenate str (not "int") to str. What the keyboard sends is text, the characters 1 and 2, and input always gives that text back as a string. The + tries to join a string and a whole number, which Python will not do.

input() always gives back a string, even when the visitor types digits. To use the text as a whole number, convert it with int():

age = int(input("How old are you? "))
print("Next year you will be", age + 1)

Now typing 12 shows Next year you will be 13. The inside call input(...) runs first and gives the text “12”; then int turns it into the whole number 12.

Think it through

What does print(“5” + “3”) show, and what does print(5 + 3) show? Why are they different?

Show what happens

"5" + "3" shows 53: with strings, + sticks the pieces together. 5 + 3 shows 8: with integers, + adds. The same symbol does two jobs, and which one it does depends on whether the values are text or numbers.

Check your understanding

The program above crashed. Which version of its first line fixes it, so that age + 1 works?
Show the answer

Answer: A. age = int(input("How old are you? "))

Convert what input() returns, not the question.

Stage: Predict

Arithmetic

Think it through

You know from pseudocode that DIV(7, 2) is 3 and MOD(7, 2) is 1. What do you think Python shows for print(7 / 2): 3, 3.5 or something else?

Show what happens

It shows 3.5. Python’s / is an ordinary division and gives a decimal result, even when the division is exact. To get DIV and MOD, Python uses different symbols, // and %.

The Python symbols are + add, - subtract, * multiply, / divide (decimal answer), // whole-number division (DIV), % remainder (MOD) and ** power. Brackets work as in maths, and *, /, // and % are done before + and -.

What each line shows
Python lineWhat it shows
print(3 + 4)7
print(10 - 4 * 2)
print((10 - 4) * 2)
print(7 // 2)
print(7 % 2)
print(2 ** 3)
print(20 / 4)

    Show the completed table
    Python lineWhat it shows
    print(3 + 4)7
    print(10 - 4 * 2)2
    print((10 - 4) * 2)12
    print(7 // 2)3
    print(7 % 2)1
    print(2 ** 3)8
    print(20 / 4)5.0

    The first row is given as an example.

    Check your understanding

    What does print(20 / 4) show?
    Show the answer

    Answer: B. 5.0, because / always gives a decimal number.

    / always gives a decimal result; // gives the whole-number part.

    Stage: Predict

    Choosing: if, elif and else

    A fictional quiz club awards a badge from a score out of 10.

    score = int(input("Quiz score out of 10: "))
    if score >= 9:
        print("Gold")
    elif score >= 6:
        print("Silver")
    else:
        print("Keep practising")

    Think it through

    A player scores 7. Predict what the program shows. Then say which lines were not carried out at all, and why.

    Show what happens

    It shows Silver. The first condition, score >= 9, is false, so its print is skipped. The second, score >= 6, is true, so Silver is shown. The else branch is not carried out, because a branch only runs when none of the conditions above it was true.

    Three details matter, and they replace the words THEN and ENDIF of pseudocode:

    • A colon : ends each if, elif and else line.
    • The instructions that belong to a branch are indented, usually by four spaces. Where the indent stops, the branch stops.
    • To test whether two values are equal, Python uses ==, with two equals signs. A single = stores a value.

    Do not confuse: One equals sign or two

    What does it do?=
    Stores a value in a variable. The right-hand side is worked out first.score = 10
    What does it do?==
    Asks whether two values are equal, and gives True or False. Used in conditions.if score == 10:

    In pseudocode the same two jobs are done by ← and =.

    What the quiz program shows for each score
    The player typesThe program shows
    10Gold
    9
    6
    5
    0

      Show the completed table
      The player typesThe program shows
      10Gold
      9Gold
      6Silver
      5Keep practising
      0Keep practising

      The first row is given as an example. The boundary scores, 9 and 6, are the ones to check carefully.

      Stage: Discover

      Reading an error message

      A program that breaks the rules of Python does not run properly. Python then shows an error message: a report of what it could not do, and which line it was on. It is information, not a telling-off. Here are four, with the line each came from.

      print(scor)
      NameError: name 'scor' is not defined
      
      if int(age) >= 13
      SyntaxError: expected ':'
      
      print("5" + 3)
      TypeError: can only concatenate str (not "int") to str
      
      if int(age) >= 13:
      print("Welcome")
      IndentationError: expected an indented block after 'if' statement

      Think it through

      Without being told, match each error message to its cause: a missing colon, a variable name that was never given a value, an indent missing under an if, and a number added to a string. What in each message helped you?

      Show a model answer

      NameError is the variable name that was never given a value (here scor, probably a typing slip for score). SyntaxError: expected ':' is the missing colon. TypeError is a number added to a string. IndentationError is the missing indent under the if. The first word names the kind of mistake; the rest describes it; and the lines above the message give the line number to look at first.

      To read an error message, work from the last line upwards: the last line names the kind of error and says what went wrong, and the line above it shows the line of your program that Python was on. Python can only report where it noticed the problem, so the mistake may be on the line before.

      Check your understanding

      Python says: NameError: name 'scor' is not defined. What is the most likely cause?
      Show the answer

      Answer: A. scor was used, but only score was given a value, so it is probably a typing slip.

      A NameError is nearly always a spelling or capital-letter slip, or a variable used before it was given a value.

      Check your understanding

      A program has a missing colon on line 3 and a misspelt variable on line 6. Python is asked to run it. What happens?
      Show the answer

      Answer: C. A SyntaxError for line 3, before any line runs, because Python reads the whole program first.

      Fix errors from the top, one at a time, and run again: fixing one often reveals the next.

      Stage: Apply

      Mend a broken program

      Here is a fictional program from a pupil, Ali, who wants a welcome message for people aged 13 or over. It has two mistakes, and Python would report them one at a time.

      nmae = input("Your name? ")
      age = input("Your age? ")
      if int(age) >= 13
          print("Welcome, " + name)

      Think it through

      Find the mistakes, say which error message each would cause and in which order Python would show them, and write the corrected program. Check by predicting what it shows for Ali, aged 14.

      Show a model answer

      First, the if line has no colon, so Python shows SyntaxError: expected ':' before running anything. After adding the colon, the program runs, but line 1 stores the name in nmae, so the last line shows NameError: name 'name' is not defined. A corrected program:

      name = input("Your name? ")
      age = input("Your age? ")
      if int(age) >= 13:
          print("Welcome, " + name)

      For Ali, aged 14, it shows Welcome, Ali. The indent under if was already right; if it were missing, Python would show an IndentationError instead.

      Mia (fictional) wants a program that adds two numbers typed by the user:

      a = input("First number: ")
      b = input("Second number: ")
      print(a + b)

      When the user types 5 and then 3, the program shows 53, not 8.

      Apply it

      What is the best change to make the program show 8?
      Show the answer

      Answer: D. Wrap each input in int(), so that + adds numbers instead of joining text.

      The mistake is not in print or +: it is that input gave text, so + joined the characters “5” and “3”.

      Stage: Apply

      Write a program of your own

      A fictional museum charges by age. Under 5 is free. From 5 to 15 inclusive, a child ticket. Aged 16 or over, an adult ticket.

      Think it through

      Write a Python program that asks for the visitor’s age, as a whole number, and shows Free, Child ticket or Adult ticket. Predict what it shows for the ages 4, 5, 15 and 16.

      Show a model answer
      age = int(input("Age? "))
      if age < 5:
          print("Free")
      elif age < 16:
          print("Child ticket")
      else:
          print("Adult ticket")

      For 4 it shows Free. For 5 it shows Child ticket, because 5 is not less than 5 but is less than 16. For 15 it also shows Child ticket. For 16 it shows Adult ticket, because 16 is not less than 16, so neither condition holds and the else runs. The elif does not need to say “at least 5”, because it can only be reached when the first condition was false.

      Zara (fictional) writes a grade program like this:

      mark = int(input("Mark: "))
      if mark >= 40:
          print("Pass")
      elif mark >= 70:
          print("Merit")
      else:
          print("Fail")

      A pupil types 75 and sees Pass.

      Apply it

      Why does 75 show Pass, and not Merit?
      Show the answer

      Answer: A. The first condition is true for 75, so Pass is shown and the elif is never checked.

      When conditions overlap, put the most specific one (the highest mark here) first.

      Stage: Consolidate

      Show what you know

      Think it through

      Explain to a friend who only knows Scratch how a small program in Python is like a block program and how it is different. Mention input, a variable and what a colon and an indent do.

      Show a model answer

      A good answer says that both give instructions in order and have the same ideas: showing something (say, print), asking and waiting (ask, input), keeping a value (a variable), and choosing (if, if/elif/else). They differ in that Python is typed, so spelling, colons and indents have to be exactly right: the colon starts a branch, and the indent shows which lines belong to it. Python also reports an error message with the line it was on if a rule is broken, and input always gives text, so int() is needed for a number.

      A set of blocks, described in words (fictional): set score to 0; ask “Guess my number” and wait; if (answer = 7) then change score by 10; say (score). A pupil turns it into Python.

      Apply it

      Which Python program does the same as the blocks?
      Show the answer

      Answer: C. score = 0, then answer = int(input("Guess my number: ")), then if answer == 7: score = score + 10, then print(score)

      Three details have to be right together: int() around input, == in the condition, and print at the end.

      Think it through

      Which part of this lesson are you least sure about? Write one question you would ask your teacher.

      Show a model answer

      There is no wrong answer. Two questions worth asking: “how do I know whether to use = or ==?” (= stores a value, == asks a question) and “how do I read a long error message?” (start with the last line, then the line number).

      • Python is a textual language. print(…) shows something, input(…) asks and waits, and name = … stores a value in a variable. Text in quotation marks is a string; a whole number is an integer.
      • input() always gives a string. Use int() to turn it into a whole number before doing arithmetic with it. "5" + "3" is 53; 5 + 3 is 8.
      • Arithmetic uses + - * /, with // for whole-number division, % for the remainder and ** for a power. / always gives a decimal.
      • if, elif and else choose between branches, each line ending in a colon, with the branch indented. == compares and = stores. Conditions are checked from the top and only the first true branch runs.
      • An error message is information: read the last line first, then the line number. A SyntaxError stops the program from starting; a NameError is usually a typing slip; a TypeError is values of the wrong kind combined.

      Sources and scope

      • What this lesson is. The eighteenth lesson of the Algorithms and Programming module, written for this site. It is a first step from block-based programs, which are described in words only, to a textual language. Its curriculum links are provisional and imply no review or endorsement by any examination board; the Cambridge points are marked as supporting because the examinations are answered in pseudocode.
      • Original material. The greeting program, the leisure centre, the quiz club, the museum and Ali, Mia and Zara are fictional, written for this lesson. Every program was run in Python, and its output, and the wording of each error message, was checked; the exact wording of an error message can differ a little between versions of Python.
      • Simplified on purpose. Only whole numbers are converted (int()), and a user typing something that is not a number, which causes a ValueError, is not treated. Python’s f strings, float() and other string tools are left out. Loops, lists and functions are in Lesson 19.
      • Left to later lessons. Loops, lists, functions and a modular program (Lesson 19).