Python introduction¶

Great dates¶

  • 1989 : Guido van Rossum (Netherlands) design a script language inspired by ABC, Modula-3, C, and Unix.
  • 1991 : Python 0.9.0 is published on the forum forum alt.sources.
  • 2001 : Python 2.1, first release under the governance of Python Software Foundation.
  • 2008 : Python 3.0, major release non backward-compatible...

Built-in types¶

Numbers¶

  • Integers : 42, of type int.
  • Reals : 3.1415, 9e15, of type float.
  • Booleans : True, False, of type bool.
In [1]:
print(7**77)
print(2/3)
print(2//3)
print(2%3)
print(2./3.)
print(2.//3.)
118181386580595879976868414312001964434038548836769923458287039207
0.6666666666666666
0
2
0.6666666666666666
0.0

Collections¶

  • Character strings : 'spam', "guido's", """multi-lines string""", of type str.
  • Tuples : (1, 'spam', 4, 'U' ).
  • Lists : [1, [2, 'three'], 4], of type list.
  • Dictionaries : {'a': 'val', 3: 'x', 'key': 124}, of type dict.

Specials¶

  • Nothing : None, of type NoneType.

Variables¶

Assignment with =¶

In [2]:
a = 10
b, c = 3.14, "hello"
b, c = c, b # swap values
print(a,c)
print(b)
10 3.14
hello

Comparison with ==¶

In [3]:
a, b, c = 10, 3.14, "hello"
print(a==10)
print(3.14==b)
print(c==c)
print(a=="10")
True
True
True
False

Variables are "pointers"¶

In [4]:
list1 = [1, 2, 3]
list2 = list1 # both point to the same collection
list2[1] = 20
print(list1)
print(list2)
[1, 20, 3]
[1, 20, 3]
In [5]:
list2 = [100, 200, 300] # list2 points to a new collection
print(list1)
print(list2)
[1, 20, 3]
[100, 200, 300]

Code layout¶

one instruction per line, comments starts with #.¶

In [6]:
# assign values to a, b, c
a, b, c = 2, 6, 2
print(a,b,c)
2 6 2

Blocks demarcated by indentation (4 spaces)¶

In [7]:
# nested tests
if a > 1:
    print("a>1")
    if b > 5 and c == 2:
        print("b>5 and c==2")
a>1
b>5 and c==2

Compound statements¶

If¶

In [9]:
a, b = 1, 2
if a > b:
  print('a>b')
elif a == b:
  print('a==b')
else:
  print('a<b')
a<b

While¶

In [10]:
a, max = 1, 5
while a < max:
    print(a)
    a += 1
1
2
3
4

For¶

In [11]:
for elem in [ 'a', 'b', 'c']:
    print(elem)
a
b
c
In [12]:
for elem in range(4):
    print(elem)
0
1
2
3
In [13]:
for elem in range(4):
    if elem == 2:
        continue
    print(elem)
0
1
3
In [14]:
for elem in range(6):
    if elem == 2:
        break
    print(elem)
0
1

Functions¶

Definition¶

In [15]:
def divs(x,y):
  """Try / and //."""
  res1 = x/y
  res2 = x//y
  return res1, res2

print(divs(2.,3.))
print(divs(2,3))
(0.6666666666666666, 0.0)
(0.6666666666666666, 0)

Docstring¶

In [16]:
help(divs)
Help on function divs in module __main__:

divs(x, y)
    Try / and //.

A function is an first-class object¶

In [17]:
print(divs)
<function divs at 0x7fb24e5780e0>
In [18]:
myprint = print
myprint("Hello world !")
Hello world !

Writing and reading text files¶

Format a value into a string¶

In [19]:
key, value = "length", 10
fmt = "{}: {}"
text = fmt.format(key,value)
print(text)
length: 10

Writing in a text file¶

In [20]:
with open("dummy.txt",'w') as file:
    file.write("{} {}\n".format(1,2))
    file.write("{}\n".format(3))

Reading from a text file¶

In [21]:
with open("dummy.txt",'r') as file:
    for line in file:
        line = line.rstrip('\n')
        print(line)
1 2
3

Standard library modules¶

In [22]:
import random
rand_number = random.randint(1, 100)
print(rand_number)
19

Newbies pitfalls¶

  • Do not forget : at the end of if/while/for conditions.
  • Highest level instructions starts on column 1 !
  • Do not use tabulations, because something that looks "visually aligned" may not be considered so by the interpreter, if there is a mix of spaces and tabulations.

External recommended ressources¶

Tutorials¶

  • Software Carpentry
  • Hitchiker's Guide
  • Cours Python (in french)
  • Developpez (in french)

Official¶

  • Documentation
  • Python Software Fundation

Tools¶

  • Online Web Editor
  • PyCharm Editor
  • Anaconda Distribution

Various¶

  • Cheatsheet

Later Python related presentations¶

  • Variables & Types
  • Code-Layout & Control-Flow
  • Input-Output
  • Functions
  • Scripts/Modules/Packages
  • Errors
  • Documentation
  • Tests
  • Numpy
  • Classes