Variables in Python

What is a variable?

It's a name you give to a piece of data. That's it. Think of it as a label for a value stored in memory. Instead of remembering a complex piece of data, you just remember the label.

user_age = 29

Here, user_age is the variable. The value is 29. The = is the assignment operator; it assigns the value on the right to the variable on the left.

Why use them?

So you can store and reuse data. If you need a user's age in ten different places, you refer to user_age. If their age changes, you only have to update it in one place. It makes code readable and manageable.

How to create them

You just name it and assign a value. That's it.

some_variable = "some value"

Python figures out the data type on its own. This is called dynamic typing. You don't have to tell Python it's a number or text beforehand.

user_name = "Steve" # This is a string (text)
items_in_cart = 5 # This is an integer (whole number)
price = 19.95 # This is a float (number with a decimal)
is_logged_in = True # This is a boolean (True or False)

You can change the type of data a variable holds at any time.

my_var = 10
my_var = "Now I'm a string"

This is fine in Python.

Rules for Naming Variables

You can't just name a variable anything. Stick to these rules:

  • Start with a letter or an underscore (_). Never a number.
  • Can only contain letters, numbers, and underscores. No spaces, no dashes, no special characters.
  • Names are case-sensitive. age, Age, and AGE are three different variables.
  • Convention, not a rule: Use snake_case for variable names. It's all lowercase with underscores separating words. It's what Python programmers expect to see.
this_is_good_snake_case
thisIsNotPythonic

Using Variables

Once you've created a variable, you can use its name as if it were the value itself.

price = 50
tax = 10
total_cost = price + tax
print(total_cost) # This will output 60

A variable is just a stand-in for its value. Keep it that simple.

We will learn in the next lesson:

Scroll to Top