Variables and Types#
No programs works without variables to store data values in while the program runs. Variables in Python are strong dynamically typed which mean you can change a variable from a number to a string by assignment, but a variable will not become a number when a string contains a number for example. This also means you may have to cast variable from a number to a string in some cases or vice versa.
Python has the following data types built-in by default, listed per category in the table below:
Category |
Data type |
---|---|
Text Type |
|
Numeric Types |
|
Sequence Types |
|
Mapping Type |
|
Set Types |
|
Boolean Type |
|
Binary Types |
|
The basics about variables#
Let start with basic example based on our Hello World. application where we have two lines. And in this example we still present print directly with a string telling about two people called John and Jack, and their age.
1#!/usr/bin/env python3
2
3def main():
4 print("My name is John and I am 42.")
5 print("My name is Jack and I am also 42.")
6
7
8if __name__ == "__main__":
9 main()
1My name is John and I am 42.
2My name is Jack and I am also 42
Lets put the name and age both in their own variable as a string and update the strings to concatenate the whole string together. Here we use the +
-sign to concatenate strings together in Python. We first define the variables name
and age
with their content on lines 4 and 5, and print it on line 6.
1#!/usr/bin/env python3
2
3def main():
4 name = "John"
5 age = "42"
6 print("My name is " + name + " and I am " + age + ".")
7 name = "Jack"
8 print("My name is " + name + " and I am also " + age + ".")
9
10
11if __name__ == "__main__":
12 main()
Looking at the output below we also see that assigning the value Jack
to variable name
on line 7 changes the output on line 8. This way we can update the value of a variable while the application is being executed.
1My name is John and I am 42.
2My name is Jack and I am also 42
Getting a variable type#
Python can also determine the data type of a variable with type()
. This can become useful when importing data from unknown source and needs validation, or to determine if a variable needs to be casted.
1#!/usr/bin/env python3
2
3def main():
4 name = "John"
5 age = 42
6 print(type(name))
7 print(type(age))
8
9
10if __name__ == "__main__":
11 main()
1<class 'str'>
2<class 'int'>
Casting variables#
Python is flexible with its data types for variables, but Python does require type casting in some cases. Using a variable that contains a number that needs to concatenated with a string needs to be casted from an integer to a string. In the example below we forget to type cast a string and it fails.
1#!/usr/bin/env python3
2
3def main():
4 name = "John"
5 age = 42
6 print("My name is " + name + " and I am " + age + ".")
7
8
9if __name__ == "__main__":
10 main()
1Traceback (most recent call last):
2 File "/workspaces/learning-python/example.py", line 10, in <module>
3 main()
4 File "/workspaces/learning-python/example.py", line 6, in main
5 print("My name is " + name + " and I am " + age + ".")
6TypeError: can only concatenate str (not "int") to str
If we type cast the variable age
from integer to string with the str()
function it works perfectly. Other functions to type cast are int()
and float()
.
1#!/usr/bin/env python3
2
3def main():
4 name = "John"
5 age = 42
6 print("My name is " + name + " and I am " + str(age) + ".")
7
8
9if __name__ == "__main__":
10 main()
Variable scope#
Variables are scope sensitive and in the example below we define the variable on a global level and can be read scopes of functions and methods. Having global variables isn’t a good idea as it leads to messy programming. For constants this is fine, but the variables should only be read from and not updated.
1#!/usr/bin/env python3
2
3phrase = "Hello World."
4
5def main():
6 print(phrase)
7
8
9if __name__ == "__main__":
10 main()
1Hello World.
Variables can have a global and local scope. In the example below we set the variable on a global level, but override it with a different value as a local variable.
1#!/usr/bin/env python3
2
3phrase = "Hello World."
4
5def main():
6 phrase = "Hello People."
7 print(phrase)
8
9
10if __name__ == "__main__":
11 main()
1Hello People.
Python also has the option to turn local variables in global variables as in the example below. The extra function setup()
uses the keyword global to make the variable x
a global variable.
1#!/usr/bin/env python3
2
3phrase = "Hello World."
4
5def setup():
6 global phrase
7 phrase = "Hello People."
8
9
10def main():
11 print(phrase)
12
13
14if __name__ == "__main__":
15 setup()
16 main()
1Hello People.
Warning
Using global variables is considert bad programming and a risk as it can have unforeseen effects.
Variables are references#
Variables in Python don’t store the value assigned to them, but are a reference to where the value is stored in memory. With the function id()
an unique identifier is returend for every object stored in memory, and for the CPython implementation this identifier matches the address in memory.
As Python works with references, copying a variable is in reality copying the reference towards the value and not the value itself. The example below shows this as the reference for var1
and var2
are the same after copying, and only changes for var2
when a new value is assigned.
1#!/usr/bin/env python3
2
3def main():
4 var1 = 'test string 1'
5 var2 = var1
6 print(id(var1))
7 print(id(var2))
8 var2 = 'test string 2'
9 print(id(var2))
10
11
12if __name__ == "__main__":
13 main()
1140676515962032
2140676515962032
3140676516592816