Introduction

Goals

This tutorial assumes that you already have some basic knowledge of the Python programming language (or some other programming language). It is meant to be concise, with the main goal of reviewing both basic concepts and more advanced notions we may use in this course. It is not meant to be a complete document. Python is such a rich programming language that this would be a futile exercice.

It is likely that, for some of you, a lot of this material can be skipped. At a minimum, this will serve as a quick review.

Some of the simple codes are available to download so you run with them on your machine. You can also cut and paste them. Of course, your first action is to install Python 3 (do not install Python 2) on your computer, if you have not done so. You should absolutely install an IDE for python like Spyder or Jupyter. There are many good IDEs for Python, with such features as syntax highlighting and integrated debugging.

Basic Features of Python

Python

Need Help?

You can get help within the Python interpreter. For instance, you would like to know the syntax of a particular object: just type help(<object>). As an example, if want some information about the quad function of the integrate submodule in the scipy module, type

from scipy.integrate import quad

help(quad)

you will get a description of the function, its parameters, the output it returns, and some simple examples of its use.

How do I learn Python?

Python is a great language for scientific computing. The best way to learn Python is to use it with the goal of solving scientific/engineering problems.

Syntax

Each programming language has its specific syntax. Here are a few key features of Python:

Examples:

x = 3
x += 2
print(x)
x -= 1
print(x)

"""This is a multiline comment.
Here we show how to concatenate two strings."""
string1 = "Hello"
string1 += " class!"
print(string1)
# Here is a way to swap two variables in one shot.
x, string1 = string1, x
print(x)

Data Types

As the previous example shows, to create a variable, you simply have to assign it a value. Variables in Python are implicitly declared by defining them, i.e. the first time you assign a value to a variable, this variable is declared and has automatically the data type of the object which has been assigned to it, such as an integer, a float, or a string. It is not necessary to declare the type of variable. For example, try this:

x = 1
print(x)
print (type(x))

On output, you will get <class 'int'>. Try now to change x = 1 to x = 1.0 (a float) or to x = "hello!" (a string).

It is possible to ask the user of your code to input to be assigned to a variable. A variable obtained by the input() instruction is a string variable. To convert it to an integer, you must use the function int().

x = input('Enter x = ') # this asks for a number which will be assigned to variable x
print (x)
print (type(x)) #  <class 'str'>
y = int(x) # convert x of type 'str' into type 'int'
print (y)
print (type(y)) #  <class 'int'>

A string is an array filled with characters. Strings can thus be manipulated like arrays. The numbering of the characters of a string starts at 0. Let’s try this:

name='Gabriel'
print(name)
print(name[2:6])    # extract the characters 2 (included) to 6 (excluded)

It is possible to add string

print ('Scientific' + ' Programming')

The length of a string is obtained with the function len(). There exists many functions to manipulate strings. See this Pyformat Guide.

A variable can be converted from one type to another:

x = float(1) # a real number from an integer
print (type(x)) # <type 'float'>
y = float('1.0') # a real number from a string
print (type(y))  #  <type 'float'>

Basic Operations

Try the operations of division /, floor division //, and power on numerical types:

print (7/2, 7//2, 3**2)

gives:$\qquad$ 3.5 3 9

print(5.0/2, 5.0//2)

The modulo operation n%q gives the floor division of n by q

print (4%3, -1%3) # 4 modulo 3, (-1) modulo 3

gives: $\qquad$ 1 2

print (7.5%3.0, -2.5%3.0) # 7.5 modulo 3.0, (-2.5) modulo 3.0

gives: $\qquad$ 1.5 0.5

To compute a square root or other basic math function, you have to load the math module of python. There are two ways to proceed. If you use import math, then you have to precede your function with math. as in math.sin(math.pi/2.0). The practice of using from math import * (which attempts to import everything from the particular module) is not encouraged and even disallowed in some IDE (like Spyder), mainly due to the risk of conflicts. You should explicitly import a few objects only, for instance

from math import pi
math.sin(pi/3.0)

However, if you type

import math
x = sin(pi/3.0)
print(x)

your IDE may complain, but may still give you the right answer. It is safer to type

import math
x = math.sin(math.pi/3.0)
print(x)

If you want a description of all functions available in the math module, type help(), then at the help prompt, type math.

If you want a random number betwen 0 and 1, import the random module:

import random
x = random.random()
print (x)

For a random integer from 1 to 6 (6 included)

import random
x = random.randint(1, 6)
print (x)

Dataset: Lists

Data sets can be regrouped in lists. Lists can be built with different types of objects. They are very useful for iterations over the objects of a list.

my_list = [1, 13, 'plot']
print (my_list)
print(my_list[0],my_list[2])
print(type(my_list))
print(type(my_list[2]))

Many operations are possible with lists. For instance, it is possible to modify a list by assigning new values:

my_list = [11, 25, 33, 76, 88]
my_list[1] = 12
print(my_list)
my_list.append(101) # this appends a new value at the end of the list
print(my_list)
my_list.insert(2,6) # this inserts a new element at index 2
print(my_list)
del my_list[1] # this deletes element of index 1
print(my_list)
x = my_list.pop(4) # delete element of index 4 and pass it to variable x
print(my_list,x)

You can obtain the length of a list (the number of objects) with the function len(). It is also possible to concatenate lists with the + operator:

list1 = ['a','Go',13,21]
list2 = [0,'ld',1]
list3 = list1 + list2;
print (list3)

To create ordered list of integers, use range(m,n) for a list from n (included) to m (excluded). Use range(n) for a list from 0 to n-1.

If you want a complete description of operations on lists, use help(list).


[Next Tutorial]