Variables and Values
Learn how to store information in variables—the building blocks of every program.
Prerequisites
Variables are how programs remember things. A variable is a name that refers to a value stored in the computer's memory.
Creating Variables
Use the equals sign = to assign a value to a variable:
age = 25
name = "Alice"
pi = 3.14159
print(name)
print(age)
print(pi)Output:
Alice
25
3.14159Think of variables as labeled boxes. The name is the label, and the value is what's inside the box.
Variables Can Change
That's why they're called "variables"—their values can vary:
score = 0
print("Starting score:", score)
score = 10
print("After bonus:", score)
score = score + 5 # Add 5 to current score
print("Final score:", score)Output:
Starting score: 0
After bonus: 10
Final score: 15The line score = score + 5 might look strange at first. It means "take the current value of score, add 5, and store the result back in score."
Naming Rules
Variable names must follow these rules:
- Start with a letter or underscore (_)
- Can contain letters, numbers, and underscores
- Cannot contain spaces or special characters
- Are case-sensitive (age, Age, and AGE are different variables)
- Cannot be Python keywords (like print, if, for)
# Valid names
user_name = "Bob"
age2 = 30
_private = "hidden"
# Invalid names (these will cause errors)
# 2fast = "nope" # Can't start with number
# user-name = "nope" # Can't use hyphens
# my name = "nope" # Can't have spacesNaming Conventions
While Python allows many names, follow these conventions for readable code:
- Use lowercase with underscores: user_name, total_price
- Be descriptive: price is better than p
- Avoid single letters except for counters: i, j, x
- Don't be too verbose: user_email not user_email_address_string
Using Variables in Calculations
# Calculate the area of a rectangle
width = 10
height = 5
area = width * height
print("Width:", width)
print("Height:", height)
print("Area:", area)Output:
Width: 10
Height: 5
Area: 50Practice
- Create variables for your name, age, and city
- Calculate your age in days (age * 365)
- Create a variable for price, another for quantity, calculate total
- Swap the values of two variables (hint: you'll need a third variable)
Your First Program
Write and run your first Python program. Learn how code executes and how to see output.
Data Types
Numbers, text, and true/false values—understand the different kinds of data Python can work with.
Operators and Math
Arithmetic, comparison, and logical operators—the tools for calculations and decisions.