Python

 

Overview

* Started by Guido van Rossum
* Named after Morty Python comedy troupe
* Supports OOP (No interface support)
* No curly brackets, colon sign and indentation are used instead
* Statement indentations are significant in Python.
Don’t mix spaces and tabs for indentations.
– See this post for details.
* No semicolon to terminate statements
* Comment char is #
* Escape char is \

Used For

* Scripts
* Web development
– Django
– Turbo Gears
– Zope
* Text processing
* Scientific computing
* Education

Install Python 3.2

* Download site

Windows

* Go to download site and download
Windows x86 MSI Installer (3.2)
* Double click the installer file to start the installer
– Install for all users
– Destination directory: C:\Python32\
– Accept defaults on Customize screen
* Start command line

cd C:\Python32
C:\Python32>python
Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 2 * 3
6
>>>

* Start command line
start -> All Programs -> Python 3.2 -> Python (command line)

* Start GUI
start -> All Programs -> Python 3.2 -> IDLE (Python GUI)

Cygwin

* Use Cygwin setup.exe program
* Select install Python
* Start command line

$ python
Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01)
[GCC 4.3.4 20090804 (release) 1] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 2*3
6
>>>

Unix

//TODO

Misc

* Comments

# This is a comment

Listing functions in a module

# list math functions
import math
dir(math)
 
# list all builtin functions
dir(__builtins__)
 
# print function help
help(f)
 
# print doc string
print(math.tanh.__doc__)
print(bin.__doc__)

Data Types

Strings

* Denote a string

# Single quotes: 
'this is a string'
 
# Double quotes: 
"this is a string"
 
# Triple quotes for multiline strings:
"""This is
a multiline
string
"""
 
# Raw string
r'c:\Program Files\python'

* String concatenation

'string 1' + 'string 2'
 
5 * 'hi' # hihihihihi
 
'ha' * 5 # hahahahaha

Type conversion

* Integer and strings -> floats: use float() function

float(3)
 
float('3.2')

* Integer and floats -> strings: use str(n) function

str(10)
str(-1.1)

* Float -> integer: use int() or round() functions

int(1.52)
1
round (1.52)
2

Variables and Values

* Variable points to a value.
* Assignments don’t copy
* Numbers and strings are immutable

# assignment
var1 = "value1"
 
# multiple assignment
x, y, z = 1, 'two', 3.0
 
# swapping var values
a, b = 6, 7
a, b
(6, 7)
a, b = b, a
a, b
(7, 6)

Reading Strings from the Keyboard

name = input('What is your name? ')
print('Hello ' + name + '!')

Boolean Logic

* Boolean values

True
False

* Logical operators

not
and
or
==

* If/else

pwd = input('What is the password? ')
if pwd == 'apple':
  print('ok')
else:
  print('wrong password')

* if/elif

if pwd == 'apple':
  print('ok')
elif pwd == 'peach'
  print('not bad')
else:
  print('not good')

* Conditional expression

food = input("What’ s your favorite food? ")
reply = 'yuck' if food == 'lamb' else 'yum'

* For loops

# count 0 to 9
for i in range(10):
  print(i)
 
# count 1 to 5
for i in range(1, 5):
  print(i)
 
# count from 5 to 1
for i in range(1, 5, -1):
  print(i)

* While loops

i = 0
while i < 10:
  print(i)
  i = i + 1

* Break out of loop: break

Functions

Define Functions

def area(radius):
  """
    ==== Function doc ====
    Usage: area(radius)
  """
  import math
  return math.pi * radius ** 2

main() Function

* No mandatory main() function
* Good practice to have a main() function
* Need implicit call to main() function to invoke it

Variable Scope

* All variables used within functions are local
* Global variables need to be re-declared within functions

name = 'Jack'
def sayhi():
    print('Hi, ' + name + '!')
 
def changeName(new_name):
    global name
    name = new_name
 
sayhi()
changeName('Jim')
sayhi()
 
>>> 
Hi, Jack!
Hi, Jim!
>>>

Function Parameters

* Function parameters are passed by object reference (see this post for details)
* Assign default parameter value

name = 'Jim'
 
def sayhi2(name, greeting = 'Hi'):
  print(greeting + ' ' + name + '!')
 
sayhi2(name)
sayhi2(name, 'Howdi')
>>> 
Hi Jim!
Howdi Jim!
>>>

* Keyword parameters
– All parameters need to have default values

def sayhi3(name = 'Jane', 
                 greeting = 'Hi'):
    print(greeting + ' ' + name + '!')
 
sayhi3(greeting = 'Nihao')
>>> 
Nihao Jane!
>>>

– Create a new object each time function is called by assigning a default ‘None‘ value to argument (see this post for details):

def append_to(element, to=None):
    if to is None:
        to = []
    to.append(element)
    return to
 
my_list = append_to(12)
print my_list
 
my_other_list = append_to(42)
print my_other_list
>>>[12]
>>>[42]

Modules

* A module is just another Python source file
* A module contains a collection of functions and assignments
* See this discussion on how to include another python file
* For example,

ac1file = './ac1.py'
execfile(ac1file)
"""
A test module
"""
 
def sayhi(name):
  """
  Simple hi
  """
  print('Hi ' , name, '!')
 
def sayhi2(name, greeting):
  """
  Hi with custom greeting
  """
  print(greeting, name, '!')

* Use module

import sayhi
 
sayhi.sayhi('jack')
sayhi.sayhi2('jack', 'Howdi')

* Output

Hi  jack !
Howdi jack !

Namespace

* Prevents name clashes

 

Strings

* String indexing

s1 = 'apple'
s1[0]
>>>a
s1[3]
>>>l

* Negative string indexing

s1 = 'apple'
s1[-1]
>>>e

* String slicing

>>> s = 'test string'
>>> s[0:3]
'tes'
>>> s[0:4]
'test'
>>> s[5:11]
'string'
>>> s[:4]
'test'
>>> s[5:]
'string'
>>> s[:]
'test string'
>>> s[-5:]
'tring'
>>> s[-6:]
'string'
>>> s[-11:-6]

* Use for-loop to access string characters

def printchar(str):
  for c in str:
    print(c)
 
printchar('test string')
 
t
e
s
t
 
s
t
r
i
n
g

Characters

* Unicode support
– Unicode to char: char(97) is ‘a’
– Char to unicode: ord(‘a’) is 97

Standard String Functions

//TODO

 

Regular Expression

import re  # use regular expressions
def is_done2(s):
  return re.match('done|quit', s) != None
 
if is_done2('done') :
  print('done')
else:
  print('not done')
 
>>>
done
>>>

Data Structure

* Checking data type: type()
* list

Sequence Types

* An ordered collection of values
* Three built-in sequence types:
– strings
– tuples (like lists but are immutable)
– lists
* For all sequences:
– left end index is 0
– right end index is -1
– can be sliced: seq[beginIdx:endIdx]
– can be concatenated with + and *.
– length can be determined by len(seq) function
– membership can be tested by x in seq

Tuples

– Items of a tuple are
enclosed in round brackets
separated by commas
– Tuples are immutables (unlike lists)

# empty tuple
()
 
# singleton tuple
(x,)
 
items = (1, 'cat', (2,3))
print(items)
(1, 'cat', (2, 3))
print(len(items))
3
print(items[0])
1
print(items[-1])
(2, 3)

Lists

* Like tuples except
– it’s mutable
– Uses [] instead of ()
– Can contain mixed elements

numbers = [1,2,-3,4]
print('numbers: ', numbers)
print('len(numbers): ', len(numbers))
print('numbers[0]: ', numbers[0])
print('numbers[2]: ', numbers[2])
print('numbers[3]: ', numbers[3])
numbers[0] = 100
print('now numbers: ', numbers)
print('now numbers[0]: ', numbers[0])

* List functions

s.append(x)
s.count(x)
s.extend(lst)
s.index(x)
s.insert(i, x)
s.pop(i)
s.remove(x)
s.reverse()
s.sort

* List comprehensions

print('[n * n for n in range(1,11)]: ')
print([n * n for n in range(1,11)])
 
[n * n for n in range(1,11)]: 
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

* Examples

list1 = 'a'
list2 = 'b'
list3 = list1 + list2 # ['a', 'b']
 
if list1[0] in list3
 print 'Found' + list1[0]

Dictionaries

* To store key:value pairs
* aka maps, hashtables, associative arrays
* Keys must be
– unique
– immutable
* Initialize dictionaries

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> tel.keys()
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
 
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}
 
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
 
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}

* Dictionary functions

d.items()
d.keys()
d.values()
d.get(key)
d.popitem()
d.clear()
d.copy()
d.fromkeys(s.t)
d.setdefault(key, v)
d.update(e)

Sets

* Like list but no duplicates
* Two kinds
– mutable sets
– immutable frozensets

lst = [1,1,1,2,2,3,3]
s = set(lst)
print(s)
 
# we get
{1, 2, 3}

IO

Format Strings

pi = 3.14159265358979323
print('pi is %f % pi gives: ', "pi is %f" % pi)
print("pi is %0.10f" % pi)
print("pi is %e" % pi)
 
print("{0} is a {1}".format('this', 'test'))
print("{pos1} is a {pos2}".format(pos1 = 'this', pos2 = 'another test'))

File IO

Listing files

import os
 
def list_cwd():
  """
  List files in the current directory
  """
  return os.listdir(os.getcwd())
 
def files_cwd():
  """
  Return files in the current directory
  as a list
  """
  return [p for p in list_cwd() 
          if os.path.isfile(p)]
 
def folders_cwd():
  return [p for p in list_cwd() 
          if os.path.isdir(p)]
 
def list_py(path = None):
  if path == None:
    path = os.getcwd()
  return [fn for fn in os.listdir(path)
          if os.path.isfile(fn)
          if fn.endswith('.py')]
 
def size_in_bytes(fname):
  return os.stat(fname).st_size
 
def cwd_size_in_bytes():
  total = 0
  for name in files_cwd():
    total = total + size_in_bytes(name)
  return total
 
def cwd_size_in_bytes2( ):
  return sum(size_in_bytes(f) 
             for f in files_cwd( ))
 
print(list_cwd())
print(files_cwd())
print(list_py())
print(size_in_bytes('testfile.py'))
print(cwd_size_in_bytes())
print(cwd_size_in_bytes2())

File modes

‘r’: read mode
‘w’: write mode
‘a’: append mode
‘b’: binary mode
‘t’: text mode (default)
‘+’: open for both read and write

Text files

* Read text file

def print_file1(fname):
  """
  Read file line by line
  """
  f = open(fname, 'r')
  for line in f:
    print(line, end = '')
  f.close()
 
print_file1(r'c:\temp\test.txt')
 
def print_file2(fname):
  """
  Read file as string
  """
  f = open(fname, 'r')
  print(f.read())
  f.close()
 
print()
print_file2(r'c:\temp\test.txt')

* Write text file

def write_file1(fname):
  """
  Write to a file
  """
  if os.path.isfile(fname):
    print(fname, ' already exists.')
  else:
    f = open(fname, 'w')
    f.write('Hello world!\n')
    f.write('Hello again.\n')
    f.close()
 
write_file1(r'c:\temp\textwrite.txt')

Binary File

* Read binary file

def is_gif(fname):
  """
  Check if a file is gif file
  """
  f = open(fname, 'br')
  first4 = tuple(f.read(4))
  f.close()
  return first4 == (0x47, 0x49, 0x46, 0x38)
 
print(is_gif(r'c:\temp\textwrite.txt'))

Pickling

* aka serialization

import pickle
def pickle_file1(infile, outfile):
  inf = open(infile, 'r')
  outf = open(outfile, 'bw')
  pickle.dump(inf.read(), outf)
  inf.close()
  outf.close()
 
pickle_file1(r'c:\temp\test.txt', r'c:\temp\testpickle.txt')
 
def unpickle_file1(fname):
  f = open(fname, 'br')
  str = pickle.load(f)
  print(str)
  f.close()
 
unpickle_file1(r'c:\temp\testpickle.txt')

Read Web Page with urllib

import urllib.request
 
def read_webpage1(urlstr):
  resp = urllib.request.urlopen(urlstr)
  return resp.read()
 
print(read_webpage1('http://www.google.com')[0:50])
 
import webbrowser
webbrowser.open('http://www.google.com')

Exception Handling

* Raise exception

raise MyTestError('My test exception')

* Catch exceptions

def test_exception():
  try:
    return 'done.'
  except FirstException:
    return 'FirstException'
  except SecondException:
    return 'SecondException'
  except:
    return 'Unknown exceptions'
  finally:
    print('finalized')
 
print(test_exception())

* with statement
//TODO

 

OOP

Class

* A method must have self as its first parameter
* Private variables (quasi) use double under scores

class Person:
  """
  Class representing a person
  """
 
  # Constructor
  def __init__(self):
    self.name = 'unknown'
    self.__age = 0
 
  def __init__(self, name = 'unknown', age = 0):
    self.__name = name
    self.__age = age
 
  # to string
  def __str__(self):
    return "Person('%s', '%d')" % (self.__name, self.__age)
 
  # object official message
  def __repr__(self):
    return str(self)
 
  def method1(self):
    return "method1"
 
  # --------- Getters and Setters    
  @property
  def age(self):
    return self.__age
 
  @age.setter
  def age(self, age):
    if 0 < age < 150:
      self.__age = age
    else:
      raise ValueError('Invalid age.')
 
p = Person()
print(p)
 
p2 = Person('John', 25)
print(p2)
print(p2.age)
 
p2.age = 95
print(p2.age)
 
p2._Person__age = 105
print(p2.age)
 
#p2.age = 200
#print(p2.age)

Inheritance

# --------- Programmer inherits Person
class Programmer(Person):
  # Override object official message
  def __repr__(self):
    return "Programmer: %s" % str(self)
 
  # Override method1
  def method1(self):
    return "Programmer: method1"
 
programmer1 = Programmer('Jane', 30)
print(programmer1)
print(programmer1.method1())

Polymorphism

# Define a base Player class
class Player:
  def __init__(self, name):
    self._name = name
    self._score = 0
 
  def reset_score(self):
    self._score = 0
 
  def incr_score(self):
    self._score = self._score + 1
 
  def get_name(self):
    return self._name
 
  def __str__(self):
    return "name = '%s', score = %s" % (self._name, self._score)
 
  def __repr__(self):
    return 'Player(%s)' % str(self)
 
# Define a human player by extending Player class
class Human(Player):
  def __repr__(self):
    return 'Human(%s)' % str(self)
 
  # Define how human selects a move
  def get_move(self):
    while True:
      try:
        n = int(input('%s move (1 - 10): ' % self.get_name()))
        if 1 <= n <= 10:
          return n
        else:
          print('try again!')
      except:
        print('try again.')
 
# Define a computer player by extending Player class
import random
class Computer(Player):
  def __repr__(self):
    return 'Computer(%s) % str(self)'
 
  # Define how computer makes a move
  def get_move(self):
    return random.randint(1, 10)
 
# Define a game function
# The game does not know if p1 and p2 are human or computer,
# it invokes different moves depending on 
# if p1 and p2 are human or computer (polymorphism)
def play_undercut(p1, p2):
  p1.reset_score()
  p2.reset_score()
  m1 = p1.get_move()
  m2 = p2.get_move()
 
  print("%s move: %s" % (p1.get_name(), m1))
  print("%s move: %s" % (p2.get_name(), m2))
 
  if m1 == m2 - 1:
    p1.incr_score()
    print(p1, '\n\r', p2, '\n\r%s wins!' % p1.get_name())
  elif m2 == m1 - 1:
    p2.incr_score()
    print(p1, '\n\r', p2, '\n\r%s wins!' % p2.get_name())
  else:
    print(p1, '\n\r', p2, '\n\rdraw: nobody win\n')
 
  print('done\r\n')
 
# Start game
c = Computer('Hal')
h = Human('Jane')
play_undercut(c,h)
 
# Computer vs computer
c1 = Computer('Hal')
c2 = Computer('hal2')
play_undercut(c1, c2)
 
# Human vs Human
h1 = Human('John')
h2 = Human('Jane')
play_undercut(h1, h2)

References

* Python: Visual QuickStart Guide, Second Edition By: Toby Donaldson

This entry was posted in python. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

This site uses Akismet to reduce spam. Learn how your comment data is processed.