|
1 Hello friends and welcome to the tutorial on "Writing Python scripts" |
|
2 |
|
3 {{{ Show the slide containing title }}} |
|
4 |
|
5 {{{ Show the slide containing the outline slide }}} |
|
6 |
|
7 In this tutorial, we shall learn |
|
8 |
|
9 * How write Python scripts |
|
10 |
|
11 Often we will have to reuse the code that we haave written. We do that by |
|
12 writing functions. Functions are bundled into packages and are imported as and |
|
13 required in the script. |
|
14 |
|
15 Let us first write a function that computes the gcd of two numbers and save it |
|
16 in a script. |
|
17 |
|
18 {{{ Open an editor and start typing out the following code }}} |
|
19 :: |
|
20 |
|
21 def gcd(a, b): |
|
22 |
|
23 while b: |
|
24 a, b = b, a%b |
|
25 |
|
26 return a |
|
27 |
|
28 We shall write an test function in the script that tests the gcd function every |
|
29 time the script is run. |
|
30 |
|
31 {{{ Add to the script }}} |
|
32 |
|
33 :: |
|
34 |
|
35 if gcd(40, 12) == 4: |
|
36 print "Everything OK" |
|
37 else: |
|
38 print "The GCD function is wrong" |
|
39 |
|
40 Let us save the file as script.py in /home/fossee |
|
41 |
|
42 We shall run the script by doing |
|
43 :: |
|
44 |
|
45 $ python /home/fossee/script.py |
|
46 |
|
47 We can see that the script is executed and everything is fine. |
|
48 |
|
49 What if we want to use the gcd function in some of our later scripts. This |
|
50 is also possible since every python file can be used as a module. |
|
51 |
|
52 Let us understand what happens when you import a module. |
|
53 |
|
54 Open IPython and type |
|
55 :: |
|
56 |
|
57 import sys |
|
58 |
|
59 {{{ Show summary slide }}} |
|
60 |
|
61 This brings us to the end of the tutorial. |
|
62 we have learnt |
|
63 |
|
64 * how to use loadtxt to read files |
|
65 * how to generate a least square fit |
|
66 |
|
67 {{{ Show the "sponsored by FOSSEE" slide }}} |
|
68 |
|
69 #[Nishanth]: Will add this line after all of us fix on one. |
|
70 This tutorial was created as a part of FOSSEE project, NME ICT, MHRD India |
|
71 |
|
72 Hope you have enjoyed and found it useful. |
|
73 Thankyou |
|
74 |
|
75 .. Author : Nishanth |
|
76 Internal Reviewer 1 : |
|
77 Internal Reviewer 2 : |
|
78 External Reviewer : |