python basics

Setting up the environment

This chapter is intended to be a Python crash course: first we install all the software needed, then we move on to programming basics. The goal is to provide the reader with all the tools necessary to progress through the rest of the material, so it's very important that you follow through and understand everything that is written here. It will be useful, during the chapters that follow this one, to come back here every time you don't remember some particular Python syntax.

Installing Anaconda

One of the easiest ways of getting python up and running on your computer is using the Anaconda distribution. Anaconda comes pre-packed with the most popular libraries for python (so you won't have to install them yourself), and also Jupyter, which is the notebook environment that we will use to write code. the instructions given here are intended for Microsoft Windows, but the same overall process applies for other operating systems, In order to install Anaconda:

  • Open your web browser and navigate to https://www.anaconda.com/download/ and select your operating system;
  • Select the version of Python that you wish to download. At the time this book was written, the latest version supported by Anaconda was Python 3.7. DO NOT download a version that uses Python 2, as some of the examples written in this book work only with Python 3;
  • Once the installer has finished downloading, open it and follow the instruction to install Anaconda. I suggest leaving the default path as the destination folder.

Once Anaconda has finished installing, open Anaconda Navigator by typing  "Anaconda navigator" in your computer's search bar. You will be greeted by a window that looks similar to the one in the next figure

 

Anaconda navigator is essentially a hub from where you can access various Python coding environments. Qt console is a command line type of editor, Spyder is a scripting editor, and finally Jupyter is a notebook editor. This is the one we are going to use, so click launch to open up Jupyter Notebook.
This will open your default browser and display your computer's folder tree. In the address bar there should be written http://localhost:8888/tree. From this window you can navigate within the folders of your computer, open existing Jupyter notebooks, and create new ones.

Using Jupyter notebooks

To create a new Jupyter notebook, navigate to a folder of your choice and select new>python3 from the top right-hand of the screen. This will create a new Jupter notebook in the folder you have selected. Your browser should then display something similar to what you see in the next image.

Jupyter is a notebook environment, which means that you have to write code inside cells. The frame in the previous image that says "ln" is a cell. If the frame is highlighted in blue, it means that the cell is selected and ready to be edited. Before we start writing some code, let's go over the various tools and drop-down menus that Jupyter offers, so that you have a clear idea of how the interface works.

  • from the File menu we can open, save, rename, export, and close notebooks;
  • from the Edit menu we can copy, cut, merge, move, and delete cells;
  • from the Insert menu we can insert a new cell above or below the one that is currently selected;
  • from the Cell menu we can select various options to run the cells in the notebook. For example we can run a single cell, or the entire notebook. In addition, from this menu we can change the cell's type;
  • from the Kernel menu we can manage the notebook's kernel. The kernel is basically the computational engine that runs the code written in the cells. It also stores all the variables you declare in your code;
  • from the Widget menu we can manage the notebook's widgets, which are essentially extensions that can be installed to expand the capabilities of Jupyter;
  • from the Help menu you can start a user interface tour (I suggest you try it), open various reference manuals and display the shortcut window.

The icons below the menu let you quickly select some of the tools present in the drop-down menu described above. Let's focus our attention on the little drop-down window that says "code": from here we can change the cell's type from code to markdown. Markdown is a typesetting language used to format your notebook. Usually, a well formatted notebook is made out of both code type cells and markdown type cells. The first contain all the various algorithms and calculations, the second contain text that explains what the code does, or that displays the result of the code cells. Let's leave the cell's type to code for now, and click inside the frame of the cell. The frame turns green: we can now write some code inside it. Let's write

 

Hello World!

 

and click the Run button. Congratulation, you have written a python program! Notice that the output of the cell is displayed below the code. A cell does not necessary display an output: if there are no instructions to do so in the code, the cell will simply run without showing anything.

Now that we got the classic "hello world" example out of the way, we can start to explore the functionalities that python offers to its users. In the next few sections you will learn how the syntax of the language works, and how to use some of the libraries that are available.

Comments

Comments are lines of code that are ignored upon execution. They are used to comment and explain what the code does, in order to keep everything as clear as possible. Their usage is explained in the next code snippet.

 

# This is a single line comment
'''This is a multiline comment'''

 

as you can see python offers two ways of writing comments. The first one uses the # symbol to write a single line comment, the second one uses the ''' sequence of characters to open and close a multiline comment.

Variables and datatypes

Variables are containers where you can store values. The main types of data structures that are built-in in python (and that can be used without loading any library) are:

  • int: integer numbers;
  • float: floating point numbers;
  • bool: boolean-type values True or False);
  • string: sequences of characters;
  • list: python's built-in arrays;
  • dict: Dictionaries;
  • tuple: tuples;

Let's go ever them in detail.

 

Integer numbers

This datatype represents integers, which are numbers without decimal values. Select an empty code cell and write the lines given in the next code snippet:

 

a=1
b=2
c=a+b
print(c)

3

We assign the values 1 and 2 to the variables a and b, then we sum them and store the result in variable c, and finally we print the value of c. a and b are integer values, and since c is the sum of two int-type objects, c it's an integer as well. As you may have guessed, the print  function is used to display the value of whatever argument you put between the parenthesis.

Floating point numbers

This datatype is used to represent, to put it mathematical terms, real numbers. They can be specified by using a decimal point, or using scientific notation. The next code block gives an example of their behavior:

a=1.0 #this is a floating point number
b=12.345 #this another floating point number
c=2.4e5 #this is floating point number specified using scientific notation
print(type(a))
print(c/b)

<class 'float'>
19441.069258809235

The function type() is used to retrieve the dtype of a certain object within the code. This function however does not print its output: we can achieve that by nesting the type and the print methods inside one another. As you can see, floating points numbers in python are called floats.

Boolean values

Boolean values are like switches, they can be True or False. They are really useful when specifying conditions in your code, as will be explained later. Let's see how to create them:

a=True         #this is a bool value
b=False #this another bool value
print(type(a))
<class 'bool'>

Strings (str)

Strings are sequences of characters, and are used to represent text. You can open and close a string by using either the '' characters or the "" characters. If you want to use one of these characters inside the string, simply add a backslash \ before the character you want to insert in the string. It's much better to understand these concepts by seeing them in action, like they are presented in the next code snippet

string_1="Hello"
string_2='World'
string_3="The quick 'brown' fox jumps \"over\" the lazy dog"
print(string_1)
print(string_2)
print(string_3)
Hello
World

As you can see in line 3, it's possible to use a ' character inside a string that has been specified with the " character. However if the string has been specified using " and we want to insert that same character inside it, we have to precede " with a backslash. 

Now let's take a look at the next piece of code:

a="Hello"+" World"
b=2+2
print(a)
print("The result of 2+2 is: {0}".format(b))
Hello World
The result of 2+2 is: 4

Python lets the user concatenate strings using the plus sign, an operation that we will be using a lot throughout this book. In line 4 we see another very powerful feature: string formatting. With the .format() method python lets you insert variables within a string, in the places specified by the numbers between the curly brackets. The method .format() can accept multiple arguments, as shown in the next code block:

a=12
b=3
print("a={0} and b={1}".format(a,b))
a=12 and b=3

This time we pass two variables to the format function, which are inserted in the string at the positions specified by the curly brackets. Since a is the first argument that we pass to .format(), it will be inserted in the position specified by the curly brackets that contain 0, and since b is the second argument,it will be inserted in the position specified by the curly brackets that contain a 1.

This type of operation will be used a lot in the next chapters, as a way to better visualize the results of the calculations.

Lists (list)

Lists are used to represent a sequence of objects. If you have used other programming languages before, you can think of lists as arrays in which you can store any type of data you want. This includes integers, floating point numbers, strings, other lists, etc.. If you haven't used another programming language before, think of lists as vectors or matrices, depending on the dimension of the list itself. Let's now go over some examples, to understand how to create lists and how to use them.
In the next code block we see some of the basic operations that involve lists:

myList1=[1,2,3,4] # this creates a list of integers
myList2=["hello", 2, 4.15, myList1]
mat=[[1,2,3,4],[5,6,7,8],[9,10,11,12]]

print(myList1)
print(myList2)
print(mat)
[1, 2, 3, 4]\\
[}hello', 2, 4.15, [1, 2, 3, 4]]\\
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

As you can see, lists are just collections of objects specified using square brackets and commas. You can nest lists one inside another to create multidimensional data structures, like you see in line 3. Next, we explore how to retrieve data from lists:

a=[2, 4, 16, 32]
print(a[0]) #prints the first element of a
a[1]="hello" # assign 'hello' to the second position of a
print(a)
b=[[3,6],[9,12]]
print(b[0][1]) #prints element in position 0,1 of b
[2, 'hello', 16, 32]

To access a value within a list, use the square brackets to specify the index of the element you wish to retrieve. In python, lists are indexed starting from zero, so the first element is in position 0, the second is in position 1, and so on. If you have a previously defined list and you wish to change one of its values, simply assign the new value to the position you want like you see in line 3. If a list is multidimensional, like the one defined in line 5, to access a specific position you need use two sets of square brackets (line 6).

Lists have also built-in methods that you can use to perform operations on their content. Let's explore some of the most useful of these functions:

a=["dog", "cat", "lion"]

a.append("seal")
print("append: {0}".format(a))

a.insert(2, "ant")
print("insert: {0}".format(a))

a.remove("dog")
print("remove: {0}".format(a))

a.pop(3)
print("pop: {0}".format(a))

a.extend(["apple", "pear"])
print("extend: {0}".format(a))
append: ['dog', 'cat', 'lion', 'seal']
insert: ['dog', 'cat', 'ant', 'lion', 'seal']
remove: ['cat', 'ant', 'lion', 'seal']
pop: ['cat', 'ant', 'lion']
extend: ['cat', 'ant', 'lion', 'apple', 'pear']

To access object's built-in functions in Python we use the dot  followed by the name of the method. Confronting the input and output of the previous code panel you can get a pretty solid idea of what each of these functions does, and I invite you to experiment with them in order to fully understand their behaviour. Let's go over them anyway, together with some other functions provided by python for lists:

  • index(value): Returns the position of the first element of the string that corresponds to value
  • insert(pos, element): Adds element in the position specified by pos;
  • pop(pos): removes the element in the position specified by pos. If pos is not specified, removes the last element of the list.
  • remove(value): Removes the first element of the list that corresponds to value;
  • reverse(): Reverse the order of the elements in the list;
  • sort(): Sorts the elements in the list.

Dictionaries (dict)

Dictionaries are similar to lists, except that they are unordered. Each element in a dictionary has a key associated to it that acts like its name. To retrieve an element from a dictionary, you call the key associated with that element. Let's look at the next piece of code:

 

mydict={"object" : "beam",
        "material" : "steel",
        "type" : "IPE120",
        "h" : 120,
        "b" : 64}

print(mydict["material"])
steel

Dictionaries are specified using curly brackets, in which each key is associated with the corresponding value. When we want to access one of the values of the dictionary, we need to use its key. Since they have similar built-in methods as lists, we won't go over them again.

Tuples

Tuples are collection of objects that are ordered and unchangeable. This means that after you create a tuple you won't be able to modify its values in any way. The next code block shows how to create a tuple and use the only two methods provided for them by python:

mytuple=(1,2,3,"apple",5)
print(mytuple)

print(mytuple.count("apple"))
print(mytuple.index(5))

print(mydict["material"])
(1, 2, 3, 'apple', 5)
1
4

As you can see, tuples are specified like lists, except they use round brackets instead of curly brackets. The two methods that can be used on a tuple are count and index. The first counts the number of elements within the tuple that correspond to the argument passed, the second returns the position of the first occurrence.

Conditions and statements

Python, like all other programming languages, gives the user the possibility of running pieces of code only when a specific condition is met. This is done through IF statements, which evaluate a proposition and execute the next chunk of code based on whether that proposition was true or false. let's see an example of an IF statement:

x=3
y=5

if x<y:
    print("x is smaller than y")
else:
    print("x is greater than y")
x is smaller than y

First, we assign values to variables x and y. Then the IF statement is introduced by using the keyword if followed by the condition x<y. If x is indeed smaller than y, then the first block of code is executed. If not, the block of code that follows the keyword else is executed. If there is no else keyword after the IF statement, and the condition is False, then the code written inside the statement will be ignored. This example also introduces a very important concept, explained in the next paragraph.

Python indentation

In other programming languages, the indentation of the code is merely a praxis to make it more readable. In python, indentation is instead used to specify blocks of code, and is mandatory for the code to work. Note that line 5 of the previous code is indented: that's because it represents the block of code that the IF statement will execute if the condition x<y is true. Notice that a  block of code will always be introduced by a semicolon, like we see at the end of line 4.

Python conditions

We find in python all the usual logical conditions from math:

  • Equals: a == b
  • Not equals: a != b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Less than: a < b
  • Less than or equal to: a <= b

Where a and b are two predefined variables.

The ELIF statement and logical operators

What if we want to specify more IF statements one after another? This is what the ELIF statement is for:

beam = {"mat" : "steel", "E" : 210000}

if beam["mat"] == "concrete":
    print("This is a concrete beam")
elif beam["mat"] == "steel":
    print("This is a steel beam")
elif beam["mat"] == "wood":
    print("This is a wooden beam")
else:
    print("I do not recognize the material")
This is a steel beam

The ELIF statements uses the same syntax as the IF statement, and can be called as many times necessary. The ELIF chain can be closed by an optional ELSE statement, that will be executed if all the conditions written before resulted to be False.

Next we learn about logical operators, used to combine multiple conditions together.

a, b, c = 1, 2, 3

if a < b and b < c:
    print("a<b<c")
a<b<c

Before discussing the IF statement, let's examine the first line: this is a shorthand notation used to assign a set of values to a set of variables. It simply stores 1 in a, 2 in b and 3 in c. Moving on, in line 3 we see the logical operator and. This operator returns True only when both the conditions associated with it are True. In this case, since the conditions a<b and b<c are indeed both true, the code inside the IF statement is executed. In python there are three logical operators:

  • and: returns True if both statements are True;
  • or: returns True if at least one of the two statements is True;
  • not: used to reverse the result of a condition (e.g. not(True) will return False).

Shorthand notation

The IF statement can also be written using only one line of code. It's important that you know how to use this type of notation as well, although it's not strictly necessary. A lot of examples that you find on-line use shorthand notation, so knowing how it works will certainly help you better understand them. Let's look at the next piece of code:

x, y = 10, 5
if x>y: print("x>y")
print("x>y") if x>y else print("x<y")
print("x>y") if x>y else print("x=y") if x==y else print("x<y")
x>y
x>y
x>y

First, we assign two values to x and y, using the same shorthand notation that we already saw previously. In line 3 we see the shorthand notation for a single IF statement: it's the same as a normal IF statement, except we write the code in one single line. In line 3 we see the shorthand notation for the IF-ELSE statement. This one is a little bit different, because the order in which the condition and the code to execute are written is reversed. The first print command is executed if x>y, otherwise the code that follows the keyword else is executed. Having understood this, it should be easy to read the fourth line: this is the shorthand notation for a statement that normally would use the elif  keyword. Instead of stopping the chain after the else keyword, we pass another shorthand IF statement that uses exactly the same notation as the one in line 3.

Go to the next section:

Numpy tutorial