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
print("Hello, world!")
print("My name is Sam")Text must go inside quotation marks. Numbers do not need them.
print(42)
print("42") # this is text, not a numberVariables
A variable stores a value under a name.
name = "Aisha"
age = 12
height = 1.52The 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_nameorfirstName - Case sensitive:
Scoreandscoreare different variables - Choose names that say what they hold
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.
- print() is a function: it displays whatever is inside the brackets.
- Text goes inside quote marks. Text in quotes is called a string.
- Anything after a # is a comment. Python ignores it: it is a note for people.
- Run it and the output appears. Python works from the top, one line at a time.
- = stores a value in a variable: the name on the left, the value on the right.
- A variable is a labelled box with a name, a value and a data type.
- The value can change. age = age + 1 takes the 15 out and puts 16 in.
- A constant holds a value that must never change. By convention it is written in capitals.
- Names use letters, digits and underscores. No spaces, and no digit first.
Input and data types
Getting input
name = input("What is your name? ")
print("Hello " + name)Even if the user types 7, Python stores it as the text "7", not the number 7. That single fact causes most beginner bugs.
age = input("How old are you? ")
print(age + 1) # ERROR, you cannot add 1 to textThe fix is to convert it:
age = int(input("How old are you? "))
print(age + 1) # worksThe main data types
| Type | Holds | Example |
|---|---|---|
int | Whole numbers | 7, -3, 0 |
float | Numbers with decimals | 3.14, 1.5 |
str | Text, called a string | "hello", "7" |
bool | True or False | True, False |
Converting
int("7") # the number 7
float("3.5") # the number 3.5
str(7) # the text "7"Joining text and numbers
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 youStep 1 of 5 input() always hands back text, even when the user typed a number.
- The user types an answer at the console.
- input() always hands it back as text, a string, even when it looks like a number.
- int() turns the text into a whole number, so it can be used in sums.
- Skip the conversion and + joins text instead of adding: "15" + "1" is "151".
- int() turns text into a whole number.
- int() on a float cuts off the decimals. It does not round.
- str() turns a number into text.
- float() turns text into a decimal number.
- input() always returns text, so convert it before doing sums.
- A conversion that does not make sense raises an error, so validate first.
Making decisions
if statements
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:
- The colon at the end of the
ifline - The indentation of the lines underneath, four spaces
- Two equals signs for comparison, one for assignment
Comparison operators
| Operator | Means |
|---|---|
== | 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
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.
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 message | What it usually means |
|---|---|
SyntaxError: invalid syntax | Missing colon, or missing bracket |
IndentationError | The lines under an if or a loop are not indented consistently |
NameError: name 'x' is not defined | Variable used before it was created, or a typo in the name |
TypeError: can only concatenate str | Trying to join text and a number without converting |
ValueError: invalid literal for int() | Trying to convert text like "hello" into a number |
- The code: if, elif and else test one condition after another.
- Follow the value 65 down: each test is True or False, in order.
- The first True test runs its block, and the rest are skipped.
- So test the strictest condition first, or an easy one will catch everything.
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.
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
- 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.
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
print("7" + "3") display?age after age = input("Age? ") if the user types 14?if score = 10:?elif mean?if mark >= 30 before if mark >= 70. What happens with a mark of 85?3.5?str(42) produce?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.
- LThe input function returns a string
- LPython cannot add a number to a string
- LThe fix is to convert the input using int()
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.
- 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
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.
- Lint() converts a value into a whole number
- Lstr() converts a value into text or a string
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.
- 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
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.
- 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
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.