1.2 Python Variables#
Variable assignment follows variable_name = value, where a single equal sign = is an assignment operator. More on operators will be covered in the next section. Let’s see a few examples of how we can do this.
# Let's create a variable called "a" and assign it the number 5
a = 5
No output will be printed to the screen when you clicked on ‘Run’, because there was no print statement. The print statement will be added later.
Now if I use a in my Python script, Python will treat it as the number \(5\).
# Adding variables
a + a
What happens on reassignment? Will Python let us write over it?
# Reassignment
a = 20
# Check
print(a)
Yes! Python allows you to overwrite assigned variable names. We can also use the variables themselves when doing the reassignment.
Since a = 20 was the last assignment to our variable a, you can keep using a in place of the number 20:
a = a + 5
print(a)
Instead of writing a+a, Python has a built-in shortcut for these simple operations.
You can add, subtract, multiply and divide numbers with reassignment using +=, -=, *=, and /=, respectively.
a += 10
The above code will add 10 to the variable a every time you run that cell.
Try it yourself, run it a few times and then run the below cell to see what’s the value of a
.
print(a)
Below an example of a code that will double a every time that you run that cell.
a *= 2
print(a)
Determining variable type with type()#
You can check what type of object is assigned to a variable using Python’s built-in type() function. Common data types include:
int (for integer numbers)
float (for floating point / all real numbers)
str (for string/text)
bool (for Boolean True/False)
list
tuple
dict
set
Attention
Always check the type of your variables as this is important to determine how the variables can be used in equations.
Below a few examples:
type(a)
float_var = 3.1415
type(float_var)
a = 0.3
b = 0.2
c = a - b
print(c)
You probably noticed that Python wrote \(0.09999999999999998\) instead of \(0.1\) when calculating \(0.3 - 0.2\). We will return to this later in this Notebook.
type(1 < 2)
Boolean variables can only take on two values: True or False. They are often used to check conditions.
1 < 2
# the variable from the first script
message = 'Hello world!'
type(message)
Strings are variables represented in between ’ ‘ or ” “.
They are a sequence of values, therefore you are able to access and manipulate every character individually.
This is done with the bracket operator [], which works as an index.
Let’s take a look at our first variable from this notebook: message.
message
message[1]
What happened?
Why index [1] gave us the second letter? For most people, the first letter of the sentence Hello world! is H not e.
So.. what happened?
In Python, indexing starts at [0]. H is the zero-th character of Hello world!.
message[0]
You can also access the last value of a string using the index [-1], the before-last using [-2] and so forth.. This will turn out to be very useful!
message[-1]
Strings are immutable: you cannot reassign a new value for one of the characters. You will have to create a new string for that. Let’s try to modify our string anyway:
message[0] = 'J'
This is an example of an error message. Python tells you that something is wrong with the code you just ran. The final line gives the error itself. Above that is an indication of which line in the cell caused the error (helpful for cells with more complicated programs).
Attention
Always read and try to understand the error messages you receive, they are there for a reason!
You can also add (i.e. concatenate) strings and characters. But it will create a new string, it will not modify the old one (since they are immutable).
message + message
Now let’s see how we can select a part of a string.
message[0] + message[1] + message[2] + message[3]
A segment of a string is called a slice. Selecting a slice is similar to selecting a character. Using the operator : you select the first value that you want to get, and the first value you want to leave out of the slice, for example:
Let’s say we want to write the word Hell using our variable message, without having to type as much as above.
Which letter is the first we want to get?
H, which has index[0].Which letter is the first we want to leave out?
o, which has index[4]. So…
message[0:4]
Real life example: Analyzing satellite data
The European Space Agency (ESA) has a float of satellites called Sentinel. The Sentinel missions are based on a constellation of two identical satellites in the same orbit around the Earth. Thanks to the data of these satellite, we can monitor vegetation, soil and water coverage on a high resolution of tens of meters. The satellite looks down on the earth’s surface and covers an area with a certain width, which is called the swath width. The swath width of the Sentinel missions is hunderds of kilometers.
When the data of the Sentinel missions are downloaded, the title of the file is formatted as: S1A_IW_SLC__1SDV_20181205T015821_20181205T015851_024884_02BD8C_8700 where each part means something, S1A means Sentinel-1A, IW means Interferometric Wide Swath
20181205T015821 is a date/time, 2018-12-05, at 01h58m21s, etc.
Therefore, being able to manipulate this string is fundamental in order to organize and select satellite data. We’ll come back to this in Exercise 1.3.4.
Dynamic Typing#
Python uses dynamic typing, meaning you can reassign variables to different data types. This makes Python very flexible in assigning data types; it differs from other languages that are statically typed, where each variable has a specified data type which cannot change.
Pros and Cons of Dynamic Typing#
Pros of Dynamic Typing#
very easy to work with
faster development time
Cons of Dynamic Typing#
may result in unexpected bugs!
you need to be aware of
type().
a = 5
print('Type of a is =',type(a))
a = 'string'
print('Type of a is =',type(a))
See, now a is no longer an int type but a str type
Casting types#
Sometimes you want to change the type of a variable. For example, there is no point in arithmetically adding a number to a string. These problems can sometimes be solved with casting. Casting is a procedure of changing variable type. Actually, you create a new variable with the requested data type using the variable you want to alter.
Examples are shown below.
string_number = '123'
print(string_number, type(string_number))
integer_number = int(string_number)
print(integer_number, type(integer_number))
As you can see, both variables look the same in the output but their type now is different. Because of that, the cell below will result in an error.
string_number + 5
But the next cell will run normally.
integer_number + 5
Floating point numbers#
We have seen that mathematics with integers (whole numbers) work as one might expect. But what about real numbers (with a decimal point)? On computers, these are called floating point numbers (where ‘point’ refers to the decimal point) or ‘float’ for short.
An important thing to remember with floating point numbers is that doing mathematical operations with them is not exact, small rounding errors will appear. Even in simple calculations such as 0.3 - 0.1. Try to run the cell below and see the result.
0.3 - 0.1
It is not what you would expect to see, right? The result has an error of \(\approx 10^{-15}\). In many cases these errors can be neglected, but be careful when comparing float and int numbers, as shown below.
0.2 == 0.3 - 0.1
Indeed, \(0.2 \neq 0.19999999999999998\). A common advice is Don’t test floating point numbers for equality. Testing for larger-than, smaller-than, is generally better.
Within this course, in the end of each lesson you get an exercise Notebook which is related to the subject that was just covered. Within the exercise Notebook, there are three types of exercises: normal, fixing and searching.
Normal exercises are straight forward exercises that you should be able to solve without much trouble.
Fixing exercises are exercises where some piece of code is already written but contains an error. You need to debug it (find the cause of the error and fix it).
Searching exercises are exercises that purposefully incorporate subjects that were not covered yet, in an attempt to encourage you to try and solve issues you haven’t learned about yet.
Additional study material
Official Python Documentation - https://docs.python.org/3/tutorial/introduction.html
Think Python (2nd ed.) - Section 2
As an observation, web search quality has decreased over the last few years. For this reason, it may be helpful to search specific sites rather than using a general search engine. Some tips:
The Think Python book, open it in a web browser or pdf reader, do text search (Control + F) (but it won’t help you for this question…)
The official Python documentation, or later when you start using modules, the documentation of the module in question.
Use a general search engine, for example Stack Overflow