Download A Short Introduction to Python

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
A Short Introduction to Python
Tuomas Puoliväli
[email protected]
26th of February 2013
Starting the Python Interpreter
Start the interactive Python interpreter by typing
$ ipython
to the terminal window. You should see something like
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
Type "copyright", "credits" or "license" for more information.
IPython 0.13.1.rc2 -- An enhanced Interactive Python.
?
-> Introduction and overview of IPython’s features.
%quickref -> Quick reference.
help
-> Python’s own help system.
object?
-> Details about ’object’, use ’object??’ for extra details.
In [1]:
if everything works correctly. Type
In [1]: print "Hello World!"
to the interpreter to execute your first command. The interpreter can be
closed by using the command
In [2]: exit
Running Scripts
Open up your favourite text editor, and type in the following:
print "This is my first Python script file"
Save the file as “script.py”. Now, type
$ ipython script.py
to the terminal window to run your script. Alternatively, you could run the
script from the Python interpreter using command
In [1]: %run script.py
Numbers
The Python interpreter acts as a calculator if you type in mathematical
expressions. The syntax is the same as in other programming languages:
In [1]: 1+1 # by the way, this is how to add comments
Out[1]: 2
In [3]: (10-2)/8
Out[3]: 1
Notice that integer division returns the floor:
In [4]: 7/3 # 7 % 3 would give the remainder
Out[4]: 2
Of course, floating point numbers are supported too:
In [5]: 7/3. # writing the decimal mark is enough to imply the use of floats
Out[5]: 2.3333333333333335
There is a native type for complex numbers:
In [6]: c = 2 + 3j
In [7]: c.real
Out[7]: 2.0
In [8]: c.imag
Out[8]: 3.0
Strings
Example 1)
In [1]: s = "Hello World!"
In [2]: s
Out[2]: ’Hello World!’
Example 2)
In [3]: "Hello %s" % "World" # compare to print f in C
Out[3]: ’Hello World’
Listing and Removing Variables
Use command whos to list your variables:
In [1]: whos
Variable
Type
Data/Info
------------------------------c
complex
(2+3j)
s
str
Hello World!
A variable may be removed using the command del:
In [2]: del s
In [3]: whos
Variable
Type
Data/Info
------------------------------c
complex
(2+3j)
Control Flow: if/elif/else
A simple example:
In [1]: x = 3
In [2]: if x < 0:
...:
print
...: elif x ==
...:
print
...: else:
...:
print
x is greater than
"x is smaller than zero"
0:
"x is equal to zero"
"x is greater than zero"
zero
In general, the else part is optional, and there can be zero or more elif
(else if) parts. Notice that Python uses indentation for grouping
statements! What would be the output of the code below?
In [1]: x = 1
In [2]: if x == 2:
...:
print "foo" # is this printed?
...: print "bar" # how about this?
How about for this?
In [1]: x = 1
In [2]: if x == 2:
...:
print "foo" # is this printed?
...:
print "bar" # how about this?
Control Flow: for
A simple example of using a for loop to iterate over a list:
In [1]: ch_names = ["MEG 2442", "MEG 2443", "MEG 2444"]
In [2]: for ch_name in ch_names
...:
print ch_name, # a trailing colon omits \n after each print command
MEG 2442 MEG 2443 MEG 2444
The function range is useful for iterating over sequences of numbers:
In [2]: for i in range(10): # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
...:
for j in range(2, i):
...:
if (i % j == 0):
...:
print "%d is a composite number" % i
...:
break
See also functions enumerate, reversed, sorted, and zip which can be
of great help for writing more complicated loops.
Defining Functions
Example 1)
In [1]: def sum(a, b):
...:
return a + b
...:
In [2]: sum(2, 2)
Out[2]: 4
Example 2)
In [1]: def sum_and_multiply(a, b):
...:
return (a+b, a*b)
...:
In [2]: result = sum_and_multiply(2, 3)
In [3]: type(result)
Out[3]: tuple
In [4]: sum, product = sum_and_multiply(2, 4)
In [5]: sum
Out[5]: 6
In [6]: product
Out[6]: 8
In [7]: type(sum), type(product)
Out[7]: (int, int)
Classes
Example:
In [1]: class Sovellusprojekti:
...:
"""Tietotekniikan laitoksen sovellusprojekti."""
...:
def __init__(self):
...:
self.nimi = "Tuntematon"
...:
def aloita(self, nimi):
...:
self.nimi = nimi
...:
print "Sovellusprojekti %s on alkanut!" % nimi
...:
def lopeta(self):
...:
print "Sovellusprojekti %s on paattynyt!" % self.nimi
...:
In [2]: s = Sovellusprojekti()
In [3]: s.nimi
Out[3]: ’Tuntematon’
In [4]: s.aloita(’Hoksotin’)
Sovellusprojekti Hoksotin on alkanut!
In [5]: s.lopeta()
Sovellusprojekti Hoksotin on paattynyt!
Unit testing
Test code:
import unittest
class EqualityTest(unittest.TestCase):
def test_equal(self):
self.assertEqual(4-2, 5-3)
if __name__ == "__main__":
unittest.main()
Running the test:
$ ipython equality_test.py
.
---------------------------------------------------------------------Ran 1 test in 0.000s
OK
There are a number of methods for doing the testing, e.g. assertEqual(a,
b), assertNotEqual(a, b), assertTrue(x), assertIn(a, b),
assertIsInstance(a, b), assertGreater(a, b),
assertRegexpMatches(s, re), ...
Numpy and Pylab
Plot a cosine wave:
In [1]: import numpy as np
In [2]: import pylab as pl
In [3]: t = np.linspace(0, 4*np.pi, 100)
In [4]: x = np.cos(t)
In [5]: pl.plot(t, x)
Out[5]: [<matplotlib.lines.Line2D at 0x4125fd0>]
In [6]: pl.show()
Help
Python documentation is available online at:
docs.python.org/2/index.html