2 minutes read

You can use a programming language like Python to do calculations or work with constant values like strings. Is this enough for you, though? When writing real programs, you usually need to store values or evaluation results in computer memory.

What is a variable?

A variable is a named place where you can store a value to access it later. Imagine a box where you keep something. That's a variable.

For example, you calculate a result and would like to reuse this result elsewhere. In this case, you can use such a box to save time.

In general, it's a good practice to give a variable a name that describes its content.

Defining a variable and assigning values

You can keep almost anything in variables by assigning a value to a named variable with an equal sign. By PEP 8, one space before and after the assignment sign is considered good practice.

day_of_week = "Monday"

Now you have a string value "Monday" stored in computer memory. You can retrieve the value by calling the variable name.

print(day_of_week)  # Monday

day_of_week stores a value of the str type.

print(type(day_of_week))  # <class 'str'>

You can always assign a new value to a defined variable.

day_of_week = "Tuesday"

Now, you will retrieve another value:

print(day_of_week)  # Tuesday

It is possible to assign the value of one variable to another variable:

a = 10
b = a  # b is 10

If you haven't defined a variable within the scope of your code, you'll see an error when you try to use it:

print(month_name)  # NameError: name 'month_name' is not defined

Python allows you to assign values of different types to the same variable. Let's assign the string name of a month to a variable and print its type.

month = "December"
print(type(month))  # <class 'str'>

Now, let's assign the number of this month to the variable and print its type again.

month = 12
print(type(month))  # <class 'int'>

This assignment works because Python is a language with dynamic typing.

Please, do not overuse dynamic typing! If your code is long, you might forget that you changed the type of a variable. This is a common reason for errors!

Naming rules

As mentioned above, each variable has a name that distinguishes it from other variables. There are some rules for naming variables that you should follow:

  • Names are case-sensitive (month is not the same as Month).

  • A name begins with a letter or an underscore, followed by letters, digits or underscores (e.g., user_name, score1, _count).

  • A name cannot start with a digit (for example, 2q is invalid).

  • A name must not be a keyword.

Do not break these rules; otherwise, your program will not work.

Conclusion

In this topic, we've learned what variables are in Python. We also saw how to define them, assign values to them, and what their naming rules are. Hopefully, this new knowledge will serve you on your way to learning Python!

4601 learners liked this piece of theory. 45 didn't like it. What about you?
Report a typo