On this page
Year 7
Python: variables, data types, conditionals and loops
Welcome to Python! In this tutorial you will learn how to display messages, store information, use data types, ask for input, make decisions, and repeat code with loops. Each section has examples you can type in and run. When you finish, try the practice questions and the quizzes.
- Display messages with
print() - Store information in variables
- Use different data types
- Ask the user for input
- Make decisions with conditionals (
if,elif,else) - Repeat code with for loops
Part 1: Your first program, print()
The print() function displays something on the screen.
print("Hello, world!")
Output:
Text inside quotation marks is printed exactly as you write it. You can use "double" or 'single' quotes, but you must use the same kind at both ends.
You can print several things at once by separating them with commas. Python adds a space between each one:
print("I am", 12, "years old")
Output:
Comments
A line starting with # is a comment. Python ignores it. Comments are notes for humans that explain what the code does.
# This line is a comment and will not run
print("This line will run")
Part 2: Variables
A variable is like a labelled box that stores a value. You give the box a name, then put something inside it.
name = "Aisha"
age = 12
The = sign means "store this value in this variable". It does not mean "equals" like in maths.
Now we can use the variables:
name = "Aisha"
age = 12
print(name)
print(age)
print(name, "is", age)
Output:
Changing a variable
You can change a variable's value at any time. The old value is replaced.
score = 10
print(score) # 10
score = 25
print(score) # 25
score = score + 5
print(score) # 30
score = score + 5 means: "take the current value of score, add 5, and store the answer back in score."
Swapping two variables
Sometimes you want two variables to swap values — so a gets what was in b, and b gets what was in a.
This naive attempt looks right, but it fails:
a = 5
b = 10
a = b # a is now 10 … the original 5 is lost
b = a # b becomes 10 as well
print(a, b) # 10 10
Output:
When a = b runs, the old value of a is overwritten. There is nowhere left to put it into b.
Use a third variable, usually called temp, to keep a copy first:
a = 5
b = 10
temp = a # 1. save a's value
a = b # 2. overwrite a
b = temp # 3. put the saved value into b
print(a, b) # 10 5
Output:
Rules for naming variables
| ✅ Allowed | ❌ Not allowed |
|---|---|
name, age, high_score | high score (no spaces) |
player1, total_marks | 1player (can't start with a number) |
_secret | my-score (no hyphens) |
print, if, for (these are Python keywords) |
Good habits:
- Use names that describe what's stored:
total_costis better thanx. - Use lowercase letters and underscores, e.g.
number_of_lives. - Python is case-sensitive:
Scoreandscoreare two different variables!
Part 3: Data types
Every value in Python has a data type. The type tells Python what kind of value it is and what you can do with it. These are the four main types you need to know:
| Data type | Python name | What it stores | Examples |
|---|---|---|---|
| Integer | int | Whole numbers | 7, -3, 0, 2026 |
| Float | float | Numbers with a decimal point | 3.14, -0.5, 2.0 |
| String | str | Text (letters, digits, symbols) | "Hello", "Y7", "123" |
| Boolean | bool | Only True or False | True, False |
lives = 3 # int
price = 4.99 # float
player = "Ben" # str
game_over = False # bool
"5" (in quotes) is a string, while 5 (no quotes) is an integer. They look similar but Python treats them very differently!True and False must start with a capital letter.Checking the type
Use type() to find out a value's data type:
print(type(42)) # <class 'int'>
print(type(3.5)) # <class 'float'>
print(type("hi")) # <class 'str'>
print(type(True)) # <class 'bool'>
Arithmetic operators
You can do maths with int and float values:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Add | 7 + 2 | 9 |
- | Subtract | 7 - 2 | 5 |
* | Multiply | 7 * 2 | 14 |
/ | Divide | 7 / 2 | 3.5 |
// | Integer division (whole part only) | 7 // 2 | 3 |
% | Remainder (modulus) | 7 % 2 | 1 |
** | Power | 7 ** 2 | 49 |
/ always gives a float, even when it divides evenly: 10 / 2 gives 5.0.% is great for checking if a number is even: if number % 2 is 0, the number is even.Python follows the usual maths order (BIDMAS): 2 + 3 * 4 gives 14, not 20. Use brackets to change the order: (2 + 3) * 4 gives 20.
Working with strings
You can join strings with + (this is called concatenation):
first = "Super"
second = "Hero"
print(first + second) # SuperHero
print(first + " " + second) # Super Hero
You can repeat a string with *:
print("Ha" * 3) # HaHaHa
You can find the length of a string with len():
print(len("Python")) # 6
Type conversion (casting)
Sometimes you need to change a value from one type to another.
| Function | Converts to | Example | Result |
|---|---|---|---|
int() | Integer | int("25") | 25 |
float() | Float | float("2.5") | 2.5 |
str() | String | str(99) | "99" |
This matters because you can't join a string and a number with +:
age = 12
print("I am " + age) # ❌ ERROR! Can't add str and int
print("I am " + str(age)) # ✅ I am 12
print("I am", age) # ✅ I am 12 (commas work too)
Watch out for this difference:
print("5" + "5") # 55 (joining two strings)
print(5 + 5) # 10 (adding two numbers)
Part 4: Getting input from the user
The input() function lets the user type something in.
name = input("What is your name? ")
print("Hello,", name)
Example run:
Output:
input() always gives you a string, even if the user types a number.To do maths with the input, convert it first:
age = int(input("How old are you? "))
print("Next year you will be", age + 1)
Use float() instead of int() if the user might type a decimal:
height = float(input("Enter your height in metres: "))
print("Your height in cm is", height * 100)
Part 5: Conditionals (making decisions)
Programs often need to make decisions. For example, if the player has 0 lives, then end the game.
Comparison operators
These compare two values and give a Boolean (True or False) answer:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 5 > 8 | False |
< | Less than | 5 < 8 | True |
>= | Greater than or equal to | 5 >= 5 | True |
<= | Less than or equal to | 9 <= 5 | False |
= stores a value, while == compares two values.The if statement
temperature = 30
if temperature > 25:
print("It's hot today!")
print("Remember your water bottle.")
print("Have a nice day.")
Output:
Two very important rules:
- The
ifline ends with a colon: - The code that belongs to the
ifis indented (moved in by 4 spaces or one Tab). Python uses indentation to know which lines are "inside" theif.
The last line isn't indented, so it always runs.
if ... else
else runs when the condition is False:
age = int(input("Enter your age: "))
if age >= 13:
print("You can create an account.")
else:
print("Sorry, you are too young.")
if ... elif ... else
elif is short for "else if". Use it when there are more than two possibilities:
mark = int(input("Enter your test mark (0-100): "))
if mark >= 80:
print("Grade: A")
elif mark >= 60:
print("Grade: B")
elif mark >= 40:
print("Grade: C")
else:
print("Grade: Keep trying!")
Python checks each condition from top to bottom and runs only the first one that is True. If the mark is 85, it prints "Grade: A" and skips the rest, even though 85 is also >= 60.
Logical operators: and, or, not
These combine conditions:
| Operator | Meaning | Example | Result |
|---|---|---|---|
and | Both must be True | 5 > 3 and 2 > 1 | True |
or | At least one must be True | 5 > 3 or 2 > 9 | True |
not | Flips True ↔ False | not True | False |
age = 12
has_ticket = True
if age >= 12 and has_ticket:
print("You can watch the film.")
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
Comparing strings
== compares strings exactly, including capital letters:
password = input("Enter password: ")
if password == "python123":
print("Access granted")
else:
print("Access denied")
"Python123" would not match "python123", because the capital P is different.
Part 6: For loops (repeating code)
Imagine printing "Hello" 100 times. Writing print("Hello") 100 times would be boring! A loop repeats code for us.
for loops with range()
for i in range(5):
print("Hello")
Output:
Just like if, the for line ends with a colon : and the code to repeat is indented.
The variable i is the loop counter. It changes each time the loop runs:
for i in range(5):
print("Loop number", i)
Output:
range(5) counts 0, 1, 2, 3, 4. It starts at 0 and stops before 5. That still makes 5 repeats.The three forms of range()
| Code | Numbers produced | Explanation |
|---|---|---|
range(5) | 0, 1, 2, 3, 4 | Start at 0, stop before 5 |
range(1, 6) | 1, 2, 3, 4, 5 | Start at 1, stop before 6 |
range(0, 11, 2) | 0, 2, 4, 6, 8, 10 | Start at 0, stop before 11, step by 2 |
range(10, 0, -1) | 10, 9, 8, …, 1 | Count down with a negative step |
Examples:
# Count from 1 to 10
for number in range(1, 11):
print(number)
# Countdown
for n in range(5, 0, -1):
print(n)
print("Blast off! 🚀")
# The 7 times table
for i in range(1, 13):
print(i, "x 7 =", i * 7)
Using a variable to keep a running total
A common pattern is to start a total at 0 and add to it each time round the loop:
total = 0
for number in range(1, 6):
total = total + number
print("The total is", total)
Output:
How it works (1 + 2 + 3 + 4 + 5):
| Loop | number | total after the loop |
|---|---|---|
| 1st | 1 | 1 |
| 2nd | 2 | 3 |
| 3rd | 3 | 6 |
| 4th | 4 | 10 |
| 5th | 5 | 15 |
This kind of table is called a trace table. It is a useful way to work out what a program does.
Letting the user choose how many times to loop
times = int(input("How many stars? "))
for i in range(times):
print("*")
Combining loops and conditionals
You can put an if inside a for loop. Notice the extra indentation:
for number in range(1, 11):
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")
Output:
Here is a mini quiz game that uses everything from this tutorial:
score = 0
for question in range(1, 4):
answer = int(input("What is " + str(question) + " x 5? "))
if answer == question * 5:
print("Correct!")
score = score + 1
else:
print("Wrong! The answer was", question * 5)
print("You scored", score, "out of 3")
Common mistakes checklist
| Mistake | Example | Fix |
|---|---|---|
| Forgetting the colon | if x > 5 | if x > 5: |
| Missing indentation | if x > 5:print("Big") | Indent print by 4 spaces |
Using = instead of == | if x = 5: | if x == 5: |
| Forgetting to convert input | age = input("Age? ") then age + 1 | age = int(input("Age? ")) |
| Joining string and number | "Score: " + 10 | "Score: " + str(10) |
| Wrong capitals | print(true) / Print("hi") | True, print |
| Missing quotes | print(Hello) | print("Hello") |
Off-by-one in range | range(1, 10) to count to 10 | range(1, 11) |
What to do next
You have finished the tutorial lessons. Next, try the written practice questions (Sections A–D), or open the quizzes page for multiple-choice tests and a link to those questions.