Python: Variables¶
Programming = rule-based processing of symbols¶
Which symbols do we have (in a high-level programming language)? Numbers and characters.
Programming means to perform actions on and with this symbols.
on = symbols are operands
with = symbols are operators
That’s what’s called executable text: the code contains instructions, which are performed when we execute it. A lot of the instructions (operations) are performed on the code itself and define/ alter the program flow.
A spatial introduction into programming with Python¶
Why spatial?
We are living in a spatial environment and we develop skills to act in space before we learn abstract thinking. Programming requires abstract thinking (and doing!), but has a spatial component.
We’ll try to combine abstract and spatial thinking and doing in this introduction into programming.
This means having a spatial mindset, focusing on where data is, in what structure it is stored and where it goes.
Small program in the visual programming language Pure Data.
Variables¶
In the last example from above, the two upper boxes represent variables, meaning placeholders for different possible values.
Variables are a very essential element of programming.
In a text based programming language like Python we have to use text to define and identify variables.
You can imagine the name of a variable as an address and the value stored inside it as the data behind that address.
In the following lines of code we will rebuild the program which adds two numbers from above with Python.
# We name the first variable "left" and assign the value 11 to it
left = 11
# The second is called "right" and assign the value -12 to it
right = 22
In Python there is no symbol (like a "." in natural language or a ";" in many other programming languages) necessary to define the end of a statement, just go to the next line and write the next statement.
# Lines that start with a # are ignored by the python interpreter.
# They are used to insert comments in your code to explain it to yourself and others.
# We can initiate multiple variables in one line of code, separated by commas:
left, right = 11, 22
If we execute the lines of code above, the variables left
and right
are initiated.
Imagine your program as a huge virtual space. When we execute the code
left, right = 11, 22
, we create two objects in this space with the corresponding names/ addresses. Each holds data, in this case the numbers 11
and 22
.
(In the beginning of programming, this space was very small, but nowadays it offers enough space for millions or billions of objects.)
If objects are available in our virtual space, we can access them. For example we can output them via a function called print
.
The function searches for the object called left
and displays its data.
print(left)
11
We can operate on them:
print(left + right)
33
We can create new variables to store results of operations:
left_and_right = left + right
print(left_and_right)
33
If we imagine this in our virtual space, it may look like this:
A third object called left_and_right
is being created and it holds as data the sum of the data of the other two objects.
print(new_variable)
new_variable = 5 # too late
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/tmp/ipykernel_14042/484762712.py in <module>
----> 1 print(new_variable)
2 new_variable = 5 # too late
NameError: name 'new_variable' is not defined
Variable names¶
In Python it is common to start variable names with lowercase characters and separate words with an _
(underscore). Like
left
left_and_right
It is possible to use numbers inside variable names, but it’s not allowed to begin a variable name with a number.
value1 = 5 # ok
value_1 = 5 # ok and better readability
1value = 5 # not working
If we try to execute this code we’ll get an syntax error, meaning we broke the rules of the language and the code is not executable.
value1 = 5
value_1 = 5
1value = 5
File "<ipython-input-8-df0835f46db4>", line 3
1value = 5
^
SyntaxError: invalid syntax
Each programming language has reserved keywords. If your code editor provides syntax highlighting, you can identify these keywords when you write them. You can’t or should not use this keywords as names for your variables.
For example if we use print
as a name, we will override our print() function, meaning we can’t print anymore (until we restart our interpreter).
# Possible but should be avoided, because it will override our print() function!
# print = 7
# print(print)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-34-033c949f272f> in <module>
1 # Possible but should be avoided.
2 print = 7
----> 3 print(print)
TypeError: 'int' object is not callable
for = 7
File "<ipython-input-33-3b857d814e92>", line 1
for = 7
^
SyntaxError: invalid syntax
The names (left
, right
, var_1
, i
, animal
, text
, paragraph
, …) are almost totally up to you. (We’ll learn exceptions later.)
Overriding variables¶
print(right)
right = 6 # This will override the variable 'right'
print(right)
22
6
If we execute the right = 6
, the Python interpreter will identify that an object with the name right
is already present in our virtual space and will change its data from 22
to 6
.
left_and_right = left + right # This will override the variable 'left and right'
print(left_and_right)
17
We can use variables as operands to override themselves:
print(left)
left = left + 7
print(left)
11
18
=
-sign is executed first. Then the result is assigned to the variable on the left.
print(left)
left = left * 2
print(left)
18
36
There is a shortcut for operations that are performed on objects themselve:
Instead of
left = left * 2
we can write
left *= 2
print(left)
left *= 2
print(left)
left += 10
print(left)
left -= 2
print(left)
left /= 2
print(left)
36
72
82
80
40.0
Output should be:
left: 6
right: 40.0
# One solution:
left, right = right, left
# Another solution with a temporary variable:
# _left = left
# left = right
# right = _left
print('left:', left)
print('right:', right)
left: 6
right: 40.0
Data types¶
As you can see the value of the variable left
is written withouth a .
, the value of right
with a .
.
These are different types of data. We can check them through the function type()
.
print(left, 'is of type', type(left))
print(right, 'is of type', type(right))
6 is of type <class 'int'>
40.0 is of type <class 'float'>
6 is an integer (ganze Zahl) (int
), 40.0 float (Kommazahl) (float
). Take care that floats are written with a dot, not with a comma.
Text is stored as type string (str
).
While integers and floats are just written down, text is defined through single, regular or triple quotation marks.
txt = 'Example text.'
print(txt)
print('''type:''', type(txt))
Example text.
type: <class 'str'>
txt = "Text inside regular quotation marks."
print(txt)
Text inside regular quotation marks.
txt = '''Triple quotation marks
are useful if you want to write
multiple lines of text.'''
print(txt)
Triple quotation marks
are useful if you want to write
multiple lines of text.
Casting¶
Python automatically adjusts the type of the variable according to the value. (In some programming languages we have to set the type manually before we assign a value to it.)
But it’s possible to change the data type (casting):
float() # Transforms data into a floating number.
int() # Transforms data into an integer.
str() # Transforms data into a string.
left = float(11)
print('left as float:', left)
left = int(left)
print('left as integer:', left)
left = str(left)
print('left as string:', left)
left as float: 11.0
left as integer: 11
left as string: 11
Be aware that the last 11 is not a number anymore for the Python interpreter. See:
print(left * 2)
1111
But as long as the string contains only numbers we can cast it back to a real number.
left = '11'
left *= 2
print(left * 2)
left = int(left)
print(left * 2)
11111111
2222
But we can’t transform a written number into an integer or float:
left = int('eleven')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-29-dc9ae2a2dfed> in <module>
----> 1 left = int('eleven')
ValueError: invalid literal for int() with base 10: 'eleven'
- Initialize a new variable
- Assign a value of type float or int to it.
- Print it.
- Cast it to the other type (int or float).
- Print it.
- Override the variable with a string and print it.
# One possibility:
m = 45.2
print(m)
m = int(m)
print(m)
m = 'the quick brown fox jumps over the lazy dog. '
print(m)
45.2
45
the quick brown fox jumps over the lazy dog.
Programs are text (files)¶
For example:
txt = 'Hello, World!'
print(txt)
Open the command line of your operating system (see help for Linux, Mac, Windows).
To execute python code that is stored in a .py file, write python
or python3
(if Python 2 is your default version) followed by the name of the file including the filepath. (You can write python
, then drag and drop your .py file into the terminal and then press enter
to execute it.
Type in your terminal window:
python3 /path/to/folder/001.py
The code is stored in a plain text file. As a proof we can change its suffix from .py to .txt and open the file with Python.
Of course this was just for demonstration purpose and you should always use the correct suffix!
Btw, the code of the Pure Data program is a plain text file as well and we can open it with a normal text editor:
#N canvas 981 313 450 300 12;
#X floatatom 109 90 5 0 0 0 - - -;
#X floatatom 198 87 5 0 0 0 - - -;
#X obj 198 111 t b f;
#X obj 143 156 +;
#X floatatom 143 200 5 0 0 0 - - -;
#X connect 0 0 3 0;
#X connect 1 0 2 0;
#X connect 2 0 3 0;
#X connect 2 1 3 1;
#X connect 3 0 4 0;