Variables
Variables are names that refer to stored data values.
Syntax
name = valueA 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_agerather thanx.
Example
Loading editor…
Press Run to execute the code.
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.
name = 'Grace'
age = 35
height = 1.75
print(name, age, height)
# Output:
# Grace 35 1.75Reassign a variable
Shows that a variable's value can be replaced or updated with augmented assignment.
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: 15Multiple assignment on one line
Demonstrates two shorthand forms: tuple unpacking and chaining the same value.
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