Learn everything about Variables in Python and how to use them effectively in this series of basic Python guides for beginners.
Variables are one of the most important concepts in programming and something that you need to master early on when learning any programming language.
What is a Variable in Python?
In Python, a variable is a name for a memory location. You can think of this memory location as a container that can store any type of data (we will learn about different data types in the next guide).
We use variables as a way to store and hold values. You can then use, change or manipulate the data stored in the variable during the execution of your Python program.
Python variables are created when you assign a value to them. The assignment creates only a reference to the object (not a copy), and the object may be of any type.
One easy thing with Python variables is that they do not need to be declared before they are used, unlike some other programming languages.
Let’s now look into how to create and use variables in Python.
Creating Variables in Python
You can simply create a variable in Python by simply assigning a value to it. There is also no need to specify the data type of the variable when you create it.
Python will automatically detect the data type of the value you assign to the variable and will store it accordingly.
Format of Variable in Python
As per the officially recommended PEP8 guidelines, you should use snake case – all lowercase with underscores in between to name your variables.
this_is_a_snake_case_variable_name
See the standard format of the variable (my_first_variable) that has a value (xyzvalue) assigned to it below.
my_first_variable = xyzvalue
The equal to sign (=) means an assignment and is used to assign a value to the variable in Python.
If you rather want to test equality, you will need to use double equals (==) in Python.
It’s also important to remember that Python variable names are case-sensitive and you can only use letters or an underscore at the beginning of a variable name. Let’s look at some other variable naming rules in the next section.
Python Variable Naming Rules
Adhering to certain rules and standard practices when naming your Python variables can go a long way in making your code readable and easy to remember.
Here is a list of some general rules to follow when choosing names for your variables:
- Variable names can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
- Variables must start with a letter or an underscore character (_name).
- Variable names are case-sensitive (age, Age, and AGE are three different variables).
- Variable names cannot start with a number (e.g., 1name, 2names, 3_names).
- Avoid using Python keywords as variable names (see the reserved words in the below section)
You can give your variables any name you want as long as it follows the above rules. However, for better programming standards, it’s important that your variables are descriptive names and help understand the context.
You can follow the PEP8 documentation to learn the official style guidelines of Python.
Python Variables Examples
Single variable: the following code creates a variable with the name “my_var” and assigns an integer value of 10 to it.
my_var = 10
Multiple variables in one line: You can also create multiple variables in one line by separating them with a comma.
x, y, z = 1, 2, 3
Here, we have created three variables x, y, and z in one line and assigned different values to them.
Assign same value to multiple variables: If you want to assign the same value to all the variables, you can do it like this.
x = y = z = 10
This will assign the value 10 to all three variables – x, y, z.
Empty Variables: You can also create a variable without assigning any value to it. Such variables are called empty or null variables.
To create an empty variable in Python, you can use the keyword None.
my_var = None
Here, my_var is an empty variable. You can also create multiple empty variables in one line like this.
x = y = z = None
Using Variables in Python
Once you have created a variable, you can use it in your program by simply referring to its name.
For example, the following code prints the value of the variable my_var that we created earlier.
print(my_var)
This will print the value 10 that is stored in the my_var variable.
You can also perform various operations on variables. For example, the following code will add two numbers and store the result in a third variable.
num1 = 10
num2 = 5
result = num1 + num2
print(result)
This will print the value 15 as the output.
Here, we have created three variables num1, num2 and result. We have assigned the values 10 and 5 to num1 and num2 respectively.
Then we have added these two numbers using the + operator and stored the result in the third variable “result“. Finally, we have printed the value of the result variable using the print() command.
You can also perform various other operations on variables like subtraction (–), multiplication (*), division (/) and so on.
Apart from numerical operations, you can also concatenate two strings using the + operator. For example,
str1 = "Hello"
str2 = "World"
result = str1 + str2
print(result)
This will print the string “Hello World”.
You can also concatenate a string with an integer value (also written in the same string data type), and in that case, the result will be a string. For example,
str1 = "Hello"
num1 = "10"
result = str1 + num1
print(result)
This will print the string "Hello10".
However, if you want to concatenate the string data type with integer data type, you will first need to convert the integer value to a string using the str() function but we will look at Casting to change data types of variables in the later section.
Assigning a value to a Python variable
Assigning a value to a Python variable is fairly straightforward. You simply use the equals (=) sign to assign the value to the variable. For example:
age = 30
This creates a variable called age and assigns the value 30 to it.
You can also assign multiple values to multiple variables in one go. For example:
age, name = 30, "Guido"
This will create two variables, age and name, and assign the values 30 and Guido to them respectively.
You can also assign the same value to multiple variables in one go. For example:
x = y = z = 10
This will create three variables, x, y and z, and assign the value 10 to all of them.
Printing a Python Variable
The print() function is used to display the output of a Python program.
Once you have created a variable and assigned a value to it, you can print the value of that variable by using the print() function. If we take the same variable example above;
age, name = 30, "Guido"
print(age)
This will print the value of the age variable, which is 30, in the above example.
If you want to print multiple variables at once, you can do so by separating them with a comma inside the print() function. For example:
print(age, name)
This will print both the age and name variables, which are 20 and Guido respectively.
Concatenating or Joining Two or More Variables in Python
If you want to concatenate two or more variables, you can use the + operator. For example:
first_name = "Guido"
last_name = "Rossum"
full_name = first_name + last_name
print(full_name)
This will print the string “Guido Rossum”.
Data Types in Python Variables
Python Variables are defined using a certain data type. Any value that you assign to a variable in Python is called a data type.
A data type is basically the format of the value. For example, a string is a data type that represents textual data, and an integer is a data type that represents numeric data.
Python comes with various built-in data types that you can use to store values in variables. We will look at the data types in detail in another guide but here are the most common data types in Python;
- Numeric data types: int, float, complex
- String data types: str
- Sequence types: list, tuple, range
- Binary types: bytes, bytearray, memoryview
- Mapping data type: dict
- Boolean type: bool
- Set data types: set, frozenset
String, Boolean, and Numeric data types are some of the most popular data types in Python. Let’s quickly look at each of them;
String Data Type: A string data type represents textual data and consists of a combination of characters.
You can create a string in Python by using single or double quotes. For example:
my_string = "Hello World"
my_string = 'Hello World'
The only difference between the two is that you can sometimes find one type more useful than the other. For example, you can use double quotes to create a string that contains single quotes. See the example below:
my_string = "I'm a string"
This is not possible with single quotes. If you try to do this, you will get an error.
Numeric Data Types: The numeric data types represent numerical values and include the following types:
int: The ‘int’ data type represents positive or negative integers with no decimal point.
The int data type is the most common type of numeric data. It is used to represent a number without any fractional part.
my_int = 10
float: This ‘float’ data type represents floating-point numbers and consists of a whole number and a fractional part.
The float data type is used to represent floating-point numbers – a number that has both an integer and a fractional part. A floating-point number is a number with a decimal point.
my_float = 3.14
complex: This ‘complex’ data type represents complex numbers and is represented by real and imaginary parts.
The complex data type is used to represent complex numbers. A complex number is a number with both a real and an imaginary part.
my_complex = 1 + 2j
You can see variables with different numeric data types in the examples above.
Boolean Data Types: Boolean is a data type that is used to represent logical values. It can only be True or False.
my_bool = True
Examples of Main Data Types in Python: See the following examples in the code for the main data types in Python.
#Main Data Types in Python
#String
word = "Hello" # This is a string as it has quotation marks
#Integer
number = 10 # This is an integer as the value is a whole number
#Float
decimal = 2.1 # This is a float as it has decimal in the value
#Boolean
answer = False # This is a boolean as the value is either True or False
#Checking Data Types
print(type(word))
print(type(number))
print(type(decimal))
print(type(answer))
''''Data Types Output
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
'''
You can learn more about all Data Types in Python in our detailed guide here.
How to find out Data Types in Variables
You can use the built-in Python function type() to know the data type of a value.
To display the output of the type() function, you can use the print() function and the output will show the data type of the specific variable in inverted commas.
For example,
age = 30
print(type(age))
This will print the following output:
<class 'int'>
Here, the value 30 is an integer, so its data type is ‘int‘, and we have used the print() function to display the data type output.
Similarly, if you have a string variable, the data type of that variable will be ‘str‘.
For example:
name = "Guido"
print(type(name))
This will print the following output:
<class 'str'>
The value “Guido” is a string, and thus the str output.
And, for the Boolean variable, see this example:
my_bool = True
print(type(my_bool))
This will print the following output:
<class 'bool'>
The value for our variable in the above example True is a Boolean and so you see the ‘bool‘ output for the Boolean data type.
Casting to change Data Types of Variables
Casting in Python allows you to specify or change the data types of Variables. So, if you are looking to change the data type of a variable, you can use a specific function for Casting into another data type.
The process of converting one data type to another is called casting in Python.
You can also convert the data type of a value to some other data type using the following data type conversion functions.
int() - Converts a value to an integer
float() - Converts a value to a floating point number
str() - Converts a value to a string
tuple() - Converts a value to a tuple
list() - Converts a value to a list
For example, you can convert a string value to an integer using the int() function. This is particularly useful if you are taking input from users which is always in the string format and needs to be converted to a string for numeric operations.
Keywords in Python – Reserved Words
Although you can name your variable whatever you like, there are some words that you cannot use as variable names because they are reserved for special purposes in Python.
These words are called keywords, and they have specific meanings in the language. You will encounter them frequently as you start learning more about Python.
The following table lists all the keywords in Python.
and | as | assert | break |
class | continue | def | del |
elif | else | except | False |
finally | for | from | global |
if | import | in | is |
lambda | None | nonlocal | not |
or | pass | raise | return |
True | try | while | with |
yield |
Just remember not to use these Python keywords as your variable names as this will throw an error.
Local and Global Variables in Python
You can also find local and global types of variable classification in Python.
A local variable is one that is declared inside a function. A global variable is one that is declared outside a function.
Local Variables
A local variable is only accessible inside the function in which it is declared. For example:
def my_func():
x = 10
print(x)
In this example, the x variable is a local variable because it is declared inside the my_func() function.
Global Variables
A global variable is one that is declared outside a function. For example:
x = 10
def my_func():
print(x)
In this example, the x variable is a global variable because it is declared outside the my_func() function.
You can also declare a global variable inside a function by using the global keyword. For example:
def my_func():
global x
x = 10
print(x)
In this example, the x variable is declared as a global variable inside the my_func() function.
The global keyword is used to declare a global variable inside a function. Without the global keyword, the variable is treated as a local variable.
Accessing Global Variables From Local Functions
If you want to access a global variable from inside a local function, you need to use the global keyword. For example:
x = 10
def my_func():
global x
x = 20
print(x)
my_func()
print(x)
In this example, the x variable is declared as a global variable inside the my_func() function. This allows the function to change the value of the x variable.
When the my_func() function is called, it sets the value of x to 20. When the print(x) statement is executed outside of the function, it prints the value of x, which is now 20.
If you don’t use the global keyword, the x variable is treated as a local variable inside the my_func() function. This means that the my_func() function can’t change the value of the x variable.
Python Variables Basic FAQs
As a beginner, you might have a lot of questions about using Python Variables the right way. See these FAQs to quickly gain an understanding of the Python Variables basics.
-
How to declare Variables in Python?
In Python, variables can be declared by simply assigning a value to them. There aren’t any commands for declaring a variable and you don’t need to declare variables before using them in Python, unlike other programming languages.
-
How to print Variables in Python?
You can print the value of a Python variable by using the “print()” function. There are several ways to print multiple Variables in Python such as using f-string method and format() code method.
-
How to assign variables in Python?
In Python, you can assign values to variables using the equal sign (=). For example, if you want to assign the value “5” to a variable “x”, you would use the following statement: x = 5
-
How do I delete a Python Variable?
You can use the command “del” to delete a Python variable. For example, if you have a variable “x” with the value “5”, you can delete it using the command del with the following statement: del x
-
How to add Variables in Python?
You can add two numeric Python variables by using the “+” operator. Adding strings is called String concatenation and you can also add the same “+” operator between two variables or strings to add them.
-
What are global variables in python?
Global variables in Python are variables that can be accessed from anywhere in the code. A global variable can be declared outside of a function and it will be available within all functions throughout the program.
-
What is the difference between a Local and Global Variable in Python?
Local variables are only accessible within the scope of the function they are declared in. Global variables, on the other hand, can be accessed by any function within the program.
Summary: Variables in Python
To summarise, variables are an important part of programming because they allow you to store data that can be accessed and changed as needed.
As we discussed in this guide, you can easily create a Python variable by assigning a value to it. As Python Variables do not need to be declared before they are used, it makes Python code easier to read and less error-prone.
Creating Variables in Python, thus, is really easy as you don’t need to put in any data type while declaring it and you can directly assign a value to the variable while declaring it. You have also seen how you can create variables with multiple values by assigning them a list of values separated by commas.
We slightly touched types while discussing variables but head over to our detailed guide on Python Data Types where you will learn how to use all kinds of data types and what you can do with them.
Now that you know how to create variables and what data types they can contain, it’s time to learn about beginner control structures. Check out our next guide where we show you how to control structures such as For Loop and While Loop in Python.
And if you are just getting started with Python programming, don’t forget to check our first guide on what are pseudocodes and how to write them with detailed examples.
More Python Guides
Start your Python learning with our complete guides and resources.
Follow our structured guided learning to Python.