Download Introduction to Python Day 10

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

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

Document related concepts
no text concepts found
Essentials for Scientific Computing:
Introduction to Python
Day 10
Ershaad Ahamed
May 2012
Python, unlike C and FORTRAN is not a compiled language. Python scripts
can be written and run in exactly the same way as bash shell scripts. Python
being an interpreted language, executes each line of code as it is encountered.
Python is a complete multi-purpose programming language. Its syntax is elegant
and easy to learn. One aspect that makes python very attractive is its large
collection of standard modules. Modules are the python equivalent of libraries.
By standard modules, we mean modules that are available in a standard python
installation. The python language itself has only basic functionality. The large
collection of modules make python useful for quickly writing scripts to perform
useful functions. Python is free software.
Getting Started
Python is present by default on most Linux installations. The quickest way
to start using python is to start the interactive python interpreter. In the interactive interpreter, you can type python statements and they are processed
immediately. The following examples will illustrate that. Starting the interpreter.
$ python
Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
The >>> prompt means the interpreter is ready to accept python language statements. Our first line of code
>>> print "Hello, World"
Hello, World
Notice how the interpreter executed and produced output immediately after
the python statement was entered. The line we just executed is the python
statement to print the string Hello, World. String literals are always enclosed
by single or double quotes. We can also print expressions which can look like.
>>> print 1 + 3
First, python evaluates the expression 1 + 3 which adds two integers and produces an integer result. The resulting integer is output by the print statement.
An operator can have different meanings depending on the data type it operates on, for example the + operator performs concatenation on strings, and the
* operator performs repetition.
>>> print "First string" + "Second one"
First stringSecond one
>>> print "word" * 4
Variables in python can be easily created by using the assignment operator
=. The right hand side of the assignment operator can also be expressions. Since
the print statement also accepts variables:
>>> mystring = "Hello, World"
>>> print mystring
Hello, World
>>> mystring = 25 * 2
>>> print mystring
In python the statement mystring = "Hello, World", creates a string Hello,
World and associates the name mystring to it. In the second statement, the
expression 25 * 2 is evaluated and the result is associated with the name
mystring. Notice that after the first assignment, mystring is associated with a
string, and after the second assignment, mystring is associated with an integer.
It is thus evident that python is a dynamic language and a variable is simply a
name associated with a value. Unline C and FORTRAN, the type of the value
that a variable is associated with need not be statically defined.
Python has built-in support for complex numbers.
>>> a = 3+4j
>>> b = 1.2+11j
>>> print a*b
>>> print a+b
>>> print a-b
>>> print a/b
>>> print a.real
>>> print a.imag
Basic Data Types
Besides the string, integer and floating point types, python supports some more
data structures are built-in types.
Lists are analogous to arrays in other languages. But, python lists are far more
flexible, they can hold any combination of data types within a list. A few
examples in the interactive interpreter.
>>> mylist = [’hello’, 12, 23.5]
>>> print mylist
[’hello’, 12, 23.5]
>>> print mylist[0]
>>> print mylist[1]
>>> print mylist[2]
>>> print mylist[0:2]
[’hello’, 12]
>>> mylist[2] = "New String"
>>> print mylist
[’hello’, 12, ’New String’]
>>> print len(mylist)
>>> numlist = [1.2, 3.5, 33, 65]
>>> print numlist * 2
[1.2, 3.5, 33, 65, 1.2, 3.5, 33, 65]
>>> print numlist + numlist
[1.2, 3.5, 33, 65, 1.2, 3.5, 33, 65]
Notice that list elements are indexed from zero. In the list above element 0 is a
string, element 1 is an integer and element 2 is a floating point number. in the
line print mylist[0:2] we use the list slice syntax, 0:2 means all elements
between element 0 and element 2. Notice that 0:2 returns a list of 2 elements
since element 2 is not included. To remember this imagine a C for loop that
looks like for(i = 0; i < 2; i++), in which i takes values 0 and 1 before the
loop ends. Assignment to list elements also works as expected. The built-in
len() function returns the number of elements in the list. List values can be
other lists also, which are called nested lists.
The bracket operator [] also works for strings
>>> mystring = "Hello, World"
>>> print mystring[0]
>>> print mystring[-1]
>>> print mystring[:7]
>>> print mystring[7:]
>>> mystring[2] = ’x’
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ’str’ object does not support item assignment
>>> print len(mystring)
Negative indexes count from the end of the list, -1 being the last element. In
the slice syntax, if no index is specified on the left of the colon it is implied to
be the lowest index (zero), and if no index is specified on the right of the colon,
it implies the higest index (length of the list - 1). Consequently a colon alone
implies all elements. The last statement fails because strings, unlike lists are
immutable, that is they cannot be modified once they are created.
Tuples are a sequence type just like Lists and strings. Tuples are created by
separating values with commas and enclosing them in parentheses. A trailing
comma is necessary when creating a tuple of one element so that python does
not interpret it as an expression.
>>> mytuple = (1, 4.5, "World")
>>> print mytuple
(1, 4.5, ’World’)
>>> print mytuple[2]
>>> mytuple[1] = 23
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ’tuple’ object does not support item assignment
>>> not_a_tuple = (24)
>>> print not_a_tuple
>>> a_tuple = (24,)
>>> print a_tuple
As is evident from above, tuples are an immutable type.
Sets are a sequence type that is unordered and does not have duplicates. Sets
are mutable and elements can be added to an existing set. But if a set already
has an identical element, a duplicate is not added. Sets are created by passing
a sequence type to the set() built-in function.
>>> mylist = [1, 3, 4, 1, ’wordA’, ’wordB’, ’wordA’]
>>> mytuple = (’wordC’, 4.5, 77, (1,2), 12, (1,2))
>>> mystring = "queue"
>>> print mylist
[1, 3, 4, 1, ’wordA’, ’wordB’, ’wordA’]
>>> print mytuple
(’wordC’, 4.5, 77, (1, 2), 12, (1, 2))
>>> print mystring
>>> myset = set(mylist)
>>> print myset
set([1, 3, 4, ’wordA’, ’wordB’])
>>> myset = set(mytuple)
>>> print myset
set([4.5, (1, 2), 12, 77, ’wordC’])
>>> myset = set(mystring)
>>> print myset
set([’q’, ’e’, ’u’])
Sets support set operations such as union, intersection, difference and symmetric
difference. The operators are
• −
Difference. Returns elements that are in one set but not in the other
• |
Logical OR. Elements in either one set or the other.
• &
Logical AND. Elements that are in both sets.
• ^
Logical Exclusive OR. Elements in either set but not both.
>>> mysetA = set([’apple’, ’mango’, ’strawberry’])
>>> mysetB = set([’mango’, ’pears’, ’grapes’])
>>> print mysetA - mysetB
set([’strawberry’, ’apple’])
>>> print mysetB - mysetA
set([’pears’, ’grapes’])
>>> print mysetA | mysetB
set([’strawberry’, ’mango’, ’apple’, ’grapes’, ’pears’])
>>> print mysetA & mysetB
>>> print mysetA ^ mysetB
set([’strawberry’, ’pears’, ’grapes’, ’apple’])
We have seen that sequence types like Lists, Tuples and Strings are indexed by
an integer. Dictionaries on the other hand are indexed by a key, which can be
any immutable value. Dictionaries are created by placing a comma separated
list of key:value pairs between braces.
>>> phone_nos = {"home":"988988988", "office":"0803332222", "integer":25}
>>> print phone_nos[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0
>>> print phone_nos[’home’]
Dictionaries can also be created from lists of tuples.
>>> myinfo = [("name","ershaad"), ("phone","98989898")]
>>> mydict = dict(myinfo)
>>> print mydict
{’phone’: ’98989898’, ’name’: ’ershaad’}
>>> print mydict["name"]
Sequence Unpacking
Python allows sequences of variables to be assigned to, that is they can be the
left hand side of an assignment operator. It can be used to extract values from
a sequence into a number of variables.
>>> mylist = ["one", "two", "three"]
>>> a, b, c = mylist
>>> print a
>>> print b
>>> print c
>>> a = 4
>>> b = 5
>>> a, b = b, a
>>> print a, b
5 4