KS3National Curriculum Y7.3 26 min read 10 question quiz 15 exam marks

Introduction to Python

Your first real code. Printing, variables, input, data types and simple if statements, with every common beginner error explained.

Output and variables

Printing

Python
print("Hello, world!")
print("My name is Sam")

Text must go inside quotation marks. Numbers do not need them.

Python
print(42)
print("42")     # this is text, not a number

Variables

A variable stores a value under a name.

Python
name = "Aisha"
age = 12
height = 1.52

The equals sign means put this value into this box. It does not mean the two sides are equal.

Rules for variable names:

  • Start with a letter
  • No spaces, use first_name or firstName
  • Case sensitive: Score and score are different variables
  • Choose names that say what they hold
Python
score = 0
score = score + 10     # score is now 10
print(score)

The line score = score + 10 looks strange in maths, but in programming it means: work out score + 10, then put the answer back into score.

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.
Variables as labelled boxes, with the code that makes themSix lines of code on the left and the boxes they create on the right. The equals sign is assignment: it stores the value on its right in the variable named on its left. Every variable is like a labelled box with a name, a value and a data type. name holds the string Asha, age holds the whole number 15, price holds the decimal 2.5 and passed holds True. The fifth line, age equals age plus one, takes the 15 out and puts 16 in, which shows that the value of a variable can change while its name stays the same. PI is a constant: a value that must never change, written in capitals by convention and shown with a padlock. A card at the bottom left gives the naming rules: use letters, digits and underscores, do not start with a digit and never use a space.variables.py1name = "Asha"2age = 153price = 2.504passed = True5age = age + 16PI = 3.14159Naming a variabletotal_scorewords joined by _age2digits are fine inside2nd_placecannot start with a digitmy scoreno spacesWhat the computer keepsname"Asha"strage16intreplaces 15price2.5floatpassedTrueboolPI3.14159a constant: never changes12345
  1. = stores a value in a variable: the name on the left, the value on the right.
  2. A variable is a labelled box with a name, a value and a data type.
  3. The value can change. age = age + 1 takes the 15 out and puts 16 in.
  4. A constant holds a value that must never change. By convention it is written in capitals.
  5. Names use letters, digits and underscores. No spaces, and no digit first.
The name stays. The value is what you can swap.

Input and data types

Getting input

Python
name = input("What is your name? ")
print("Hello " + name)
input always gives you text

Even if the user types 7, Python stores it as the text "7", not the number 7. That single fact causes most beginner bugs.

Python
age = input("How old are you? ")
print(age + 1)      # ERROR, you cannot add 1 to text

The fix is to convert it:

Python
age = int(input("How old are you? "))
print(age + 1)      # works

The main data types

TypeHoldsExample
intWhole numbers7, -3, 0
floatNumbers with decimals3.14, 1.5
strText, called a string"hello", "7"
boolTrue or FalseTrue, False

Converting

Python
int("7")        # the number 7
float("3.5")    # the number 3.5
str(7)          # the text "7"

Joining text and numbers

Python
score = 15
print("You scored " + str(score))     # convert the number to text first
print("You scored", score)            # or use a comma, which Python handles for you
Input, variables and data typesWhy input plus one is an error. The input function always returns text, so after age equals input, a user who typed fourteen leaves the string quote fourteen quote in memory, with type str, not the number fourteen. Printing age plus one then raises a TypeError, because Python will not guess: it cannot add the number one to a word. Wrapping the input in int converts the text to a whole number, so age holds fourteen as an int and age plus one gives fifteen. The four main types are int for whole numbers such as seven or minus three, float for numbers with a decimal point such as three point one four, str for text including the digits quote seven quote, and bool for True or False. The same conversion applies when printing: joining a number onto text with a plus sign needs str around the number, or you can pass both to print separated by a comma and Python handles it.The single most common beginner bugage = input("How old are you? ")# the user types 14IN MEMORYage"14"type: strThose quote marks are the whole problem. 14 went in, "14" came out.age = input("How old are you? ")print(age + 1)TypeErrorcan only concatenatestr to str, not intPython will not guess. "14" is a word and 1 is a number.age = int(input("How old are you? "))print(age + 1) # 15IN MEMORYage14type: intint() around the input. Three characters, and most of your bugs go away.intwhole numbers7 -3 0floatnumbers with a decimal point3.14 1.5strtext, called a string"hello" "7"boolTrue or False, nothing elseTrue FalseNote the fourth row: "7" is a str and 7 is an int. They are not the same thing.score = 15print("You scored " + score) # TypeErrorprint("You scored " + str(score)) # converts it firstprint("You scored", score) # or let the comma do itA plus sign joins two strings. A comma prints two things with a space between.
If an error message mentions str and int in the same sentence, you have forgotten a conversion.
input() gives text, so convert it before doing sumsThe journey of one typed answer. The program asks How old are you, and the user types 15. The input function always gives back text, so the variable age holds the string 15 in quote marks, not the number. Passing it through int turns the text into the whole number 15, which can now be added to, so age plus one gives 16. The code on the bottom left does exactly that in three lines. The trap on the right shows what happens if the conversion is forgotten: adding the text 15 and the text 1 with a plus sign joins them into 151, whereas adding the numbers 15 and 1 gives 16.consoleHow old are you?15the user types 15age"15"strinput() always gives textint()age15intnow it can be added upage + 1 gives 16age.py1age = input("How old are you? ")2age = int(age)3print("Next year you will be", age + 1)The trap"15" + "1"15 + 1= "151"= 16joined, not addedarithmeticforget int() and + joins text1234
  1. The user types an answer at the console.
  2. input() always hands it back as text, a string, even when it looks like a number.
  3. int() turns the text into a whole number, so it can be used in sums.
  4. Skip the conversion and + joins text instead of adding: "15" + "1" is "151".
If the answer is going into a calculation, convert it as you take it in.
Casting between types: int, float and str, and when it failsCasting converts a value from one data type to another. int of the text 42 gives the whole number 42. int of 3.7 gives 3, because it cuts off the decimal part and does not round. str of the number 5 gives the text 5, so it can be joined to words. float of the text 3.14 gives the decimal number 3.14. The input function always gives back text, so a number typed by a user must be converted, as in age equals int of input. Some conversions fail: int of the text hello raises a ValueError, so input should be checked before it is converted.int("42")42stringint()42integertext to a whole numberint(3.7)3.7floatint()3integercuts off the decimal part: it does not roundstr(5)5integerstr()"5"stringa number to text, so it can be joined to wordsfloat("3.14")"3.14"stringfloat()3.14floattext to a decimal number1234input() always gives text5age = int(input("Age? "))print(age + 1)convert it before doing sums with itSome conversions fail6Output>>> int("hello")ValueError: invalid literalso check the input before converting it
  1. int() turns text into a whole number.
  2. int() on a float cuts off the decimals. It does not round.
  3. str() turns a number into text.
  4. float() turns text into a decimal number.
  5. input() always returns text, so convert it before doing sums.
  6. A conversion that does not make sense raises an error, so validate first.
Casting does not change the original. It makes a new value of the type you asked for.

Making decisions

if statements

Python
age = int(input("How old are you? "))

if age >= 13:
    print("You can have an account")
else:
    print("You are too young")

Three things to notice:

  1. The colon at the end of the if line
  2. The indentation of the lines underneath, four spaces
  3. Two equals signs for comparison, one for assignment

Comparison operators

OperatorMeans
==is equal to
!=is not equal to
<is less than
>is greater than
<=is less than or equal to
>=is greater than or equal to

More than two options

Python
mark = int(input("Enter your mark: "))

if mark >= 70:
    print("Excellent")
elif mark >= 50:
    print("Good")
elif mark >= 30:
    print("Keep working")
else:
    print("See your teacher")

elif means else if. Python checks each condition in order and runs the first one that is true, then skips the rest.

The order matters enormously

If mark >= 30 came first, a mark of 95 would print "Keep working", because 95 is greater than 30 and Python stops at the first true condition. Always put the most restrictive condition first.

Common beginner errors

Error messageWhat it usually means
SyntaxError: invalid syntaxMissing colon, or missing bracket
IndentationErrorThe lines under an if or a loop are not indented consistently
NameError: name 'x' is not definedVariable used before it was created, or a typo in the name
TypeError: can only concatenate strTrying to join text and a number without converting
ValueError: invalid literal for int()Trying to convert text like "hello" into a number
if, elif and else: the first true branch winsA grading program with the score 65, and the route that 65 takes. The first test, score greater than or equal to 70, is False, so the block that prints A is skipped. The second test, score greater than or equal to 60, is True, so its block runs and prints B. Because a branch has been chosen, the else is never reached. Only one branch of an if, elif and else ever runs, and it is the first one whose condition is True. That is why the order of the tests matters: if a test for 50 or more had been written first, a score of 90 would satisfy it and receive the lowest grade, so the strictest condition must come first.grade.py1score = 652if score >= 70:3    print("A")4elif score >= 60:5    print("B")6else:7    print("C")Where does 65 go?65score >= 70Falseskip "A"score >= 60Trueprints "B"elsenever reachedfirst True branch winsOrder mattersTest the strictest condition first.if score >= 50:   # catches 90 too!    print("C")a 90 would get the C: the first test is True1234
  1. The code: if, elif and else test one condition after another.
  2. Follow the value 65 down: each test is True or False, in order.
  3. The first True test runs its block, and the rest are skipped.
  4. So test the strictest condition first, or an easy one will catch everything.
Conditions are checked in order, and checking stops at the first one that is True.

Key terms you must be able to define

Variable
A named store for a value that can change while the program runs.
String
Text data, written inside quotation marks.
Integer
A whole number, with no decimal part.
Float
A number with a decimal part.
Input
Data entered by the user, which Python always stores as text.
Casting
Converting a value from one data type to another, such as int() or str().
Indentation
Spaces at the start of a line that tell Python which lines belong inside an if or a loop.
Syntax error
A mistake in the way the code is written, which stops the program running at all.

Flashcards

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

DefineVariable
AnswerA named store for a value that can change while the program runs.
DefineString
AnswerText data, written inside quotation marks.
DefineInteger
AnswerA whole number, with no decimal part.
DefineFloat
AnswerA number with a decimal part.
DefineInput
AnswerData entered by the user, which Python always stores as text.
DefineCasting
AnswerConverting a value from one data type to another, such as int() or str().
DefineIndentation
AnswerSpaces at the start of a line that tell Python which lines belong inside an if or a loop.
DefineSyntax error
AnswerA mistake in the way the code is written, which stops the program running at all.

Reach the top grade on this topic

Reaching the top level in Year 7 Python is about explaining what your code does, not just getting it to run.

Read error messages properly. They tell you the line number and the type of error. Learning to read them turns a frustrating hour into a two minute fix.

Test your program with awkward input. What happens if someone types letters when you asked for a number? What if they type nothing at all? Thinking about that is what separates a working program from a good one.

Explain your conditions. Why did you use >= rather than >? Because a mark of exactly 50 should count as a pass, and > would exclude it.

  • Write a program that asks for input, converts it and uses it in a calculation
  • Write an if elif else chain in the correct order and explain why the order matters
  • Identify the cause of each of the five common error messages
  • Explain what int() and str() do and when each is needed

Mistakes that cost marks here

Avoid these
  • Forgetting the colon at the end of an if line.
  • Using one equals sign in a condition when two are needed.
  • Forgetting to convert input to a number before doing arithmetic.
  • Indenting inconsistently, mixing tabs and spaces.
  • Putting elif conditions in the wrong order, so higher values are caught by the wrong branch.
Fun fact

Python was released in 1991 and its creator wrote most of it over a Christmas holiday. He named it after Monty Python, which is why the official documentation is full of references to spam and eggs.

Knowledge check

0 of 10 answered
1What does print("7" + "3") display?
2What is stored in age after age = input("Age? ") if the user types 14?
3Which line correctly converts input into a whole number?
4What is wrong with if score = 10:?
5What does elif mean?
6A program uses if mark >= 30 before if mark >= 70. What happens with a mark of 85?
7Which data type is 3.5?
8What causes a NameError?
9Why must lines inside an if statement be indented?
10What does str(42) produce?
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.

15 marks
1Explain why the following code causes an error: age = input("Age? ") then print(age + 1)3 marks
Explain

Mark scheme0 / 3
  • LThe input function returns a string
  • LPython cannot add a number to a string
  • LThe fix is to convert the input using int()
Model answer

The input function always returns a string, so age holds the text "14" rather than the number 14 even when the user types digits. Python cannot add the integer 1 to a string, so it raises a TypeError. The fix is to convert the input to a whole number as it is read, by writing age = int(input("Age? ")), after which the addition works correctly.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Write a Python program that asks the user for their name and their age, then prints a message saying whether they are old enough to watch a 12 rated film.5 marks
Write

Mark scheme0 / 5
  • LAsks for the name using input
  • LAsks for the age and converts it to an integer
  • LUses an if statement with a correct condition
  • LPrints a suitable message when old enough
  • LUses else to print a message when not old enough
Model answer

name = input("What is your name? ") age = int(input("How old are you? ")) if age >= 12: print(name + ", you can watch a 12 rated film.") else: print(name + ", you are too young for a 12 rated film.") The name is read as a string, which is correct because it is text. The age is converted to an integer so it can be compared with a number. The condition uses greater than or equal to, so someone who is exactly 12 is correctly allowed.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3State the purpose of the int() function and the str() function in Python.2 marks
State

Mark scheme0 / 2
  • Lint() converts a value into a whole number
  • Lstr() converts a value into text or a string
Model answer

The int() function converts a value into a whole number, which is needed when input has been read from the user as text but arithmetic or a numerical comparison has to be performed on it. The str() function does the opposite, converting a value such as a number into a string, which is needed when you want to join it to other text using the plus operator.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4A program should print 'Pass' for a mark of 50 or more and 'Fail' otherwise, but a mark of exactly 50 prints 'Fail'. Explain the likely cause and the correction.3 marks
Explain

Mark scheme0 / 3
  • LThe condition uses greater than rather than greater than or equal to
  • LA mark of exactly 50 is not greater than 50, so it fails the test
  • LChange the condition to mark >= 50
Model answer

The likely cause is that the condition has been written as if mark > 50 rather than if mark >= 50. A mark of exactly 50 is not greater than 50, so the condition is false and the else branch runs, printing Fail. The correction is to change the operator to greater than or equal to, writing if mark >= 50, so that a mark of exactly 50 is correctly counted as a pass.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5Explain why indentation matters in Python.2 marks
Explain

Mark scheme0 / 2
  • LIndentation shows which lines belong inside a structure such as an if statement or a loop
  • LIncorrect indentation causes an error or makes the program behave incorrectly
Model answer

In Python, indentation is not just formatting: it is how the language knows which lines belong inside an if statement, a loop or a function. Lines indented under an if only run when the condition is true, while a line that is not indented runs regardless. If the indentation is inconsistent Python raises an IndentationError and the program will not run at all, and if it is consistent but wrong the program will run while doing something the programmer did not intend.

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