Basic training

operators and comparisons, None, True, False

> , < , == , !=, not, is
In [1]:
a = None
b = None
a is b
Out[1]:
True
In [26]:
a == b
Out[26]:
True
In [5]:
a != b
Out[5]:
False
In [11]:
a = 'hello world!'
b = 'hello world!'

print 'a is b :', a is b,', a is not b :',a is not b
print 'a == b :', a == b
a is b : False , a is not b : True
a == b : True

We can write also : "not (logical expression)" :

In [13]:
print not a is b , not a == b
True False

logical operators

In []:
or and not
In [3]:
True or False
Out[3]:
True
In [4]:
True and False
Out[4]:
False
In [5]:
not True
Out[5]:
False

operator in

In [3]:
'a' in ['a','b','c','d']
Out[3]:
True
In [2]:
'x' in 'ooooooooxooooooo'
Out[2]:
True
In [3]:
'y' in 'ooooooooxooooooo'
Out[3]:
False

'not' can be inserted before 'in' operator, like in natural language :

In [2]:
'x' not in 'ooooooooxooooooo'
Out[2]:
False

Looping and flow control:

In the described expressions, the different zones are differentiated by the indentation.

Logical expression is delimited by ':'

Back to the previous indentation tells the end of the zone.

if

In [14]:
if 1 in [1,2,3]:
  print "OK"  
OK

else

In [3]:
a = 10
if a < 100:
  print "a is lower than 100"
else:
  print "a is upper 100"
a is lower than 100

In [4]:
    
if a == 10:
  print "a is 10"  
else:
  print "a is not 10" 
    
a is 10

elif

In [5]:
if a == 1:
  print "one"
elif a == 2:
  print "two"
elif a == 3:
  print "three"
else:
  print "a out of domain"  
    
    
a out of domain

for loops :

In [2]:
names = ['Fabio', 'Karl', 'Marc', 'Olivier', 'Alan', 'Jean-Marc','Damien','David']

for name in names:
  print name  
Fabio
Karl
Marc
Olivier
Alan
Jean-Marc
Damien
David

In [1]:
 for i in [1,2,3]:
   print 'i:',i
i: 1
i: 2
i: 3

Use of range function :

In [3]:
range(1,10,1)
Out[3]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
previous loop:
In [5]:
for i in range(1,4):
  print 'i:',i  
i: 1
i: 2
i: 3

Use of xrange : xrange is a generator, doing the same as range : to be used in a loop only

In [13]:
for i in xrange(1,4):
  print 'i:',i
    
print 'range(1,4):',range(1,4)

print

print 'xrange(1,4):',xrange(1,4)
i: 1
i: 2
i: 3
range(1,4): [1, 2, 3]

xrange(1,4): xrange(1, 4)

while loops :

In [2]:
i = 0
while i < 10:
  i += 1
  print 'i:',i  
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
i: 10

using else with for and while :

In [18]:
i = 6
while i > 0:
  i -= 1
  print " ***",str(i).center(8),"***"
else:
  print " *** Ignition ***"  
 ***    5     ***
 ***    4     ***
 ***    3     ***
 ***    2     ***
 ***    1     ***
 ***    0     ***
 *** Ignition ***

In [10]:
for i in range(5,0,-1):
  print ">>",i  
else:
  print ">> Go !!"  
>> 5
>> 4
>> 3
>> 2
>> 1
>> Go !!

Use of break :

Stops the loop

In [5]:
for i in [1,2,3,4,5]:
  if i >= 4:
    print "Found breaking point : exiting"    
    break
  print "i :",i  
i : 1
i : 2
i : 3
Found breaking point : exiting

Use of continue :

Go to next item

In [7]:
for i in range(1,100):
  if i%10 != 0:
    continue
  print "i:",i  
i: 10
i: 20
i: 30
i: 40
i: 50
i: 60
i: 70
i: 80
i: 90

Use of pass :

In []:
Does nothing in test but process the following commands
In [7]:
for i in range(1,10):  
  if i%3 == 0:
    pass
  else:
    print 'i : ',i
  print '***',i  
i :  1
*** 1
i :  2
*** 2
*** 3
i :  4
*** 4
i :  5
*** 5
*** 6
i :  7
*** 7
i :  8
*** 8
*** 9

enumerate

In [2]:
for i,num in enumerate(['zéro','un','deux','trois','quatre','cinq']):
  print num,':',i
    
zéro : 0
un : 1
deux : 2
trois : 3
quatre : 4
cinq : 5

Comprehensive lists

for is also used in a way to generate a list :
In [1]:
squares = [x**2 for x in range(10)]

print squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Equivalent for ternary operator

In [15]:
a = 15
x =  1 if a > 10 else 0
print 'x:',x
x: 1

string slicing/indexing (non-numpy)

In [11]:
print 'introduction'[:5]
intro

In [10]:
print 'intersection'[5:]
section

Printing and formatting, raw input

In [4]:
print "Hello"
Hello

In [2]:
print " %d is %s" % (42,'the answer')
x=42
print " {} is {}".format(x,'the answer')
 42 is the answer
 42 is the answer

In [35]:
nw = raw_input("Enter the right number: ")

if int(nw) != 5:
  print "*** You did not find the right number. Try again ***"
else:
  print "*** Congratulations, the right number is indeed",nw,"***"
  
Enter the right number: 3
*** You did not find the right number. Try again ***

basic reading and writing

In [14]:
f = open("toto","w")
for i,num in enumerate(['zéro','un','deux','trois','quatre','cinq']):
  print >>f, num,':',i
f.close()

f = open("toto","r")
lines = f.readlines()
f.close()

for line in lines:
  print line  
zéro : 0

un : 1

deux : 2

trois : 3

quatre : 4

cinq : 5


In [12]:
f = open("toto","a")
for i,num in enumerate(['six','sept','huit']):
   print >>f,num,':',i+6
f.close()

f = open("toto","r")
lines = f.readlines()
f.close()

for line in lines:
  print line  
zéro : 0

un : 1

deux : 2

trois : 3

quatre : 4

cinq : 5

six : 6

sept : 7

huit : 8


Accessing remote files

In [3]:
import urllib2
response = urllib2.urlopen('http://physics.nist.gov/cuu/Constants/Table/allascii.txt')

for line in response:
  if 'constant' in line :
    print line 
  From:  http://physics.nist.gov/constants

atomic mass constant                                        1.660 538 921 e-27       0.000 000 073 e-27       kg

atomic mass constant energy equivalent                      1.492 417 954 e-10       0.000 000 066 e-10       J

atomic mass constant energy equivalent in MeV               931.494 061              0.000 021                MeV

Avogadro constant                                           6.022 141 29 e23         0.000 000 27 e23         mol^-1

Boltzmann constant                                          1.380 6488 e-23          0.000 0013 e-23          J K^-1

Boltzmann constant in eV/K                                  8.617 3324 e-5           0.000 0078 e-5           eV K^-1

Boltzmann constant in Hz/K                                  2.083 6618 e10           0.000 0019 e10           Hz K^-1

Boltzmann constant in inverse meters per kelvin             69.503 476               0.000 063                m^-1 K^-1

conventional value of Josephson constant                    483 597.9 e9             (exact)                  Hz V^-1

conventional value of von Klitzing constant                 25 812.807               (exact)                  ohm

electric constant                                           8.854 187 817... e-12    (exact)                  F m^-1

Faraday constant                                            96 485.3365              0.0021                   C mol^-1

Faraday constant for conventional electric current          96 485.3321              0.0043                   C_90 mol^-1

Fermi coupling constant                                     1.166 364 e-5            0.000 005 e-5            GeV^-2

fine-structure constant                                     7.297 352 5698 e-3       0.000 000 0024 e-3       

first radiation constant                                    3.741 771 53 e-16        0.000 000 17 e-16        W m^2

first radiation constant for spectral radiance              1.191 042 869 e-16       0.000 000 053 e-16       W m^2 sr^-1

inverse fine-structure constant                             137.035 999 074          0.000 000 044            

Josephson constant                                          483 597.870 e9           0.011 e9                 Hz V^-1

Loschmidt constant (273.15 K, 100 kPa)                      2.651 6462 e25           0.000 0024 e25           m^-3

Loschmidt constant (273.15 K, 101.325 kPa)                  2.686 7805 e25           0.000 0024 e25           m^-3

mag. constant                                               12.566 370 614... e-7    (exact)                  N A^-2

molar gas constant                                          8.314 4621               0.000 0075               J mol^-1 K^-1

molar mass constant                                         1 e-3                    (exact)                  kg mol^-1

molar Planck constant                                       3.990 312 7176 e-10      0.000 000 0028 e-10      J s mol^-1

molar Planck constant times c                               0.119 626 565 779        0.000 000 000 084        J m mol^-1

Newtonian constant of gravitation                           6.673 84 e-11            0.000 80 e-11            m^3 kg^-1 s^-2

Newtonian constant of gravitation over h-bar c              6.708 37 e-39            0.000 80 e-39            (GeV/c^2)^-2

Planck constant                                             6.626 069 57 e-34        0.000 000 29 e-34        J s

Planck constant in eV s                                     4.135 667 516 e-15       0.000 000 091 e-15       eV s

Planck constant over 2 pi                                   1.054 571 726 e-34       0.000 000 047 e-34       J s

Planck constant over 2 pi in eV s                           6.582 119 28 e-16        0.000 000 15 e-16        eV s

Planck constant over 2 pi times c in MeV fm                 197.326 9718             0.000 0044               MeV fm

Rydberg constant                                            10 973 731.568 539       0.000 055                m^-1

Rydberg constant times c in Hz                              3.289 841 960 364 e15    0.000 000 000 017 e15    Hz

Rydberg constant times hc in eV                             13.605 692 53            0.000 000 30             eV

Rydberg constant times hc in J                              2.179 872 171 e-18       0.000 000 096 e-18       J

Sackur-Tetrode constant (1 K, 100 kPa)                      -1.151 7078              0.000 0023               

Sackur-Tetrode constant (1 K, 101.325 kPa)                  -1.164 8708              0.000 0023               

second radiation constant                                   1.438 7770 e-2           0.000 0013 e-2           m K

Stefan-Boltzmann constant                                   5.670 373 e-8            0.000 021 e-8            W m^-2 K^-4

von Klitzing constant                                       25 812.807 4434          0.000 0084               ohm

Wien frequency displacement law constant                    5.878 9254 e10           0.000 0053 e10           Hz K^-1

Wien wavelength displacement law constant                   2.897 7721 e-3           0.000 0026 e-3           m K


python error output (what does it mean)

ipython gives position of failure among many code lines:
In [3]:
for i in range(1,6):
  print '1/i-3:',1/(i-3)  
  print 'i*i:',i*i,'\n'  
1/i-3: -1
i*i: 1 

1/i-3: -1
i*i: 4 

1/i-3:
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-3-db6cc97e491c> in <module>()
      1 for i in range(1,6):
----> 2   print '1/i-3:',1/(i-3)
      3   print 'i*i:',i*i,'\n'

ZeroDivisionError: integer division or modulo by zero
Many error codes can be displayed according to the type of error detected.
In [1]:
print A/0
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-dd6555757187> in <module>()
----> 1 print A/0

NameError: name 'A' is not defined
In [2]:
A=1
print A/0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-2-7e53f7623446> in <module>()
      1 A=1
----> 2 print A/0

ZeroDivisionError: integer division or modulo by zero
In [11]:
'2' + 3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-b2d67de0be7e> in <module>()
----> 1 '2' + 3

TypeError: cannot concatenate 'str' and 'int' objects
In [13]:
f = open("notexistingFile","r")
for line in f:
  print f
f.close()    
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-13-a23beea261e4> in <module>()
----> 1 f = open("notexistingFile","r")
      2 for line in f:
      3   print f
      4 f.close()

IOError: [Errno 2] No such file or directory: 'notexistingFile'
An example showing that you cannot assign something to None :
In [17]:
None = 1
  File "<ipython-input-17-48142bc569f9>", line 1
    None = 1
SyntaxError: cannot assign to None
But this is not true for True and False : although it is not recomended, some variables can be used having these names
In [24]:
True = 2
False = 1

print False

print 3==4

print False
1
False
1

You can find a list of python exceptions at the following place : https://docs.python.org/3/library/exceptions.html

Using exceptions:

In [13]:
A=1
try:
  print A/0    
except  ZeroDivisionError:
  print "*** Error dividing by 0 ***"

print 

try:
  print A/0    
except  ZeroDivisionError,e:
  print "*** ZeroDivisionError:",e  
    
print    
*** Error dividing by 0 ***

*** ZeroDivisionError: integer division or modulo by zero


raise an exception :

In [19]:
A = int(raw_input('Enter integer:'))
try:
  print A/0
except  ZeroDivisionError,e:
  if A==1:
    print "*** Error dividing by 0 ***"
  else:
    raise e    
Enter integer:8

---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-19-32f572e0a89d> in <module>()
      6     print "*** Error dividing by 0 ***"
      7   else:
----> 8     raise e

ZeroDivisionError: integer division or modulo by zero

try, finally :

In [16]:
 try:
   x = int(raw_input('Please enter a number: '))
 finally:
   print('Thank you for your input')
Please enter a number: e
Thank you for your input

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-16-aeed082c34ae> in <module>()
      1 try:
----> 2   x = int(raw_input('Please enter a number: '))
      3 finally:
      4   print('Thank you for your input')

ValueError: invalid literal for int() with base 10: 'e'

Use of assert :

In [27]:
def square(x):
  return x*x

assert square(2)==4,"Assertion 1 : not verified"
print ".."
assert square(2)==-1,"Assertion 2 : Wrong output for square function !!"
print ".."
..

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-27-9d0435e83bc4> in <module>()
      4 assert square(2)==4,"Assertion 1 : not verified"
      5 print ".."
----> 6 assert square(2)==-1,"Assertion 2 : Wrong output for square function !!"
      7 print ".."

AssertionError: Assertion 2 : Wrong output for square function !!

Breakout : Getting your code on :

Create a program (a .py file) which repeatedly asks the user for a word. The program should append all the words together. When the user types a "!", "?", or a ".", the program should print the resulting sentence and exit. For example, a session might look like this: [~]$ python breakout01.py\n Enter a word (. ! or ? to end): My\n Enter a word (. ! or ? to end): name Enter a word (. ! or ? to end): is Enter a word (. ! or ? to end): Walter Enter a word (. ! or ? to end): White Enter a word (. ! or ? to end): ! My name is Walter White!
In [4]: