We introduce here the Python language. Only the bare minimum necessary for getting started with Numpy and Scipy is addressed here. To learn more about the language, consider going through the excellent tutorial http://www.scipy-lectures.org/intro/index.html. Dedicated books are also available, such as http://www.diveintopython.net/.
Python is a programming language, as are C, Fortran, BASIC, PHP, etc. Some specific features of Python are as follows:
C or Fortran, one does not compile Python code before executing it. In addition, Python can be used interactively: many Python interpreters are available, from which commands and scripts can be executed.
be used and distributed free of charge, even for building commercial software.
systems, Windows, Linux/Unix, MacOS X, most likely your mobile phone OS, etc.
a very readable language with clear non-verbose syntax
a language for which a large variety of high-quality packages are
available for various applications, from web frameworks to scientific computing.
and C++.
example, Python is an object-oriented language, with dynamic typing (the same variable can contain objects of different types during the course of a program).
See https://www.python.org/about/ for more information about distinguishing features of Python.
print("Hello world")
1+1
We can assign values to variables with =
a = 4
type(a)
a = 4
type(a)
Note that one does not declare the type of a variable before assigning its value. In C, conversely, one should write:
int a = 4;
There exists a floating point type that is created when the variable has decimal values:
c = 2.1
type(c)
c = 2.1
type(c)
Similarly, boolean types are created from a comparison:
3 > 4
test = (3 > 4)
type(test)
test = (3 > 4)
type(test)
Tip:A Python shell can therefore replace your pocket calculator, with the basic arithmetic operations +
, -
, *
, /
, %
(modulo) natively implemented
a = 1
type(a)
b = float(a)
type(b)
colors = ['red', 'blue', 'green', 'black', 'white']
type(colors)
colors = ['red', 'blue', 'green', 'black', 'white']
type(colors)
Indexing: accessing individual objects contained in the list::
colors[2]
Counting from the end with negative indices:
colors[-2]
colors
colors[1:5:2]
Slicing syntax: colors[start:stop:stride]
Tip: All slicing parameters are optional::
colors
colors[3:]
colors[:3]
colors[::2]
. Why?¶colors[::2]
colors[::-1]
Different string syntaxes (simple, double or triple quotes)::
s = 'Hello, how are you?'
s = "Hi, what's up"
s = '''Hello, # tripling the quotes allows the
how are you''' # the string to span more than one line
s = """Hi,
what's up?"""
s = 'asdfdfdf'
type(s)
s = "asdfdfd"
s = """asdfadsf
asdfdf
asdfdf
"""
A dictionary is basically an efficient table that maps keys to values. It is an unordered container
tel = {'emmanuelle': 5752, 'sebastian': 5578}
tel
{'emanuelle': 5752, 'sebastian': 5578}
tel['francis']
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-3-7b0ad96275f8> in <module>() ----> 1 tel['francis'] KeyError: 'francis'
tel['francis'] = 5919
tel
{'emanuelle': 5752, 'francis': 5919, 'sebastian': 5578}
tel['sebastian']
5578
tel.keys()
dict_keys(['sebastian', 'emanuelle', 'francis'])
tel.values()
dict_values([5578, 5752, 5919])
'francis' in tel
True
It can be used to conveniently store and retrieve values associated with a name (a string for a date, a name, etc.). See https://docs.python.org/tutorial/datastructures.html#dictionaries for more information.
Tip: A dictionary can have keys (resp. values) with different types:
d = {'a':1, 'b':2, 3: 'asdf'}
d
{'a': 1, 3: 'asdf', 'b': 2}
del d['a']
d
{3: 'asdf', 'b': 2}
tel = {'emanuelle': 5752, 'sebastian' : 5578, 'francis' : 1234}
tmp = tel['francis']
tel['francis'] = tel['sebastian']
tel['sebastian'] = tmp
tel
{'emanuelle': 5752, 'francis': 5578, 'sebastian': 1234}
if 2 ** 2 == 5:
print('Obvious')
print('YES')
YES
Tip: Type the following lines in your Python interpreter, and be careful
to respect the indentation depth. The Ipython shell automatically
increases the indentation depth after a colon :
sign; to
decrease the indentation depth, go four spaces to the left with the
Backspace key. Press the Enter key twice to leave the logical block.
>>> a = 10
>>> if a == 1:
... print(1)
... elif a == 2:
... print(2)
... else:
... print('A lot')
A lot
a = 10
if a == 1:
print(1)
elif a == 2:
print(2)
for i in range(4):
print(i + 1)
1 2 3 4
a = []
for i in range(0, 101, 2):
print(i)
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100
But most often, it is more readable to iterate over values::
>>> for word in ('cool', 'powerful', 'readable'):
... print('Python is %s' % word)
Python is cool
Python is powerful
Python is readable
for word in ['green', 'blue', 'yellow']:
print(word)
green blue yellow
>>> [i**2 for i in range(4)]
[0, 1, 4, 9]
[2 * i for i in range(51)]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
a = 10
b = 1
while b < a:
b = b + 1
print(b)
2 3 4 5 6 7 8 9 10
Compute the decimals of Pi using the Wallis formula:
$$ \pi = 2 \prod_{i=1}^{100} \frac{4i^2}{4i^2 - 1} $$pi = 2
eps = 1e-6
dif = 2 * eps
i = 1
while(dif > eps):
old_pi = pi
pi *= 4 * i ** 2 / (4 * i ** 2 - 1)
dif = pi - old_pi
i += 1
pi
3.140707822589477
Typical C-style while loop (Mandelbrot problem)::
>>> z = 1 + 1j
>>> while abs(z) < 100:
... z = z**2 + 1
>>> z
(-134+352j)
[i while i < 10; i += 1]
File "<ipython-input-43-d058ae05126b>", line 1 [i while i < 10; i += 1] ^ SyntaxError: invalid syntax
def test():
print('in test function')
test()
in test function
Functions can optionally return values.
>>> def disk_area(radius):
...: return 3.14 * radius * radius
...:
>>> disk_area(1.5)
>>> 7.0649999999999995
Note: By default, functions return None
.
The syntax to define a function:
* the ``def`` keyword;
* is followed by the function's **name**, then
* the arguments of the function are given between parentheses followed
by a colon.
* the function body;
* and ``return object`` for optionally returning values.
Mandatory parameters (positional arguments)
>>> def double_it(x):
....: return x * 2
....:
>>> double_it(3)
>>> 6
>>> double_it()
---------------------------------------------------------------------------
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: double_it() takes exactly 1 argument (0 given)
Optional parameters (keyword or named arguments)
>>> def double_it(x=2):
....: return x * 2
....:
>>> double_it()
>>> 4
>>> double_it(3)
>>> 6
Keyword arguments allow you to specify default values.
def square(x):
return x ** 2
square(4)
16
Python supports object-oriented programming (OOP). The goals of OOP are:
* to organize the code, and
* to re-use code in similar contexts.
Here is a small example: we create a Student class, which is an object gathering several custom functions (methods) and variables (attributes), we will be able to use::
>>> class Student(object):
... def __init__(self, name):
... self.name = name
... def set_age(self, age):
... self.age = age
... def set_major(self, major):
... self.major = major
...
>>> anna = Student('anna')
>>> anna.set_age(21)
>>> anna.set_major('physics')
In the previous example, the Student class has __init__
, set_age
and
set_major
methods. Its attributes are name
, age
and major
. We
can call these methods and attributes with the following notation:
classinstance.method
or classinstance.attribute
. The __init__
constructor is a special method we call with: MyClass(init parameters if any)
.
Now, suppose we want to create a new class MasterStudent with the same
methods and attributes as the previous one, but with an additional
internship
attribute. We won't copy the previous class, but
inherit from it::
>>> class MasterStudent(Student):
... internship = 'mandatory, from March to June'
...
>>> james = MasterStudent('james')
>>> james.internship
'mandatory, from March to June'
>>> james.set_age(23)
>>> james.age
23
class Numbers:
def add(self, x, y):
return x + y
def substract(self, x, y):
return x - y
a = Numbers()
a.add(2, 3)
5
add
and substract
¶