I1 · Python Programming for AI

Variables

A variable is a name that refers to a value stored in memory. It is created with the assignment operator =, which stores the value on the right under the name on the left. Assigning again replaces the value, so variables can change as the program runs.

8 min Intermediate Jump to the activity

What you need: The earlier topics of this module.

Definition

How does a game remember your score from one moment to the next?

A variable is a name that refers to a value stored in memory. It is created with the assignment operator =, which stores the value on the right under the name on the left. Assigning again replaces the value, so variables can change as the program runs.

In simple words

Think of a labelled box. score = 0 puts 0 in a box labelled score. score = score + 10 takes what is in the box, adds 10, and puts the result back. The label stays the same; what's inside changes.

Why it matters

Every program stores information: a user's name, a running total, a model's accuracy. Variables are how. Good names, such as total_marks instead of t, make code readable for others and for you next month.

How it works

Naming rules

  • Use letters, digits and underscores only, and don't start with a digit: score_2 is fine, 2score is not.
  • Names are case-sensitive: Score and score are different.
  • Don't use Python keywords such as if, for or class as names.
  • Use snake_case: words in lowercase joined by underscores.

= is not 'equals' as in maths. It means 'store'. x = x + 1 makes perfect sense in Python: it adds one to x.

In code

A score that changes as the game goes on.

score.py
score = 0
print("Start:", score)

score = score + 10      # a coin
score = score + 25      # a gem
score += 5              # += is a short way to add
print("After collecting:", score)

lives = 3
lives -= 1
print("Lives left:", lives)

player_name = "Aarav"
print(player_name, "scored", score)

Output

Start: 0
After collecting: 40
Lives left: 2
Aarav scored 40

Try it yourself

Valid or invalid name?

Can each be used as a Python variable name?

  • for

  • score2

  • total_marks

  • my score

  • 2nd_place

Common mistakes

  • Using a variable before giving it a value: NameError.
  • Reading = as 'equals'. It means 'store the right side in the left'.
  • Choosing names like x and temp2 that say nothing about the value.

Check yourself

Question 1

1. After x = 5 and x = x + 2, what is x?

Question 2

2. Which is a valid name?

Question 3

3. What does score += 5 do?

Summary

  • A variable is a name for a stored value; = stores it.
  • Reassigning changes the value; += and -= are shortcuts.
  • Use clear snake_case names that follow the rules.

Finished reading?

Sources: W3Schools Python Tutorial