Variables play an important role in Python, as they allow us to declare elements in our code, which we use to create executable functions. Variables are deeply linked to Python Data Types, as one cannot exist without the other. Because of their connection to each other, these two elements are often confused or seen as the same thing, when in fact they are slightly different.
NOTE: This tutorial requires that Python is already installed, as well as an IDE (Integrated Development Environment), such as PyCharm. It’s also recommended that you have a basic understanding of How to Use Python if this is your first time learning Python.
With that said, let’s get started with this free Python Variables tutorial.
What are Variables in Python?
Variables are containers for storing data values in Python.
Think of variables as a tupperware container on your desk. Everything you put into the container becomes a variable, whether it be a pencil, an apple, a written poem, some Pokemon cards, your tax return, or even your shopping list – they are all considered Variables in Python.
Although, these items cannot become variables unless we declare them first, in order for Python to know what they are, and then what to do with them.
To do this we use Python Data Types.
Think of Data Types as a labels or categories for variables, which defines them as follows:
- Integers (int) – Whole numbers: 1, 14, 576 etc
- Floating Point (float) – Decimal values: 1.24, 5.6, 786.463
- Strings (str) – Sequence of Characters: “I love Python”, “this course is great”, “year 3000”
- Booleans (bool) – Logical values representing: TRUE or FALSE
- Lists (list) – Ordered sequence of Objects: [14,”welcome”,365.34]
- Dictionaries (dict) – Unordered Key:Value Pairs: {“amount” : “value” , “name” : “Susan”}
- Tuples (tup) – Ordered immutable sequence of objects: (14,”welcome”,365.34)
- Sets (set) – Unordered Collection of Unique objects: {“set1”,”set2”}
Using these Data Types, we are able to declare our variables in Python, letting it know what they are and how it should use them in the code.
In other words:
- We are telling that apple in our tupperware container: “Hey, you are an apple and there are 6 of you, that are red”.
- Or giving each of our Pokemon cards a name, a value and that they are part of a set.
- Or telling our tax return that it’s a bunch of whole and decimal numbers so that we can calculate out how much we are owed back.
Rules for Variables in Python
There are some rules and guidelines that pertain to Python Variables, which we need to adhere to
- Variable Names cannot start with a number
- Variables cannot use spaces to separate words, only underscores “_”
- Variables cannot use any of these symbols : ~ ! @ # $ % ^ & * ( ) – + \ | ‘ “ , < > / ?
- Variables are Case Sensitive
- Follow the PEP8 Style Guide
Variable names cannot start with a number
For example, a variable can be written as “twothousand”, but cannot be written as “2thousand” or “2000”.
Variables cannot use Spaces, only Underscores
We may not use spaces in Variables, therefore a Python Variable CANNOT be written as:
- Number of college students
- NUMBER OF COLLEGE STUDENTS
- number Of College Students
- Number Of College Students
- Number of college students
We may use underscores in Variables, therefore a Python Variable CAN be written as:
- numberofcollegestudents
- NUMBEROFCOLLEGESTUDENTS
- numberOfCollegeStudents (Camel Case)
- NumberOfCollegeStudents (Pascal Case)
- number_of_college_students
- Number_Of_College_Students
While “numberofcollegestudents” and “NUMBEROFCOLLEGESTUDENTS” are both viable Variable names, they are difficult to read due to there being no separation or boundaries between the words.
As we are not permitted to use spaces between the words, we make use of either capitalization or underscore “_” case techniques, such as:
- Camel Case
- Pascal Case
- Snake Case
Camel Case
When the second and subsequent words are capitalized such as in “numberOfCollegeStudents”, it is referred to as Camel Case, as they presumably represent the humps on a camel’s back.
Pascal Case
Exactly the same as Camel Case, except the first letter is also capitalized such as “NumberOfCollegeStudents”
Snake Case
Words are separated by underscores such as “number_of_college_students” or “Number_Of_College_Students”
Variables cannot use any of these Characters or Symbols
Python Variable cannot use any of these characters and symbols:
- :
- ~
- !
- @
- #
- $
- %
- ^
- &
- *
- (
- )
- –
- +
- \
- |
- ‘
- “
- ,
- .
- < >
- /
- ?
Variables are Case Sensitive
Variables are Case Sensitive, which means that you can have the same word such as “dog” be used as two completely different variables, should you use different capitalization between the two words such as:
- dog
- Dog
- dOg
- DOG
You can then also make use of underscores to add even more variation:
- d_o_g
- _dog
- dog_
- _DOG_
Having two variables of the same sounding word is however not good practice as it can easily cause confusion to anyone trying to read your code, and even you yourself, if you haven’t looked at it in a while.
For example, its best to differentiate the dogs by another keyword such as color
- Brown_Dogs
- White_Dogs
- Black_Dogs
Or by breed:
- YorkshireTerrier_dog
- Rottweiler_dog
- GoldenShepherd_dog
Or by age:
- Young_Dogs
- Middle_Age_Dogs
- Old_Dogs
Follow the PEP8 Style Guide
There are actually many other rules/guidelines in Python, outlined the “PEP8 – Style Guide for Python Code”.
This page outlines the above capitalization guidelines I mentioned above, together with many others.
These rules are there to create a global understanding of code formatting and layout in Python between developers, in the case that you are working on a group project or someone has to take over your code someday in the future.
They however, do not influence the functionality of your code and will work without these guidelines in place.
It just might be confusing to other developers to look at.
The only two guidelines you really do need to know from the start, are the ones covered above, as well as How Python Indentation works, as this has an impact on code working or not.
How to Declare a Variable in Python
Alright, so how do we actually assign one of Data Types, to an object, in order to make it a Variable?
Python Variables are very easy to assign and declare using the equals “=” sign:
For example, if we want to know how many cats I have at home, we would need to tell Python that we want to represent the object “cats” with a number, using the “=” sign, we do it like this:
cats = 2
“cats” is our Variable, of Data Type “int” (integer).
Python now reads/interprets this as: “Cats is assigned the value of 2”
Once this is done, “cats” can be used in a statement or expression, where its value will be substituted.
We can see this in our basic print statement:
cats = 2
print(cats)
#>> 2
We are essentially asking Python what the value of the Variable “cats” is, and to print this value, which we know is “2”
Chained Variable Assignment
Python also allows you to create a Chained Variable Assignment, which makes it possible to assign the same value to several variables at the same time:
cats = dogs = fish = 4
print(cats, dogs, fish)
#>> 4 4 4
We see that Python gave us the answer of “4”, three times, one for each of our three animal Variables.
We can also declare difference Variables of the same Data Type within a single line:
cats, dogs, fish = 4, 3, 2
print(cats, dogs, fish)
#>> 4 3 2
Although its preferred to keep each variable on it own line of code, as it’s easier to read:
cats = 4
dogs = 3
fish = 2
print(cats, dogs, fish)
#>> 4 3 2
Variable Casting in Python
Unlike other programming languages such as C#, or C++, Python doesn’t require us to type out the Data Type in our code, in order to declare a Variable.
For example, in C# you have to declare a variable as: “type variableName = value;”
int apple = 6;
However; in Python, we can also type in the Variable’s Data Type, as follows:
int = apples = 6
print(apples)
#>> 6
In the above example, the breakdown of each element is as follows:
- “int” is the Data Type
- “apples” is our Variable
- “6” is a Whole Number
But we actually don’t need to do this, as Python is clever enough to automatically know that when we assign a Whole Number (6) to a Variable (apples), that its an Integer (int), as follows:
apples = 6
print(apples)
#>> 6
Now Python see our statement (line of code) as follows:
- “apples” is our Variable
- “6” is a Whole Number, therefore it’s an “int” Data Type
The result is the same, as both will print out the word “apples” in our console when executed, but the second method is the preferred method when using Python.
So, if you come from another programming language like C# and prefer labeling your Variables by their Data
Types within the code, you’re still able to do this in Python, as shown above.
Correct way to Cast Variables in Python
There is however another way of doing this as well, which is called Casting.
apples = int(6)
print(apples)
#>> 6
While this works the same as “int = apples = 6”, declaring Variables by their Data Type, via the Casting method is preferably done as “apples = int(6)” instead.
Note that you CANNOT mix the two in the same code, as this will result in the “int = apples = 6” version not to execute and compile.
For example, if you had code such as:
int = oranges = 7
print(oranges)
apples = int(6)
print(apples)
#>> 7
While this code would compile without throwing any errors, giving a result of “7”, it is still technically broken, as it would leave out the apples variable of “6“, which is not correct.
But if we created both using the preferred Casting method, then both Variables will be printed to the console:
oranges = int(7)
print(oranges)
apples = int(6)
print(apples)
#>> 7
#>> 6
Now the result in our console is “7” and “6”, which is correct.
Dynamically Change Variable Types in Python
As we say above, In many other programming languages such as C# or C++, Variables are hard coded in.
This is referred to as Statically-Typed.
This means that when a variable is initially declared to have a specific data type, any value that is assigned to it during its lifetime, will always be of that type.
int apple = 6;
Python however, uses Dynamic Typing removing its Variables from this restriction, as they can be assigned one Data Type, then reassigned to another later on in the code.
This naturally only works if you have not used the Casting method, explained above.
Example: Change Integer to String
Lets first assign our variable “Cats” as an integer number “5”
cats = 5
print(cats)
#>> 5
Now let’s change that “integer number” to a “string“:
cats = 5
cats = "These cats are really fast" #changing Variable from int to string
print(cats)
#>> These cats are really fast
Example: Change Integer to List
This time, let’s change our “cats” variable from an “int” to a “list“
cats = 3
print(cats)
#>> 3
Now let’s rather assign our three cats some names, in the form of a “list“:
cats = 3
cats = ["MrBoots", "Fluffy", "Sparky"] #changing Variable from int to list
print(cats)
#>> [MrBoots, Fluffy, Sparky]
This Dynamic Typing has some downside, such as unexpected Data Types, but at the same time is what makes Python so easy to learn and use.
If we do run into an issue though , we can always use Casting to fix it, so we have the best of both worlds in Python.
Python Variables Conclusion
I hope you enjoyed this tutorial on how to use Variables code in Python. We first looked into what Python Variables are, how they relate to Python Data Types, including int, float, str, bool, list, dict, tup and set.
Next we looked at the Rules of Variables, which tells us how they can and can’t be used or typed in Python, including that they cannot start with a number, cannot use spaces, cannot use symbols, are case sensitive and need to follow the PEP8 style guidelines.
From here we learnt how to Declare a Variable in Python using the equals “=” sign, followed by more advanced topics such as Chained Variable Assignments, Variable Casting and Dynamically Changing Variable Types in Python.
If you enjoyed this content and would like others to benefit from it as well, make sure to share it on your favorite Social Media platform, using the share buttons below.