A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks...

38
A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University [email protected] @Duke University January 21, 2015

Transcript of A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks...

Page 1: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

A Brief Review of Python

COMPSCI 270 (Thanks for Richard Guo’s slides)

Zhenyu Zhou

CS Dept., Duke University [email protected]

@Duke University January 21, 2015

Page 2: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Outline n  Installing n  Executing n  The Python Style n  Basic Operators n  Variable Types n  Built-in Data Structures n  Control Flows n  Function n  Class n  Module n  Useful Tricks n  Reference 2

Page 3: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Installing n  Mac OS (Recommended)

q  Already done after OS X 10.8 q  Course website

n  Linux (Sometimes the same as OS X, but may not be tested by myself) q  apt-get

n  Windows (Not recommended) q  Official website

n  https://www.python.org/downloads/windows/

n  Version q  2.7 q  python --version

3

Page 4: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Installing

n  Try to run pacman.py q  python pacman.py (in terminal)

n  Text editor q  Vim q  Sublime q  Notepad++ q  Etc.

4

Page 5: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Installing

n  Eclipse (Recommended IDE) q  Plugin

n  PyDev

q  Install plugins (not only for PyDev) n  Install new software/eclipse marketplace (Mac)

q  Tell Eclipse where is your python n  Preference -> PyDev -> Interpreters -> Python Interpreter n  The location of your interpreter (Mac & Linux): whereis python

q  Create new python project n  File -> New -> Project -> PyDev -> Pydev Project

5

Page 6: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Outline n  Installing n  Executing n  The Python Style n  Basic Operators n  Variable Types n  Built-in Data Structures n  Control Flows n  Function n  Class n  Module n  Useful Tricks n  Reference 6

Page 7: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Executing n  Terminal

q  Shell prompt - python abc.py n  File name ends with .py

q  Python prompt n  After typing “python” under shell prompt n  Type the script directly

7

Page 8: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Executing n  Shell prompt

n  Python prompt

8

Page 9: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Outline n  Installing n  Executing n  The Python Style n  Basic Operators n  Variable Types n  Built-in Data Structures n  Control Flows n  Function n  Class n  Module n  Useful Tricks n  Reference 9

Page 10: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

The Python Style n  Interpreter

q  Interactive running q  Running a script

n  Dynamic q  Use variables without declaration

n  Structured by Indent and colon q  Options: TAB, 2 spaces, 4 spaces q  Be consistent throughout the program! q  Q: which one is used in pacman.py?

10

Page 11: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Outline n  Installing n  Executing n  The Python Style n  Basic Operators n  Variable Types n  Built-in Data Structures n  Control Flows n  Function n  Class n  Module n  Useful Tricks n  Reference 11

Page 12: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Basic Operators n  Most are straightforward

q  + - / * % []

n  Division: integer vs. fractional q  10/3=3 q  10.0/3=3.3333.. q  Trick: a * 1.0 / b q  Can be different in other python version

n  Power: ** (not ^)

12

Page 13: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Outline n  Installing n  Executing n  The Python Style n  Basic Operators n  Variable Types n  Built-in Data Structures n  Control Flows n  Function n  Class n  Module n  Useful Tricks n  Reference 13

Page 14: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Variable Types

n  Integer q  100

n  Double q  3.14

n  Bool q  True

n  None q  Just like null in Java

14

Page 15: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Outline n  Installing n  Executing n  The Python Style n  Basic Operators n  Variable Types n  Built-in Data Structures n  Control Flows n  Function n  Class n  Module n  Useful Tricks n  Reference 15

Page 16: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Built-in Data Structures n  List

q  An array storing different kinds of elements n  >>> a = [] (initialize) n  >>> a = [“hello”, 1, 5.5] n  >>> listOfList = [[1,2],[3,4]]

q  Indexed from 0 q  Operations

n  a.append(x) n  removal

q  del a[0] q  if “hello” in a: a.remove(“hello”) (first occurrence of the value)

n  a.sort() (do not forget the brackets, it is a method) n  a.reverse() n  a + listOfList (concatenation)

16

Page 17: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Built-in Data Structures n  Tuple

q  x = (1,2,’ok’) q  Much like a list, but cannot be changed q  One-element tuple: (1, )

n  String q  s = 'hello '+'world’ q  Newline: \n q  Quote: \’ q  Q: how to print out ‘\’ itself?

17

Page 18: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Built-in Data Structures n  Dictionary

q  A hash table: key -> value n  mydict = {} (initialize) n  mydict[1] = “one” (automatically adding a new key-value pair)

q  Keys do NOT have the same order as you put in them q  Key must be of an immutable type:

n  string, number

n  tuple q  mydict[(-1,0)] = “west”

q  Operations n  mydict.keys() (in the form of a list) n  mydict.values() (in the form of a list) n  print mydict[(-1,0)]

n  del mydict[(-1,0)]

q  How to get the keys sorted by value? n  for w in sorted(mydict, key=mydict.get): n  print w, mydict[w]

18

Page 19: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Built-in Data Structures n  Set

q  An unordered collection of unique elements q  Efficient to test if an element is marked/visited

n  x in exploredSet

q  Initialization n  setOfShapes = set() (empty set) n  setOfShapes = set([“circle”, “triangle”, “square”, “circle”]) n  setOfShapes = {“circle”, “triangle”, “square”, “circle”}

q  Operations n  setOfShapes.add(“hexagon”) n  setOfShapes.remove(“circle”) n  set1 | set2 n  set1 & set2 n  set1 – set2

19

Page 20: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Outline n  Installing n  Executing n  The Python Style n  Basic Operators n  Variable Types n  Built-in Data Structures n  Control Flows n  Function n  Class n  Module n  Useful Tricks n  Reference 20

Page 21: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Control Flows n  If statement

q  age = 20 q  if age >= 6: # Don’t forget “:” q  print 'teenager' q  elif age >= 18: q  print 'adult' q  else: q  print 'kid'

n  Q: What’s the output?

21

Page 22: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Control Flows n  For statement

q  sum = 0 q  for x in range(101): # what is range()? q  sum = sum + x q  print sum

q  names = ['Michael', 'Bob', 'Tracy'] q  for name in names: q  print name

n  Q: how to translate for(int i = 50; i < 100; i += 2) into python?

22

Page 23: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Control Flows n  While statement

q  i = 0 q  while i<100: q  i = i + 1

n  Special clauses in loops q  break q  continue q  else

n  Executed if no “break” is executed in the loop

n  for answer in possibleAnswers:n  if isRightAnswer(answer):n  breakn  else:n  print “No answer found”

23

Page 24: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Outline n  Installing n  Executing n  The Python Style n  Basic Operators n  Variable Types n  Built-in Data Structures n  Control Flows n  Function n  Class n  Module n  Useful Tricks n  Reference 24

Page 25: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Function n  Defining a function

q  def myadd(x, y):q  z = x+yq  return z (would return None if without this line)

n  Calling functions q  myNumbers = [2, 4]q  print myadd(myNumbers[0], myNumbers[1])q  print myadd(*myNumbers)

25

Page 26: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Outline n  Installing n  Executing n  The Python Style n  Basic Operators n  Variable Types n  Built-in Data Structures n  Control Flows n  Function n  Class n  Module n  Useful Tricks n  Reference 26

Page 27: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Class n  Defining a class

q  def classname(baseClassName)

n  Providing data attributes and methods with “self” q  self.title = “a simple class”q  def showTitle(self, repeats=1):q  for t in range(0, repeats):q  print self.title

n  Construction q  def __init__(self, someArg):

n  Making a variable looking private by naming with a leading underscore q  Unlike C++, Python does not enforce data hiding mechanism

27

Page 28: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Class – Queue class Queue: def __init__(self): self.queueList = [] def push(self, x): self.queueList.append(x) def pop(self): z = self.queueList[0] del self.queueList[0] return z def isEmpty(self): return (len(self.queueList)==0)

28

Page 29: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Class - TreeNode

n  Try to implement a TreeNode class on your own q  Parent q  Path from root q  “May” be helpful to your assignments

29

Page 30: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Outline n  Installing n  Executing n  The Python Style n  Basic Operators n  Variable Types n  Built-in Data Structures n  Control Flows n  Function n  Class n  Module n  Useful Tricks n  Reference 30

Page 31: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Module

n  Similar to library and package in Java

n  A .py file is called a module

n  Import a module q  import utilq  myQueue = util.Queue()

n  Please learn more about util.py

31

Page 32: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Outline n  Installing n  Executing n  The Python Style n  Basic Operators n  Variable Types n  Built-in Data Structures n  Control Flows n  Function n  Class n  Module n  Useful Tricks n  Reference 32

Page 33: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Useful Tricks n  Try to print everything out when debugging

q  More advanced n  assert n  logging n  pdb

n  Looping with ease q  Iterate with multiple variables

n  for i, v in enumerate([“a”,”b”,”c”])n  print i, v

33

Page 34: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Useful Tricks

n  About list q  >>> classmates = ['Michael', 'Bob', 'Tracy']q  >>> classmates[-1]q  'Tracy’q  >>> classmates[0:2]q  ['Michael', 'Bob']

q  >>> S = [x**2 for x in range(4)]q  >>> Sq  [0, 1, 4, 9]

34

Page 35: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Useful Tricks

n  Copy before modifying q  What would you expect?

n  x = [1,2,3,4] n  y = x n  y.append(5) n  print x

q  Even more careful when passing them to a function n  x = [1,2,3,4] n  def sumUp(z): n  z.append(sum(z)) n  return z[-1] n  sumUp(x) n  print x

q  Solution n  X = copy.copy(Y) n  X = copy.deepcopy(Y) n  X = Y.copy() 35

Page 36: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Outline n  Installing n  Executing n  The Python Style n  Basic Operators n  Variable Types n  Built-in Data Structures n  Control Flows n  Function n  Class n  Module n  Useful Tricks n  Reference 36

Page 37: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Reference n  Thanks for Richard Guo’s python review slides. Some

portions of this slide will be based on his slides. n  Official tutorial

q  http://docs.python.org/2/tutorial/

n  Python/UNIX tutorial on the course webpage q  http://inst.eecs.berkeley.edu/~cs188/fa10/projects/tutorial/

tutorial.html#Python

n  A Byte of Python q  http://swaroopch.com/notes/python/

n  Python Information and Examples q  http://www.secnetix.de/olli/Python/

n  Learning Python (O’Reilly) n  Python Pocket Reference (O’Reilly)

37

Page 38: A Brief Review of Python - Duke Computer Science · A Brief Review of Python COMPSCI 270 (Thanks for Richard Guo’s slides) Zhenyu Zhou CS Dept., Duke University zzy@cs.duke.edu

Thank you!

Questions?

38