Download Introduction to Python - High-Performance Computing – Temple

Document related concepts
no text concepts found
Transcript
Introduction to Python
Ershaad Basheer
Research Assistant Professor
XSEDE Campus Champion
Dept. of Mathematics
[email protected]
Python

High level language

Interpreted

Interactive or script file like shell

Object oriented and general purpose

Present on most Linux distributions

Simple syntax
Python

Large standard library

Libraries are organised as modules

Extensive library allows quick prototyping

Python is free software

Two major versions



2.x has wider installed base
3.x is backward incompatible and is focus of
development
We cover features available in 2.6
Python interpreter

Python shell or interpreter can be started with
$ 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.
>>>
Interactive interpreter

>>> is the primary prompt
>>> print 'Hello, World'
Hello, World
>>>

String constants between double or single
quotes
Interactive interpreter

Expressions are evaluated
>>> print 1 + 3
4
>>>
Variables


Created with the assignment operator
RHS can be literal value, expression or another
variable

Python variables are names / identifiers

Variable types are dynamic

type() built-in function
Variables
>>> myval = 25
>>> print myval
25
>>> mystring = "Hello, World"
>>> print mystring
Hello, World
>>> mystring = 25 * 2
>>> print mystring
50
Variables
>>> a = 22
>>> type(a)
<type 'int'>
>>> a = 22.0
>>> type(a)
<type 'float'>
>>> a = 3+2j
>>> type(a)
<type 'complex'>
>>> type('abc')
<type 'str'>
Built-in Types

Numeric Types

int, float, long and complex

int has limited range

long integers have arbitrary precision


Literal has L suffix
Octal and hex input
Variables
>>> a = 22
>>> type(a)
<type 'int'>
>>> a = 12343986238947239L
>>> type(a)
<type 'long'>
>>> a = 0x2F
>>> print a
47
Variables
>>> type(a)
<type 'int'>
>>> a = 0772
>>> print a
506
>>> type(a)
<type 'int'>
>>> a = 0xFFFAL
>>> type(a)
<type 'long'>
Built-in Types

Numeric Types

float usually implemented as C double

Literal with decimal point or exponential notation
Variables
>>> a = 22.00
>>> type(a)
<type 'float'>
>>> b = 1E3
>>> type(b)
<type 'float'>
Built-in Types

Numeric Types

Built-in functions




int()
long()
float()
complex()
>>> print float('22.2')
22.2
>>> print int(22.2)
22
Built-in Types

Operations on numeric types

Usual arithmetic operators + - * %

** is the power operator

Some operators are built-in functions

abs()returns the absolute value
>>> a = -2.23
>>> b = abs(a)
>>> print b
2.23
Division


Special attention to the / division operator
In Python 2.x performs floor division if both
operands are of type int

True division if any of the operands are float

May lead to unexpected results
>>> 1/2
0
>>> 1/2.0
0.5
Division



In Python 3.x / always does true division
// operator in Python 3.x and 2.x always
performs floor division
Python 3.x behaviour can be enabled in 2.x
>>> from
>>> 1/2
__future__ import division
0.5
>>> 1//2.0
0.0
Built-in Types

Operators



Operands of different numerical types
Less general operand is promoted to the more
general operand
int → long → float → complex
Type complex has two attributes
>>> avar = 3+2.3j

>>> print avar.real
3.0
>>> print avar.imag
2.3
Built-in Types

Numeric types

Are immutable types

Value cannot be changed once created

Reassignment leads to creation of new object in
memory
>>> cvar = 3+1.2j
>>> cvar.real = 2.2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: readonly attribute
Built-in Types

Sequence Types


We cover strings, lists and tuples
Strings (type str)

String literals are enclosed in single/double quotes
>>> mystr = 'Hello, World'
>>> type(mystr)
<type 'str'>
Built-in Types

Sequence Types

Lists (type list)


Collection of elements
Can be of different types
>>> mylist = ['hello', 12, 23.5]
>>> print mylist
['hello', 12, 23.5]
>>> mynlist = [1, 2, 3, ['x','y','z'], 4]
Built-in Types

Sequence Types

Tuples (type tuple)


Like lists, but immutable
Parens optional
 Required for empty tuple
Built-in Types

Sequence Types
>>> mytuple = 1.2, 3, 'word'
>>> print mytuple
(1.2, 3, 'word')
>>> mytuple = (1, 4.5, "World")
>>> print mytuple
(1, 4.5, 'World')
>>> empty_tuple = ()
>>> print empty_tuple
()
Built-in Types

Sequence Types

Syntax for a one element tuple
>>> single_tuple = 33,
>>> print single_tuple
(33,)
Built-in Types

Operations on Sequence Types

Membership testing

Returns a value of type bool (True or False)
>>> mylist = [1, 33.3, 'world']
>>> mytuple = ('hello', 123, 3+4j)
>>> print 33.3 in mylist
True
>>> print 'hello' in mytuple
True
>>> print 3+4j in mylist
False
Built-in Types

Operations on Sequence Types

Membership testing

not in inverts sense of test
>>> mylist = [1, 33.3, 'world']
>>> print 'world' not in mylist
False
Built-in Types

Operations on Sequence Types

Concatenation: + operator
>>> list1 = [1, 2, 'world']
>>> list2 = ['a', 'b', 33]
>>> list1 + list2
[1, 2, 'world', 'a', 'b', 33]
>>> mystr1 = 'sentence one'
>>> mystr2 = 'two words'
>>> mystr1 + mystr2
'sentence onetwo words'
Built-in Types

Operations on Sequence Types

Concatenated copies: * operator
>>> mystr2 = 'two words'
>>> print mystr2*4
two wordstwo wordstwo wordstwo words
>>> zeros = [0]*5
>>> print zeros
[0, 0, 0, 0, 0]
Built-in Types

Operations on Sequence Types

Indexing




Returns an element of a sequence
Index of first element is zero
Negative index counts from end, beginning
with -1
a[i]
Sequence Types

Indexing
>>> mylist = ['a', 'b', 'word', [1,2,3], 20, 0]
>>> print mylist[0]
a
>>> print mylist[3]
[1, 2, 3]
>>> print mylist[-1]
0
Sequence Types

Operations on Sequence Types

Slicing



Returns a sequence of elements
a[i:j] returns the sequence of elements
between i and j
a[i:j:k] returns a sequence of elements
between i and j with a step of k
Sequence Types
>>> mylist = ['a', 'b', 'word', [1,2,3], 20, 0]
>>> print mylist[0:2]
['a', 'b']
'a'
0
'b'
1
'word'
2
20
[1,2,3]
3
4
>>> print mylist[0:6]
['a', 'b', 'word', [1, 2, 3], 20, 0]
0
5
6
Sequence Types

Slicing
>>> mylist = ['a', 'b', 'word', [1,2,3], 20, 0]
>>> print mylist[:3]
['a', 'b', 'word']
>>> print mylist[:]
['a', 'b', 'word', [1, 2, 3], 20, 0]
>>> print mylist[::2]
['a', 'word', 20]
Sequence Types

Indexing/Slicing strings
>>> print "abcedfghijk"[4]
d
>>> print "abcedfghijk"[0:10:2]
acdgi
Sequence Types

Indexed sequences can be assigned to
>>> mylist = ['a', 'b', 'word', 33.3, 20, 0]
>>> mylist[2] = 'NEWWORD'
>>> print mylist
['a', 'b', 'NEWWORD', 33.3, 20, 0]
Sequence Types

Sliced sequences can be assigned to
>>> mylist[3:6] = 0, 0, 0
>>> print mylist
['a', 'b', 'NEWWORD', 0, 0, 0]
Sequence Types

Assignment only for mutable types
>>> mystr = "abcdef"
>>> mytuple = (1, 4, 'x')
>>> mystr[2] = 'f'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> mytuple[0] = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item
assignment
Sequence Types

Built-in functions that operate on lists
>>> mystr = "two words"
>>> print len(mystr)
9
>>> mylist = ['a', 'b', 'word', 'python']
>>> print sorted(mylist)
['a', 'b', 'python', 'word']
Built-in Types

Set Type

Type set

Unordered containers

No duplicates

Created with set() built-in function

2.7 supports newer syntax


Comma separated elements between braces
{'elem1', 'word2'}
Sets
>>> mylist = [1, 3, 4, 1, 'wordA', 'wordB', 'wordA']
>>> myset = set(mylist)
>>> print myset
set([1, 3, 4, 'wordA', 'wordB'])
>>> mytuple = ('wordC', 4.5, 77, (1,2), 12, (1,2))
>>> myset = set(mytuple)
>>> print myset
set([4.5, (1, 2), 12, 77, 'wordC'])
>>> mystring = "queue"
>>> myset = set(mystring)
>>> print myset
set(['q', 'e', 'u'])
Built-in Types

Set Operations

Return sets

- Difference

| Logical OR

& Logical AND

^ XOR
Sets
>>> mysetA = set(['Tokyo','Berlin', 'Nairobi', 'Manama'])
>>> mysetB = set(['Khartoum', 'Beijing', 'Nairobi'])
>>> print mysetA - mysetB
set(['Manama', 'Berlin', 'Tokyo'])
>>> print mysetA | mysetB
set(['Manama', 'Berlin', 'Khartoum', 'Tokyo', 'Nairobi',
'Beijing'])
>>> print mysetA & mysetB
set(['Nairobi'])
>>> print mysetA ^ mysetB
set(['Beijing', 'Berlin', 'Manama', 'Khartoum', 'Tokyo'])

Unordered, so indexing and slicing not supported
Built-in Types

Dictionary

Type dict

Can be indexed using a key

Key can be any immutable hashable type
Includes str, tuple,
int/long/float ...etc
 But not list, set
{key1:value1, key2:value2, …}



Or dict() passing a sequence type in which each
element is a sequence of 2 elements
Dictionaries
>>> phone_nos = {"home":"988988988",
... "office":"0803332222", "integer":25}
>>> print phone_nos['home']
988988988
>>> myinfo = [("name","ershaad"), ("phone","98989898")]
>>> mydict = dict(myinfo)
>>> print mydict
{'phone': '98989898', 'name': 'ershaad'}
Built-in Types

Dictionary operations

Indexing

Using a key
Dictionaries
>>> mydict = {'Name':'John', (1,2,3):'Tuple', 32:'int'}
>>> mydict['Name']
'John'
>>> mydict[(1,2,3)]
'Tuple'
>>> mydict[32]
'int'
>>> mydict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0
Dictionaries

Dictionaries are mutable
>>> mydict = {'Name':'John', (1,2,3):'Tuple', 32:'int'}
>>> mydict['Name'] = 'New name'
>>> print mydict
{32: 'int', 'Name': 'New name', (1, 2, 3): 'Tuple'}

Membership testing of keys are supported

Using in and not in
Sequence Unpacking

As a extension of assigning to variables

A sequence of variables can also be assigned to

RHS must also be a sequence
Sequence Unpacking
>>> mylist = ["one", "two", "three"]
>>> a, b, c = mylist
>>> print a
one
>>> print b
two
>>> print c
three
>>> a = 4
>>> b = 5
>>> a, b = b, a
>>> print a, b
5 4
Conditionals

Truth Values

Besides the bool value False

Following are considered false in Python
Special value None
 Number 0 represented in any of the numeric
types
 0, 0L, 0.0, 0+0j
 A sequence type of zero elements
 ””, [], ()
Everything else is true



Standard comparison operators <, <=, >=, >, ==,
!=, is, is not return True or False
Indentation

Blocks grouped by indentation level

Advice: only use spaces, never use tabs

Statement that begins a new block ends in a colon

An indentation level is usually 4 spaces

Interactive interpreter

New block gives … prompt

Block ended with a blank line
Conditionals

if...elif...else construct
>>> myint = 234
>>> if myint % 2 == 0:
...
print "Multiple of 2"
... elif myint % 3 == 0:
...
print "Multiple of 3"
... elif myint % 4 == 0:
...
print "Multiple of 4"
... else:
...
print "Not multiple of 2, 3 or 4"
...
Multiple of 2
Identity Comparison

is and is not comparison operators compare identity
>>> a = 25
>>> a = [1,2,3]
>>> b = a
>>> b = a
>>> print a is b
>>> print a is b
True
True
>>> a = 13
a[0] = 'newval'
>>> print a is b
>>> a is b
False
True
>>> print a
['newval', 2, 3]
>>> print b
['newval', 2, 3]
Conditionals

Combining conditions with and, or and not
>>> a = 123
>>> if (a > 100) and (a < 200):
...
print '100 < a < 200'
... else:
...
print 'out of range'
...
100 < a < 200

and and or return the last expression executed
Looping

for loop


Loops over values in a sequence
range() built-in
Returns sequential numbers in a list
>>> seq = range(10)

>>> print seq
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for loop
>>> for i in range(5):
...
print "Current value of i is ", i
...
print "twice that is", i*2
...
Current value of i is
0
twice that is 0
Current value of i is
1
twice that is 2
Current value of i is
2
twice that is 4
Current value of i is
3
twice that is 6
Current value of i is
twice that is 8
4
for loop

Looping over list of tuples using sequence unpacking
>>> mylist = [("name","ershaad"), ("surname","basheer"),
... ("dept.", "TUE-CMS")]
>>> for i in mylist:
...
print i
...
('name', 'ershaad')
('surname', 'basheer')
('dept.', 'TUE-CMS')
for loop

Looping over list of tuples using sequence unpacking
>>> for field, value in mylist:
...
print field, " has value ", value
...
name
has value
surname
dept.
ershaad
has value
has value
basheer
TUE-CMS
for loop

Loop over any sequence type
>>> mystring = "TEMPLE"
>>> for alph in mystring:
...
...
T
E
M
P
L
E
print alph
for loop

Loop over dict type, loops over keys
>>> mydict = {"home":"988988988", "office":"0803332222",
... "integer":25}
>>> for key in mydict:
...
print key, " --> ", mydict[key]
...
home
-->
office
integer
988988988
-->
-->
0803332222
25
List comprehensions

Consider a loop that creates a list
>>> powertwo = []
>>> for i in range(10):
...
powertwo += [2**i]
...
>>> print powertwo
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
List comprehensions

List comprehensions provide concise syntax

Brackets with expression followed by a for clause
>>> powertwo = [2**i for i in range(10)]
>>> print powertwo
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
List comprehensions

Consider a nested loop that creates a list
>>> ijlist = []
>>> for i in range(3):
...
...
for j in range(3):
ijlist += [(i,j)]
...
>>> print ijlist
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2),
(2, 0), (2, 1), (2, 2)]
List comprehensions

Can have more than one for clause

Equivalent list comprehension
>>> [(i,j) for i in range(3) for j in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2,
0), (2, 1), (2, 2)]
List comprehensions

if statement can be incorporated

Odd powers of 2 from between 0 and 10
>>> powertwo = [2**i for i in range(10) if i%2 != 0]
>>> print powertwo
[2, 8, 32, 128, 512]
while Loop

while loop
>>> count = 0
>>> while count < 5:
...
print count
...
count = count + 1
...
0
1
2
3
4
break and continue

break and continue statements

break terminates the loop that encloses it

continue causes the loop to advance to next iteration
>>> while True:
...
inp = raw_input("Enter word :")
...
if inp == 'end' or inp == 'End':
...
...
...
...
...
...
break
elif inp == 'skip' or inp == 'Skip':
continue
else:
print inp
break and continue

break and continue statements

break terminates the loop that encloses it

continue causes the loop to advance to next iteration
Enter word :World
World
Enter word :eND
eND
Enter word :word
word
Enter word :skip
Enter word :End
Functions

Groups code into a callable routine

Optionally returns a value

def keyword to create function

Formal parameters in parentheses


Function that returns a string that has all occurrences of
one character replaced with another
Return value assigned to a variable name
Functions
>>> def subst(fchar, tchar, srcstr):
...
result = ""
...
for char in srcstr:
...
if char == fchar:
...
result += tchar
...
else:
...
...
result += char
return result
...
>>> mystring = 'helloworld'
>>> mystring = subst('o', 'x', mystring)
>>> print mystring
hellxwxrld
Functions

Keyword arguments




Arguments are usually positional
Python allows arguments to be specified by parameter
name
Order doesn't matter
Except when positional and keyword are mixed in the
same call
Functions
>>> mystring = 'helloworld'
>>> mystring = subst('o', 'x', mystring)
>>> print mystring
hellxwxrld
>>> mystring = subst(tchar='x', fchar='o', srcstr=mystring)
>>> print mystring
hellxwxrld
>>> mystring = subst('o', srcstr=mystring, tchar='x')
>>> print mystring
hellxwxrld
Functions
>>> mystring = subst(fchar='o', 'x', mystring)
File "<stdin>", line 1
SyntaxError: non-keyword arg after keyword arg
Functions

Variable Scope

Functions have their own namespace

Function variables in local namespace

Exists until the function returns or terminates


Python searches from inner to outer namespaces for
identifiers
Consequence


Global variables masked by local ones
Unmasked when function scope ends
Functions
>>> def myfunc():
...
lvar = 'myfunc variable'
...
print lvar
...
print gvar
...
>>> lvar = 'global value'
>>> gvar = 'global value'
>>> myfunc()
myfunc variable
global value
Functions

Case is a little different for mutable types
>>> def modval(im):
...
im[0] = 22
...
>>> mylist = ['word', 0.15, 'last']
>>> modval(mylist)
>>> print mylist
[22, 0.15, 'last']
Functions

Case is a little different for mutable types
>>> mylist = ['word', 0.15, 'last']
>>> modval(mylist[:])
>>> print mylist
['word', 0.15, 'last']
>>> import copy
>>> >>> modval(copy.deepcopy(mylist))
>>> print mylist
['word', 0.15, 'last', [1, 2, 4]]
Methods

Are functions

But, are bound to a variable

Perform some operation on the variable data when called

Set of methods for each data type

To call a method called varmthd() of variable var

Use var.varmthd()
Methods
>>> mylist1 = [1, 2, 'end']
>>> mylist2 = ['word', 3, (1,2)]
>>> mylist1.append('newelem')
>>> mylist2.append(3.33)
>>> print mylist1
[1, 2, 'end', 'newelem']
>>> print mylist2
['word', 3, (1, 2), 3.33]
>>> mylist2[2] = 'word'
>>> print mylist2.count('word')
2
Methods
>>> mystr = 'hello, world'
>>> newstr = mystr.upper()
>>> print newstr
HELLO, WORLD
>>> mylist = ['word1', 'word2', 'end']
>>> print ''.join(mylist)
word1word2end
>>> print '||'.join(mylist)
word1||word2||end
Methods

dir() and help()built-in functions
dir()
>>> mylist = []
>>> print dir(mylist)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getslice__', '__gt__',
'__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__',
'__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__reversed__', '__rmul__',
'__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__',
'__subclasshook__', 'append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
help()
>>> mylist = []
>>> help(mylist.append)
Help on built-in function append:
append(...)
L.append(object) -- append object to end
>>> help(list.count)
Help on method_descriptor:
count(...)
L.count(value) -> integer -- return number of occurrences of value
Python scripts

Similar to bash scripts

First line

#!/usr/bin/env python
Make executable with

chmod +x scriptfile.py
Sequence Types

Function to convert a string to its Rot13
encoding

a→n

b→o

c→p
Exercise

Implement merge sort algorithm

Divide and conquer algorithm


Recursively divide list until base case is
reached
Merge back results of each recursive step
Exercise
23 76 36 43 41
23 76 36
23 76
43 41
mergesort(list_us)
36
43
41
76
36
43
41
23 76
36
43
41
23
23 36 76
41 43
23 36 41 43 76
merge(left,right)
Exercise

Implement using two functions


mergesort(list_unsorted)
merge(left, right)
Related documents