Variables are always a key concept in any programming language. They are the essential blocks on which you build your programs. Learn more about Python variables below.
You can use variables to name values for later use. They tell Python to store those values in the system’s memory (if it hasn’t) and provide a way to reference it through an identifier (name).
For example, after assigning the string “learnshareit” to the variable “site”, you can recall the string and use it in your function or operation by using the name “site”.
Variables have important and fundamental roles in Python. They help you keep track of values that may change in your programs. Those identifiers are also an elegant way to refer to complex data. You don’t have to type the full string again whenever you need it. Variables, therefore, make values easier to manage and increase both the reusability and readability of your programs.
Variable Declaration And Assignment
In some languages like C and Java, you will need to give a variable a type the moment you declare it. This isn’t the case with Python.
You can just create a variable with an assignment statement. There is no need to tell Python to reserve space for your variable ahead of time.
A simple assignment statement has the following form:
<variable name> = <expression>
Python evaluates the expression on the right side of the equal sign and assigns the resulting object to the name on the left.
>>> a = 'learnshareit' >>> b = 2 + 3 >>> c = b
The first statement binds the string ‘learnshareit’ to the variable a, while the second evaluates the expression ‘2+3’ and gives the result to b. Finally, the value of b is assigned to another variable, c. Those values are stored in memory, identified by the identifiers you can have given them (a, b, and c in this case).
We can check the value of variables by simply entering their names in the interpreter shell. This is also how you can use variables to make a reference to values you have assigned to them before. Python will resolve those references and retrieve the values in memory you have assigned to those identifiers earlier:
>>> a 'learnshareit' >>> b 5 >>> c 5
Note: you can also assign values to slices, subscriptions, and attribute references. Check out our guides on sequence data types and classes to learn more about this advanced use of the assignment operator.
You can’t use variables that haven’t been defined. Python won’t be able to know which value you are referring to and will give you an error as a result:
>>> print(undefinedVariable) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'undefinedVariable' is not defined
You can assign a value to multiple variables at the same time with a single statement:
>>> a = b = c = 5 >>> a 5 >>> b 5 >>> c 5
Remember to avoid names Python has reserved for its purposes, such as import, class, function, def, or if. Variable names can contain letters, digits, and underscores. However, they shouldn’t start with digits.
Python variables are case sensitive, meaning site and SITE are two different names:
>>> site = 'learnshareit' >>> SITE = 'LEARNSHAREIT' >>> site 'learnshareit' >>> SITE 'LEARNSHAREIT'
Most developers use lowercase letters to name variables. But they also often capitalize every word (except for the first one) when the names consist of more than one word. This makes them easier to read (for example, siteDomain compared to sitedomain).
Another common practice is to use only the uppercase for values that you don’t plan to change at any later point in the program. Many languages provide constants for this purpose. This feature doesn’t exist in Python, and most developers mark those variables with uppercase letters and underscores, such as SITE_DOMAIN.
You should choose easy-to-understand names for variables, even if this may make them longer. They make it easier to troubleshoot problems and maintain your code than short and cryptic variables.
Checking The Type Of Variables
You can use the built-in function type() to find out and verify the type of any name in Python:
>>> a = 5 >>> b = 'python' >>> type(a) <class 'int'> >>> type(b) <class 'str'>
You can give new values to existing variables. All you need is an assignment statement, just like how you initialize them in the first place.
>>> a = 6 >>> a 6 >>> a = 8 >>> a 8
Since variables aren’t tied to any data type, the new value can even belong to a different type than the old one.
>>> a = 9 >>> a 9 >>> a = 'blue' >>> a 'blue'
This makes Python variables more dynamic than those of programming languages where variables have fixed types and can’t be changed later.
There are scenarios where you must swap the values between two variables. This is one of the most basic tasks you must know how to carry out. For instance, consider these two variables that contain integer values:
>>> a = 10 >>> b = 20
Our desired result is that a will hold the value 20, while b holds 10. The natural idea is that we assign b to a, and then assign a to b later. This won’t work, however:
>>> a = b >>> b = a >>> a 20 >>> b 20
Now two variables both hold the original value of b. This happens because when you make the first assignment statement to assign b to a, you have removed the original value from a. As a result, there is no way to refer to it with an identifier and assign it to b.
To fix this issue, you will need a temporary variable to hold this value:
>>> tmp = a >>> a = b >>> b = tmp >>> a 20 >>> b 10
Most of the time, Python automatically handles memory management for you. You don’t need to deal with lower-level tasks like allocating memory for objects in your program. But when there is a need for manual memory cleanup, there are plenty of ways to do it too.
The del statement can delete a variable:
>>> a = 5 >>> a 5 >>> del a >>> a Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'a' is not defined
When you attempt to use a variable that has been deleted by del, it will raise a NameError exception as if the variable hasn’t been declared.
You can learn more about Variables in Python in the articles below.
- Check if a variable is not Null in Python
- Check if a variable is Null in Python
- Test multiple variables against a single value in Python
- Check if multiple variables are equal in Python
- Check if a variable is a datetime object in Python
- Add single quotes around a variable in Python
- Print a variable’s name in Python
- How to print a String and a Variable in Python
Python variables allow you to store and refer to values in your program. You don’t need to declare a type and can even assign a new type later, making them more flexible and easier to use.
My name is Robert. I have a degree in information technology and two years of expertise in software development. I’ve come to offer my understanding on programming languages. I hope you find my articles interesting.
Name of the university: HUST