Python Fundamentals Practice
Python Variables
Containers for Your Code
Think of variables as labeled containers. You can put something inside, give the container a name, and then refer to it by that name later. In programming, we use variables to store data that our code needs to work with.
Assigning a value to a variable in Python is simple. You use the equals sign (=). The name of the variable goes on the left, and the value you want to store goes on the right.
# The variable 'planet' now holds the string "Earth"
planet = "Earth"
# The variable 'moons' now holds the number 1
moons = 1
# The variable 'has_life' now holds the boolean value True
has_life = True
Once you've stored a value, you can use the variable's name to retrieve it. You can also change the value a variable holds by assigning it a new one. The old value is simply replaced.
apples = 5
# The value of 'apples' is now 5
apples = 10
# The value of 'apples' has been updated to 10
What's in the Box?
The information we store comes in different forms, or data types. Python automatically figures out the type of data you're storing. Let's look at the most common ones.
Strings are used for text. You create them by wrapping text in either single (
') or double (") quotes.
user_name = "Alex"
Integers are whole numbers, both positive and negative, without any decimal points.
year = 2024
Floats, or floating-point numbers, are numbers that have a decimal point. They're used for values that require more precision than integers.
price = 19.99
Booleans can only have one of two values:
TrueorFalse. They're great for representing states, like whether a switch is on or off.
is_logged_in = False
It's important to know the data type you're working with because it determines what you can do with the data. For example, you can perform math operations on integers and floats, but not on strings.
Naming Conventions
Python has a few rules for naming variables. Following them ensures your code will run without errors and be easy for others to read.
| Rule | Description |
|---|---|
| Starts with | Must begin with a letter (a-z, A-Z) or an underscore (_). |
| Contains | Can only have letters, numbers (0-9), and underscores. No spaces or special characters like ! or @. |
| Case-Sensitive | book, Book, and BOOK are three different variables. |
| No Keywords | Cannot be a reserved Python keyword like if, for, or class. |
While you can technically name a variable x or a1, it's much better to use descriptive names. A name like customer_email is far more understandable than ce. This practice of using underscores to separate words is called snake case, and it's the standard convention in Python.
# Good variable names
first_name = "Guido"
user_age = 68
# Bad variable names
2nd_place = "Sally" # Can't start with a number
user-name = "Javier" # Can't contain a hyphen
What is the best analogy for a variable in programming?
Which line of Python code correctly assigns the integer value 50 to a variable named score?