1.2. Python Variables#

One of the most powerful features of a programming language is the ability to create and manipulate variables. A variable is a labeled storage that refers to a value. They are usually used in a way to make the code more readable, allowing reusability of your code.

As it was mentioned previously, Python is a high-level programming language. For that, it uses concepts of Class and Object. In short, a Class is a defined model or a data structure, it describes how the data of that class can be described and how it can be manipulated, and an Object or Instance is its realization. In other words, think about your favorite meal: the recipe is the Class of your meal and when you decide to use the recipe and cook it — you create an Object of that Class. Variables are the way how objects are stored and processed.

1.2.1. Rules for variable names#

  • names can not start with a number

  • names can not contain spaces, use _ instead

  • names can not contain any of these symbols:

    :'",<>/?|\!@#%^&*~-+
    

Note

  • it’s considered best practice (PEP8) that names are lowercase with underscores

  • avoid using Python built-in keywords like list and str

1.2.2. Assigning 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 an object called a and assign it the number 5

a = 5

Now if I call a in my Python script, Python will treat it as the number \(5\).

Adding the objects

a + a
10

What happens on reassignment? Will Python let us write over it?

a = 20

Check

print(a)
20

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
40

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)
30

Below an example of a code that will double a every time that you run that cell.

a *= 2
print(a)
60

1.2.3. 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

Warning

Always check the type of your variables when debugging!

Below a few examples:

type(a)
int
float_var = 3.1415
type(float_var)
float
a = 0.3
b = 0.2
c = a-b
print(c)
0.09999999999999998

You probably noticed that Python wrote \(0.09999999999999998\) instead of \(1\) when calculating \(0.3 - 0.2\). Ignore it for now, this is explained later in this Notebook.

type(1<2)
bool

Boolean variables can only take on two values: True or False. They are often used to check conditions.

1<2
True

The variable from the first script

type(message)
str

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
'Hello world!'
message[1]
'e'

Nani???

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]
'H'

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 also immutable. You cannot reassign a new value for one of the characters. You will have to create a new string for that.

message[0] = 'J'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[20], line 1
----> 1 message[0] = 'J'

TypeError: 'str' object does not support item assignment

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
'Hello world!Hello world!'
message[0]+message[1]+message[2]+message[3]
'Hell'

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.

  1. Which letter is the first we want to get? H, which has index [0].

  2. Which letter is the first we want to leave out? o, which has index [4]. So…

message[0:4]
'Hell'

One can also use our variable message to write the sentence Hold door.

message[0]+message[4]+message[-3:-1]+message[5]+message[-2]+2*message[4]+message[-4]
'Hold door'

Note

Real life example: Analyzing satellite data

Sentinel data title 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, 2018 12 05, at 01h58m21s, etc.

Therefore, being able to manipulate this string is fundamental in order to organize and select satellite data.

Exercise

Exercise

1.2.4. Dynamic Typing#

The way the computer is able to use the stored data becomes an attribute of the stored data. This attribute is called a data type. Python uses dynamic typing, meaning you can also reassign variables to different data types. This makes Python very flexible in assigning data types; it differs from other languages that are statically typed.

1.2.4.1. Pros and Cons of Dynamic Typing#

1.2.4.1.1. Pros of Dynamic Typing#

  • very easy to work with

  • faster development time

1.2.4.1.2. 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))
Type of a is = <class 'int'>
Type of a is = <class 'str'>

See, now a is no longer an int type but a str type

1.2.5. 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. Or, when estimating the amount of oil wells, those should be integers (how would you build \(2.5\) wells?). These two problems can be sometimes solved with casting.

Casting is a procedure of changing variables 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))
123 <class 'str'>
123 <class 'int'>

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
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[28], line 1
----> 1 string_number + 5

TypeError: can only concatenate str (not "int") to str

But the next cell will run normally.

integer_number + 5
128

1.2.6. How do computers read variables?#

Computers and humans have different views on data. We, fellow humans, can easily read poetry and enjoy music. Computers are limited in that sense and they can operate on a really primitive level. They cannot even read normal text, for a computer, everything is represented with numbers. One of the popular text encodings ASCII has a table, where every symbol there is an integer number assigned to it. Letter ‘a’, for instance, has a value of \(97\), and letter ‘A’ has a value of \(65\). The value of ‘B’ is \(66\) and if we want to take the letter before ‘B’ we just calculate \(66 - 1\). You don’t have to open an alphabet and, therefore, it is easier to work with numbers than with letters.

But even for numbers, computers have their own approach. On a really low level, all numbers are stored and operated in their binary form. Number \(5\) becomes \(101\), because \(5 = 1\cdot2^2 + 0 \cdot2^1 + 1\cdot2^0\). And since all symbols are also represented with numbers, it is not hard for computers to operate with them. But what about the floating numbers? How do you represent \(1.5\) or \(\pi\)? Well, computers try to represent them with binary code, which introduces some problems. In order to represent a fraction, they need an infinite amount of bits, to obtain the precision we use in math. But that’s impossible! In other words, small errors will always be present in calculations as simple as \(0.3 - 0.2\). From your math classes you know that the result of \(0.3 - 0.2 = 0.1\), not \(0.10001\) or \(0.09999\). But try to run the cell below and see the result.

0.3 - 0.1
0.19999999999999998

It is not what you would expect to see, right? The result has an error of \(\approx 10^{-15}\). In most cases, it can be neglected but be careful when comparing float and int numbers, as shown below.

0.2 == 0.3-0.1
False

Indeed, \(0.2 \neq 0.19999999999999998\).

Note

Within this course, in the end of each section you’ll find exercises related to the subject that was just covered. 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 and you need to debug it (find the root 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.