In this Python tutorial, I will explain what a variable in Python is, how to create a Python variable, and what are the different types of Python variables with some demonstrative examples.
In any programming language, a variable can be considered the equivalent of a storage box where we keep information. This concept is no different in Python, one of the world’s most popular programming languages. Variables in Python play a vital role in storing and managing data used in our programs.
What is a variable in Python?
In its essence, to define variable in Python means to name a location in memory where a programmer can store data and later retrieve this data using the variable’s name. Think of it as naming a box so we can identify its contents without having to open it.
In Python, variables:
- Do not need explicit declaration: A Python variable is created the moment we first assign a value to it.
- Are dynamically typed: We can assign a Python variable of one type and later reassign it to a different type.
If we assign a variable in Python and after some time we again assign some different value to it. Then, the value will change for that Python variable.
Types of Variables in Python
The type of Python variable is decided according to the type of data we store in it. i.e., Python’s flexibility is evident in the types of data one can assign to variables. Some of the primary types include:
- Integers: Whole numbers.
- Floats: Decimal numbers.
- Strings: Textual data.
- Lists: An ordered collection of items.
- Sets: An unordered collection of unique items.
- Dictionaries: Key-value pairs.
Special keywords, like the global keyword in Python, allow us to declare variables that are global (accessible throughout the code). Another concept is the static variable in Python, which retains its value across function calls.
However, while var in Python is not a reserved keyword like in some other languages, there are certain reserved words we should avoid as variable names.
How to Create Variable in Python
Creating or to make a variable in Python is straightforward, its syntax is:
variable_name = value
Where:
- variable_name is the name we want to give to our Python variable.
- value is the data we want to store.
Naming Conventions for Variables in Python
Python has a few rules and conventions when it comes to naming variables:
- Variables must start with a letter or an underscore: e.g., name or _name.
- The remainder of the variable can consist of letters, numbers, or underscores: e.g., name1 or first_name.
- Variable names are case-sensitive: So, country and Country would be two different variables.
- Descriptive names are preferred: For clarity, choose names that indicate the purpose of the Python variable, e.g., population rather than p.
- Avoid Reserved Words: Just as we wouldn’t name a city “United States” (since it’s too broad), we shouldn’t name our variables after Python’s reserved words like if, else, print, etc.
Examples of variables in Python
Let’s break down each of the mentioned data types of variables in Python, and provide a demonstrative example:
Assigning a String to a Python variable
Strings abbreviated as str in Python, are sequences of characters enclosed within single, double, or triple quotes.
national_bird = "Bald Eagle"
print(national_bird)
print('The type of variable:', type(national_bird))
The output is:
Bald Eagle
The type of variable: <class 'str'>
In this example, we’ve created a Python variable named national_bird that holds the name of the national bird of the USA. Hence, we can create an str variable in Python
Reassigning a Python Variable
Python’s dynamic nature allows us to reassign variables. Reassigning a Python variable means giving it a new value after its initial assignment. Once a variable is defined in Python, its value can be changed at any time by simply reassigning a new value to the same variable name.
For instance: Let’s take the name of states in California in a Python variable to check whether reassigning a variable works in Python or not.
state = "California"
print('The first print:', state)
state = "Texas"
print('The second print:', state)
The output is:
The first print: California
The second print: Texas
Now, the Python variable state holds the value “Texas” instead of “California“. after we assign different values to the Python variable in the code.
Assigning a Number or integer in a Python variable.
Integers in Python, commonly abbreviated as int, are whole numbers that can be positive, negative, or zero.
number_of_states = 50
print(number_of_states)
print('The type of variable:', type(number_of_states))
The output is:
50
The type of variable: <class 'int'>
Here, In the example, number_of_states Var in Python represents the total number of states in the USA. So, it is an Integer Python variable.
Assigning a Float to a Python Variable
Python floats (or floating-point numbers) represent real numbers and can have decimal points.
avg_temperature = 65.7
print(avg_temperature)
print('The type of variable:', type(avg_temperature))
The output is:
65.7
The type of variable: <class 'float'>
The Python variable avg_temperature stores the average yearly temperature (in Fahrenheit) for California.
Assigning a Python list to a variable
A Python list is an ordered collection of items that can be of any type. Items in a list are indexed starting at 0. For instance, if we wish to understand the correct syntax for creating a variable that is bound to a list, it would be:
variable_name = (item1, item2, item3, ...)
So, Let’s consider a Python list of major cities in California:
major_cities = ["Los Angeles", "San Diego", "San Jose", "San Francisco"]
print(major_cities)
print('The Type of variable is:', type(major_cities))
The output is:
['Los Angeles', 'San Diego', 'San Jose', 'San Francisco']
The Type of variable is: <class 'list'>
The major_cities variable in Python contains a list of some major cities in California.
Assigning a Set to a variable
A Python set is an unordered collection of unique items. Unlike lists, sets do not allow duplicate values. For instance, if we’re wondering what is the correct syntax for creating a variable that is bound to a set, it’s:
variable_name = {item1, item2, item3, ...}
For example,
primary_colors = {"red", "blue", "green"}
print(primary_colors)
print('The Type of variable is:', type(primary_colors))
The output is:
{'red', 'blue', 'green'}
The Type of variable is: <class 'set'>
The primary_colors set in Python represents three fundamental colors, ensuring that each color appears only once.
Assigning a Dictionary to a variable in Python
A Python dictionary, or dict, is a collection of key-value pairs where each key must be unique. The correct syntax for creating a variable that is bound to a dictionary in Python, it is:
variable_name = {key1: value1, key2: value2, key3: value3, ...}
For example,
state_capitals = {"California": "Sacramento", "Texas": "Austin"}
print(state_capitals)
print('The Type of variable is:', type(state_capitals))
The Output is:
{'California': 'Sacramento', 'Texas': 'Austin'}
The Type of variable is: <class 'dict'>
In the state_capitals Python dictionary, each state (key) is paired with its capital (value). For instance, the capital of California is Sacramento.
Conclusion
To create a variable in Python means to define a reference to some data, similar to how U.S. cities reference particular regions of states. Whether we want to create variable in Python as a list, set, or any other type, the principles remain consistent. By understanding how to define in Python, one paves the way to write efficient and effective code.
You may also like to read:
- How to Create a String with Variables in Python [Create a String with Multiple Variables in Python]
- How to add two variables in Python
- Check if the variable exists in Python
- Check if a variable is None in Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.