How to use variables in Python ?
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
First of all, in Python and a lot of other programming languages variables are a way to store temporary values that will be used within the execution of our program.
Second, in Python unlike a lot of other languages you don't need to specify the type of variable when creating a variable.
Third, a variable can change its type along the way. It is not recommend but Python can handle it.
Here are all the possible variables that you can use in Python:
- Numbers (integer, float, complex)
- Strings (single quote, multiple quote, multi-line)
- Booleans
- Data Structures (Lists, Dictionaries, Tuples, Sets, ...)
- Files
Our focus in this article are about 1,2 and 3.
Assign a value to a variable
When you first declare the variable and assign a value to it, the variable is created.
Here are some examples :
age = 27 # An integer
gpa = 5.7 # A float
name = "Brice" # A double quote string
has_siblings = True # A boolean
quote = """ # Multi line string
The world as we have created it is a process of our thinking.
It cannot be changed without changing our thinking.
Albert Einstein
"""
Edit the value of a variable
When a variable already have a value like above, it is totally possible to reassign a new value to it.
age = 28 # Assigning a new value to an integer
gpa = 5.5 # Assigning a new value to an float
name = "James" # A double quote string
Show the value of a variable
There is in Python a general method to show the value of a variable within a console.
Here is an example that prints the variable age with a value of 28
age = 28
print(age)
F-string printing
You will need to print multiple variable along with text.
Here is the best method to do that has been introduced in Python 3.6
age = 28
name = "Brice"
print(f"My age is {age}")
print(f"{name} age is {age}")
Delete the variable
You might need once or twice to delete the value of a variable for various reasons.
Using the del attribute before a variable you delete it.
This frees up memory space
Here is how you do it :
age = 28
del age
Here you are ! You now know how to use a variable in Python !
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Related Articles
Continue your learning journey with these related topics
Master Data Science in Days, Not Months 🚀
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚