Variables

Variables are names that refer to stored data values.

Syntaxname = value

A variable is a name that refers to a value. You create one simply by assigning a value with the = sign — no keyword needed.

Rules for names

  • Start with a letter or underscore, followed by letters, digits or underscores.
  • Names are case-sensitive.
  • Choose clear names like user_age rather than x.

Example

Example · python
first_name = 'Ada'
birth_year = 1815
age = 2026 - birth_year
print(first_name, 'is', age, 'years old')

# Output:
# Ada is 211 years old

When to use it

  • A shopping cart stores the current item count in a variable that updates as the user adds products.
  • A weather app saves the current temperature in a variable to display and compare against thresholds.
  • A game tracks a player's score in a variable that increments after each correct answer.

More examples

Declare and print variables

Creates three variables of different types and prints them all in one line.

Example · python
name = 'Grace'
age = 35
height = 1.75
print(name, age, height)

# Output:
# Grace 35 1.75

Reassign a variable

Shows that a variable's value can be replaced or updated with augmented assignment.

Example · python
score = 0
print('Start:', score)
score = 10
print('After bonus:', score)
score += 5
print('After extra:', score)

# Output:
# Start: 0
# After bonus: 10
# After extra: 15

Multiple assignment on one line

Demonstrates two shorthand forms: tuple unpacking and chaining the same value.

Example · python
x, y, z = 1, 2, 3
print(x, y, z)

a = b = c = 0
print(a, b, c)

# Output:
# 1 2 3
# 0 0 0

Discussion

  • Be the first to comment on this lesson.