We will also look at a simple command to show you all reserved keywords in Python, by the end of this post you will be very well versed in Python variables as well as understand how Python variables act as a pointer to objects in memory and at which point Python's garbage collector is required to reclaim allocated memory.
Variables are containers used to hold values, this makes it possible to reference the contained value multiple times throughout the execution life cycle of the program.
Without variables, it will be a real challenge to write computer programmes.
Topics covered in this post:
Let's explore how to use variables...
To assign a value to a variable you use the =
operator, the variable name would be on the left side of the =
operator and the value to the right. Below we are going to explore different ways of assigning a value to a variable.
# add "Kingsley" to the variable `name`
name = "Kingsley"
# output => Kingsley
print(name)
# assign same value to multiple variables on the same line
a = b = c = 'cat'
print(a) # output => cat
print(b) # output => cat
print(c) # output => cat
# assign a different value to multiple variables on the same line
a, b, c = 'cat', 'dog', 'horse'
print(a) # output => cat
print(b) # output => dog
print(c) # output => horse
# reuse variable name, last assignment is printed
colour = 'Red'
colour = 'Blue'
print(colour) # output => Blue
Above you learnt how to assign values to variables, now we are going to learn the rules around variables names, not all names are legal, let's have a look at some examples below.
# legal variable names
firstname = "Kingsley"
first_name = "Kingsley"
_first_name = "Kingsley"
firstName = "Kingsley"
firstname2 = "Kingsley"
FIRSTNAME = "Kingsley"
# illegal variable names
2firstname = "Kingsley"
first-name = "Kingsley"
first name = "Kingsley"
Underscores are allowed in variable names, numbers are allowed as long as it is not placed as the first character in the variable name, you cannot use dashes or have spaces in the variable names.
Using an invalid variable name will product an invalid syntax error: SyntaxError: invalid syntax
There are additional invalid names when it comes to creating variables, and these are the reserved keywords. Python 3.8 has 35 reserved keywords that you cannot use as variable names.
Below is a list produced by typing into python console: help("keywords")
'''
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
'''
False = 'hello' # output => SyntaxError: invalid syntax
class = 30 # output => SyntaxError: invalid syntax
from = 'hi' # output => SyntaxError: invalid syntax
In some other languages, variables a statically typed, which means that once you create them you also declare what type of data they accept and therefore they cannot accept any other data types.
In python things are done differently, a variable can change its type at any point during execution, let's have a look at how to override a variable value type and how to print out the type of value held by any variable using the type
function.
# first assign a string to var
var = "Hello World!"
print(var) # output => Hello World!
type(var) # output => <class 'str'>
# assign an int to var
var = 23
print(var) # output => 23
type(var) # output => <class 'int'>
Above shows that we can create a var
assign a value of type string
into it and then override that and assign a value to type int
to the same variable and it is all perfectly legal.
In python every object that is created is given a unique number for identifying that object, so when we create a variable and assign value into it, that variable will also have a unique id
associated to it.
# print the id for int stored in a variable
score = 400
id(score) # example output => 4341576592
As you can see from the above example, calling id() method will give you a unique identifier. But what happens as int he example below?
# score variable is saved into pb by reference
score = 400
pb = score
id(score) # output => 4342358576
id(pb) # output => 4342358576
As you can see from the output above the id
printed for both score
and pb
are exactly the same, your id will be different values compared to mine since they are unique for each computer, but they will be identical to each other.
Python simply points to the same reference, so both score and pb are pointing to the same object in this case, below we will look at object reference
in more detail.
When you assign a value to a variable ( score = 100 )
the following happens:
score
points to it.If you then assign the variable score
to another variable pb
, then below is what happens:
score
variable point to int object containing 100pb
variable also point to the same int object containing 100'''
both score and pb point to same int object
score ---------> int 100 <--------- pb
'''
score = 100
pb = score
type(score) # output => <class 'int'>
type(pb) # output => <class 'int'>
score # output => 100
pb # output => 100
'''
point pb to new location (int 20), score remains pointing to int 100
pb ---------> int 20
score ---------> int 100
'''
pb = 20
type(score) # output => <class 'int'>
type(pb) # output => <class 'int'>
score # output => 100
pb # output => 20
'''
point score to str 'Completed' this means int 100 still exists but not being
referenced by any variable and therefore at some point will be garbage collected by Python.
pb ---------> int 20
score ---------> str 'Completed'
---------> int 100
'''
score = 'Completed'
type(score) # output => <class 'str'>
type(pb) # output => <class 'int'>
score # output => 'Completed'
pb # output => 20
You will come across object lifecycle from time to time, as you saw from above, when we create int or str objects we reference them by pointing a variable to it, we can increase the number of references to each object as seen above with score
and pb
pointing to the same object int 100.
When the reference goes down to zero, e.g no variable is pointing to that object, then Python will reclaim that allocated memory using a process known as garbage collection.
In this blog post you learnt the basics of Python variables, explored how to assign values to them, multiple values in one line etc, you also learnt about object reference and object identification.
Read this again, book mark this page if you need to, know it by heart because Python variables will play a big role as you continue on your journey into learning to code Python.
Please share this post with your audience.
Happy coding...