Skip to content

Samples of python scripts seen during the course

Sample 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python3


def f(x,y=1):
  "this is a sample function"
  if y == 1:
    fx = 3*x*x+2*x-5
  else:
     fx = 3*x*x+2*x+5
  return fx

#print(f(3,-1))
#print(f(3,1))
#print(f(3))
#print(f(x=3,y=1))
#print(f(y=1,x=3))
#print(f(1,3))
print(f.__doc__)

Sample 2

sample2.py:

1
2
3
4
5
6
#!/usr/bin/env python3

import sample2_module
import random
print(sample2_module.randrange(10))
print(sample2_module.isPerfect(6))

sample2_module.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python3


def f(x):
  fx = 3*x*x+2*x-5
  return fx

#print(f(2))
#print(f(5))
#print(f(-3))

#a = [ 3,2,57,8]

def somme(anyList):
    mysum = 0
    for i in anyList:
      mysum = mysum + i
    return mysum
#print(somme(a))

def divisors(n):
  aList = []
  for i in range(1,n):
    if n%i == 0: 
      aList = aList + [i]
  return aList

#print(divisors(10))

def isPerfect(n):
   return somme(divisors(n)) == n

#print(isPerfect(5))
#print(isPerfect(6))

#for i in range(1,10000):
#  if isPerfect(i):
#    print(i, ' is a perfect number')
#

def randrange(n):
  print("randrange from sample2_module")
  return 0

Sample 3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/usr/bin/env python3

# recherche de l'énergie finale dans un fichier Gaussian
energies = []
f = open('h2o.log', 'r')
for line in f:
  if 'SCF Done' in line:
    energies = energies + [ line[24:40] ]

print(energies[-1])

Sample 4

sample4.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env python3

class MyClass(object):
  pass

mouse = MyClass()
mouse.button1 = 0
mouse.button2 = 1
mouse.middle = 'Middle button'
#print(mouse)
#print(mouse.button1)
#print(mouse.button2)
#print(mouse.middle)
mouse2 = MyClass()
#print(mouse2)
#print(mouse2.button1)

class Complex(object):

  def __init__(self, x=0, y=0):
#   print("this is __init__")
    self.real = x
    self.imag = y

  def conjugate(self):
    return Complex(self.real, -self.imag)

  def __repr__(self):
    if self.imag < 0:
      return "%f - %f i" % (self.real, -self.imag)
    else:
      return "%f + %f i" % (self.real,  self.imag)


print("call Complex")
#c1 = Complex()
c1 = Complex(5.0, 3.0)
#c1.real = 5.0
#c1.imag = 3.0
print(c1)
#print(c1.real)
#print(c1.imag)
print("call Complex2")
c2 = Complex()
print(c2)
#print(c2.real)
print("call Conjugate")
cz = c1.conjugate()
print(cz)
#print(cz.real)
#print(cz.imag)