From Blocks to Text: Your First Python
Python is a popular text-based programming language that is readable and powerful. You type the code instead of snapping blocks.
Printing
print("Hello, world!")
print() shows text on the screen. Text goes inside quotation marks.
Variables
name = "Sam"
age = 10
print(name)
A variable stores a value. Here name holds the text "Sam".
Maths
x = 5
y = x * 2
print(y)
This prints 10. Python uses + - * / for add, subtract, multiply and divide.
Input
name = input("What is your name? ")
print("Hello", name)
input() asks the user to type something.
Selection: if and else
score = 8
if score > 10:
print("Well done!")
else:
print("Keep trying!")
Notice the colon (:) and the indent (spaces) before the lines that belong to the if. In Python, the indent matters. This prints Keep trying!
Repetition: for loops
for i in range(5):
print("Hip hip hooray!")
This runs 5 times. range(5) counts from 0 to 4.
Comments
A line that starts with # is a comment. It is for humans to read, and the computer ignores it.
Errors
When Python cannot understand your code it shows an error message. A SyntaxError means you broke the rules, for example by forgetting a bracket or quotation mark. Read the message, find the line number, fix it and run again. Every programmer sees errors, and they are how we learn.
Curriculum link: National Curriculum in England: Computing programmes of study (DfE) — Key Stage 2: design, write and debug programs; use sequence, selection and repetition; work with variables and various forms of input and output