On this page
  1. Welcome
  2. Part 1 · print()
  3. Part 2 · Variables
  4. Part 3 · Data types
  5. Part 4 · Input
  6. Part 5 · Conditionals
  7. Part 6 · For loops
  8. Common mistakes
  9. What to do next
  10. Practice questions
  11. Studio
  12. Python lab
  13. Quizzes
  14. Challenges

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:

Hello, world!

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:

I am 12 years old

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:

Aisha 12 Aisha is 12

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:

10 10

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:

10 5
💡 Remember the order: save → overwrite → restore.

Rules for naming variables

✅ Allowed❌ Not allowed
name, age, high_scorehigh score (no spaces)
player1, total_marks1player (can't start with a number)
_secretmy-score (no hyphens)
print, if, for (these are Python keywords)

Good habits:

  • Use names that describe what's stored: total_cost is better than x.
  • Use lowercase letters and underscores, e.g. number_of_lives.
  • Python is case-sensitive: Score and score are 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 typePython nameWhat it storesExamples
IntegerintWhole numbers7, -3, 0, 2026
FloatfloatNumbers with a decimal point3.14, -0.5, 2.0
StringstrText (letters, digits, symbols)"Hello", "Y7", "123"
BooleanboolOnly True or FalseTrue, 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:

OperatorMeaningExampleResult
+Add7 + 29
-Subtract7 - 25
*Multiply7 * 214
/Divide7 / 23.5
//Integer division (whole part only)7 // 23
%Remainder (modulus)7 % 21
**Power7 ** 249
💡 Normal division / 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.

FunctionConverts toExampleResult
int()Integerint("25")25
float()Floatfloat("2.5")2.5
str()Stringstr(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:

What is your name? Leo Hello, Leo
⚠️ Important: 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:

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than5 > 8False
<Less than5 < 8True
>=Greater than or equal to5 >= 5True
<=Less than or equal to9 <= 5False
⚠️ Don't mix them up: = 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:

It's hot today! Remember your water bottle. Have a nice day.

Two very important rules:

  1. The if line ends with a colon :
  2. The code that belongs to the if is indented (moved in by 4 spaces or one Tab). Python uses indentation to know which lines are "inside" the if.

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:

OperatorMeaningExampleResult
andBoth must be True5 > 3 and 2 > 1True
orAt least one must be True5 > 3 or 2 > 9True
notFlips True ↔ Falsenot TrueFalse
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:

Hello Hello Hello Hello Hello

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:

Loop number 0 Loop number 1 Loop number 2 Loop number 3 Loop number 4
💡 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()

CodeNumbers producedExplanation
range(5)0, 1, 2, 3, 4Start at 0, stop before 5
range(1, 6)1, 2, 3, 4, 5Start at 1, stop before 6
range(0, 11, 2)0, 2, 4, 6, 8, 10Start at 0, stop before 11, step by 2
range(10, 0, -1)10, 9, 8, …, 1Count 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:

The total is 15

How it works (1 + 2 + 3 + 4 + 5):

Loopnumbertotal after the loop
1st11
2nd23
3rd36
4th410
5th515

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:

1 is odd 2 is even 3 is odd ... 10 is even

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

MistakeExampleFix
Forgetting the colonif x > 5if x > 5:
Missing indentationif x > 5:
print("Big")
Indent print by 4 spaces
Using = instead of ==if x = 5:if x == 5:
Forgetting to convert inputage = input("Age? ") then age + 1age = int(input("Age? "))
Joining string and number"Score: " + 10"Score: " + str(10)
Wrong capitalsprint(true) / Print("hi")True, print
Missing quotesprint(Hello)print("Hello")
Off-by-one in rangerange(1, 10) to count to 10range(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.

Well done for finishing the tutorial! Use the studio to type and run code with your teacher. Then try the practice questions, the quizzes, the Python lab, and the harder challenges.