Variables: Storing Data
A variable is a name that holds a value. You create one by assigning a value with =. Variables let your program remember things and reuse them, which is the foundation of everything else you will write.
What You'll Learn
- Creating variables and following naming rules
- Reassigning and updating values
- Assigning several variables at once and swapping them
Creating Variables
Loading Python Playground...
The name goes on the left, the value on the right. After that, using the name gives you back the value.
Naming Rules
- Must start with a letter or underscore
- Can contain letters, numbers, and underscores
- Case-sensitive (
nameandNameare different) - Cannot be a Python keyword (like
if,for,while)
By convention, Python uses snake_case (lowercase words joined by underscores):
Loading Python Playground...
Exercises
Loading Python Exercise...
Loading Python Exercise...
Loading Python Exercise...
Reassigning Values
A variable can be updated at any time. The latest value wins:
Loading Python Playground...
Multiple Assignment and Swapping
Python lets you assign several variables in one line, and swap two values without a temporary variable:
Loading Python Playground...
Loading Python Exercise...
Combining Text Variables
You can join text stored in variables using +:
Loading Python Playground...
This idea powers the Mad-Libs project at the end of this module, where you slot words into a story.
Key Takeaways
- Create variables with
=(the assignment operator) - Use descriptive
snake_casenames - Variables can be reassigned; the newest value wins
- Assign many at once:
a, b = 1, 2 - Swap easily:
a, b = b, a
Quiz
Question 1 of 425% Complete
0 of 4 questions answered

