Slide 1

Slide 1 text

Introduction to Python

Slide 2

Slide 2 text

Interactive Shell • Interpreter talks with you • Good for experiments • The REPL

Slide 3

Slide 3 text

$  python   Python  2.7.3  (default,  Mar  18  2014,  05:13:23)     [GCC  4.6.3]  on  linux2   Type  "help",  "copyright",  "credits"  or   "license"  for  more  information.   >>>

Slide 4

Slide 4 text

$  python3   Python  3.2.3  (default,  Mar    1  2013,  11:53:50)     [GCC  4.6.3]  on  linux2   Type  "help",  "copyright",  "credits"  or   "license"  for  more  information.   >>>

Slide 5

Slide 5 text

Practice: Arithmetic • 4  -­‐  2  *  5   • 40  /  (7  -­‐  3)  *  2   • 2  **  3   • 3  /  2   •   2 3 + 64 + ( 2) ÷ ( 50)

Slide 6

Slide 6 text

>>>  3  /  2   鸍剙⽩⳿➊랁

Slide 7

Slide 7 text

Numbers • int • float • bool • True, False • complex • 1  +  2j

Slide 8

Slide 8 text

>>>  a  =  3   >>>  b  =  2   >>>  c  =  3.0   >>>  a  /  b          #  Integer  division.   1   >>>  c  /  b          #  Auto  up-­‐casting.   1.5 Mind your types!

Slide 9

Slide 9 text

Best Practice >>>  a  /  float(b)        #  Always  works.   1.5   >>>  a  //  b                    #  Always  works.   1   >>>  c  //  b                    #  Still  works.   1.0

Slide 10

Slide 10 text

Basic Operators +   -­‐   *   /   % <<   >>   **   //   &   |   ^   ~  

Slide 11

Slide 11 text

Basic Operators >   <   ==   is   and   or   not   >=   <=   !=   <>  

Slide 12

Slide 12 text

#  I  can  write  anything  here,  as   #  long  as  each  line  begins  with   #  a  hash  (#)  symbol.   #  The  following  line  will  be  run.   1  +  1   ex0.py

Slide 13

Slide 13 text

$  python  ex0.py   $ ???

Slide 14

Slide 14 text

#  I  can  write  anything  here,  as   #  long  as  each  line  begins  with   #  a  hash  (#)  symbol.   #  The  following  line  will  be  run.   print(1  +  1)   ex0.py

Slide 15

Slide 15 text

$  python  ex0.py   2   $

Slide 16

Slide 16 text

Variables • Assignment is declaration • Describes values • Aliasing (pointers)

Slide 17

Slide 17 text

ramen  =  200   beer  =  90   meal_price  =  ramen  +  beer   total_price  =  meal_price  *  1.1   print(total_price) ex1.py

Slide 18

Slide 18 text

Type System • Strong typing • Dynamic typing • Duck typing • Not inferred

Slide 19

Slide 19 text

ramen  =  200   beer  =  90   meal_price  =  ramen  +  beer   total_price  =  meal_price  *  1.1   print(total) What Happens?

Slide 20

Slide 20 text

$  python  ex1.py   Traceback  (most  recent  call  last):      File  "ex1.py",  line  7,  in            print(total)   NameError:  name  'total'  is  not  defined

Slide 21

Slide 21 text

Errors • Happen when the program runs • This is dangerous and fragile! • Just need to be careful • Errors are not fatal • Except SyntaxError and IndentationError

Slide 22

Slide 22 text

ramen  =  200   beer  =  90   meal_price  =  ramen  +  beer   total_price  =  meal_price  *  1.1   print(total_price)   ex1.py

Slide 23

Slide 23 text

$  python  ex1.py   319.0   $

Slide 24

Slide 24 text

ramen  =  200   beer  =  95   meal_price  =  ramen  +  beer   total_price  =  meal_price  *  1.1   to_pay  =  int(total_price)   print(to_pay) ex1.py

Slide 25

Slide 25 text

$  python  ex1.py   319   $

Slide 26

Slide 26 text

str • Represents text • Character = string of length 1 • No “char” type • Basic arithmetics

Slide 27

Slide 27 text

'This  is  a  string  literal.'   "This  is  also  a  string  literal."   "I'm  feeling  lucky."   'And  he  said:  "Hello,  Python!"'   "She\'s  like  \"There\'s  no  way!\""

Slide 28

Slide 28 text

poem  =  ('Roses  are  red,\n'                  'Violets  are  blue,')   poem  +=  '''   Sugar  is  sweet,   And  so  are  you.   '''   message  =  '\u6211  \u611b  \u4f60'   print(poem)   print(message)

Slide 29

Slide 29 text

fruit  =  'Apple'   print(fruit[0])   print(fruit[1])   print(fruit[-­‐1])   ex2.py

Slide 30

Slide 30 text

fruit  =  'Apple'   print(fruit[0])   print(fruit[1])   print(fruit[-­‐1])   print(fruit[10]) ex2.py

Slide 31

Slide 31 text

$  python  ex2.py   A   p   e   Traceback  (most  recent  call  last):      File  "ex2.py",  line  7,  in            print(fruit[10])   IndexError:  string  index  out  of  range

Slide 32

Slide 32 text

fruit  =  'Apple'   print(fruit[0])   print(fruit[1])   print(fruit[-­‐1])   print(fruit[:3]) ex2.py

Slide 33

Slide 33 text

Slicing • [start]:[end][:step]   • 'Python'[0:5:1]   • 'Python'[:5]   • 'Python'[-­‐2:]   • 'Python'[::2]

Slide 34

Slide 34 text

Slicing • 'Python'[0:5:1]   • 'Python'[:5]   • 'Python'[-­‐2:]   • 'Python'[::2] 'Pytho'   'Pytho'   'on'   'Pto'

Slide 35

Slide 35 text

name  =  'Python'   greeting  =  'Hello  '  +  name   print(greeting)   print(('How  old  are  you?\n')  *  3)   ex3.py

Slide 36

Slide 36 text

name  =  'Python'   greeting  =  'Hello  '  +  name   print(greeting)   print(('How  old  are  you?\n')  *  3)   age  =  24   print("I'm  "  +  age  +  '  years  old.') ex3.py

Slide 37

Slide 37 text

$  python  ex3.py   Hello  Python   How  old  are  you?   How  old  are  you?   How  old  are  you?   Traceback  (most  recent  call  last):      File  "ext3.py",  line  8,  in            print("I'm  "  +  age  +  '  years  old.')   TypeError:  cannot  concatenate  'str'  and   'int'  objects

Slide 38

Slide 38 text

name  =  'Python'   greeting  =  'Hello  '  +  name   print(greeting)   print(('How  old  are  you?\n')  *  3)   age  =  24   print("I'm  "  +  str(age)  +  '  years  old.') ex3.py

Slide 39

Slide 39 text

str • Represents text • Character = string of length 1 • No “char” type • Basic arithmetics • Immutable

Slide 40

Slide 40 text

>>>  intro  =  'My  name  is  Tim.'   >>>  print(intro)   My  name  is  Tim.   >>>  print(intro[12])   i   >>>  intro[12]  =  'o'   Traceback  (most  recent  call  last):      File  "",  line  1,  in     TypeError:  'str'  object  does  not  support   item  assignment

Slide 41

Slide 41 text

>>>  intro  =  'My  name  is  Tim.'   >>>  print(intro)   My  name  is  Tim.   >>>  print(intro[12])   i   >>>  intro2  =  intro[:12]  +  'o'  +  intro[13:]   >>>  print(intro2)   My  name  is  Tom.  

Slide 42

Slide 42 text

• b'Byte  literal'   • u'Unicode  literal'   • r'Raw  string  literal'   • '''Multiline
 string'''   • """Another  multiline
 string"""

Slide 43

Slide 43 text

$  python  tip_calc.py   Meal  price:  $290   Please  pay:  $319 Practice: Tip Calculator

Slide 44

Slide 44 text

ramen  =  200   beer  =  95   meal_price  =  ramen  +  beer   print('Meal  price:  '  +  str(meal_price))   total_price  =  meal_price  *  1.1   to_pay  =  int(total_price)   print('Please  pay:  '  +  str(to_pay)) tip_calc.py

Slide 45

Slide 45 text

Built-in Functions • You can print() anything • len() calculates the length • raw_input() asks questions https://docs.python.org/3/library/functions.html

Slide 46

Slide 46 text

name  =  raw_input('What  is  your  name?  ')   name_length  =  len(name)   print('Hello  '  +  name  +  '!')   print('Your  name  is  '              +  str(name_length)              +  '  characters  long.') ex4.py

Slide 47

Slide 47 text

$  python  accountant1.py   What  to  buy:  Apple   Price:  10   Item:    Apple   Price:  10 Practice: Accountant (1)

Slide 48

Slide 48 text

name  =  raw_input('What  to  buy:  ')   price  =  raw_input('Price:  ')   print('Item:    '  +  name)   print('Price:  '  +  price) accountant1.py

Slide 49

Slide 49 text

Common String Methods • decode()   • encode()   • find()   • format()   • isalnum() • isalpha()   • isdigit()   • join()   • lower()   • partition() • replace()   • split()   • startswith()   • strip()   • upper() https://docs.python.org/3/library/stdtypes.html#string-methods

Slide 50

Slide 50 text

name  =  raw_input('What  is  your  name?  ')   name_length  =  len(name)   response_template  =  (          'Hello  {name}!\nYour  name  is  '          '{length}  characters  long.'   )   print(response_template.format(          name=name,  length=name_length,   )) ex4.py

Slide 51

Slide 51 text

$  python  ex4.py   What  is  your  name?  pi   Hello  pi!   Your  name  is  2  characters  long.

Slide 52

Slide 52 text

String Formation • '{}  {}'.format(10,  11) • '{n:3d}'.format(n=10)   • '{x:<5}'.format(x='Mo') '10  11'   '  10'   'Mo      ' https://docs.python.org/3/library/string.html#formatstrings

Slide 53

Slide 53 text

$  python  accountant.py   What  to  buy:  Apples   Price:  10   Item                                Price             -­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐   Apples                                  10 Practice: Accountant (2) 20 5

Slide 54

Slide 54 text

item  =  raw_input('What  to  buy:  ')   price  =  raw_input('Price:  ')   print('{name:20}{price:>5}'.format(          name='Item',  price='Price',   ))   print('-­‐'  *  25)   print('{name:20}{price:>5}'.format(          name=item,  price=price,   )) accountant2.py

Slide 55

Slide 55 text

Documentation • https://docs.python.org/3/ • help()

Slide 56

Slide 56 text

https://docs.python.org/3/library/functions.html#print

Slide 57

Slide 57 text

Classes and Objects • Classes describe things • Objects are instances of a thing • Everything is an object in Python

Slide 58

Slide 58 text

Common Built-in Classes • Numbers • str • Errors • tuple • list • dict Sequences Also a sequence

Slide 59

Slide 59 text

tuple • A group of things with ordering • Immutable • Indexing and slicing • IndexError • Arithmetics • Built-in sorted() function

Slide 60

Slide 60 text

list • A group of things with ordering • Mutable • Similar to tuple (but different!) • insert() and append() • In-place sort()

Slide 61

Slide 61 text

dict • Unordered key-value pairs • Hash map • KeyError • keys(), values(), and items()

Slide 62

Slide 62 text

set • Unordered group of things • Immutable variant: frozenset • add() and remove() • Special arithmetics

Slide 63

Slide 63 text

#  A  tuple.   date_parts  =  (2015,  05,  31)   #  A  list.   names  =  ['Travis',  'Lucas',  'Daniel']   #  A  dict.   info  =  {'name':  'TP',  'nation':  'Taiwan'}   #  A  set.   people  =  {'Matt',  'Zack',  'Jacob',  'Noah'}

Slide 64

Slide 64 text

#  Not  a  tuple!   site  =  ('http://tw.pycon.org')   #  This  is  a  tuple.   site  =  ('http://tw.pycon.org',)   #  This  is  a  list.   people  =  ['Michael',  'Juan',  'Curtis']   #  Trailing  commas  are  fine.   people  =  ['Michael',  'Juan',  'Curtis',]

Slide 65

Slide 65 text

empty_tuple  =  ()   empty_list  =  []   empty_dict  =  {}   #  No  way  to  write  a  literal  empty  set.   #  This  works.   empty_set  =  set()

Slide 66

Slide 66 text

Sequences • Can be heterogeneous • Iterable • len() • del  obj[key]

Slide 67

Slide 67 text

names  =  ['Travis',  'Lucas',  'Daniel']   #  Append  an  item  at  the  end.   names.append('Wilmer')   #  Insert  an  item  at  a  certain  index.   names.insert(0,  'Ruben')   #  Remove  first  occurrence  of  an  item.   names.remove('Travis')   #  Remove  by  index.   del  names[3]

Slide 68

Slide 68 text

info  =  {'name':  'TP',  'nation':  'Taiwan'}   #  Add  an  item.   info['location']  =  'Taipei'   #  Update  an  existing  item.   info['name']  =  'Mosky'   #  Remove  an  item.   del  info['location']   #  Check  whether  an  item  is  in  the  dict.   del  names[3]

Slide 69

Slide 69 text

people  =  {'Matt',  'Zack',  'Jacob',  'Noah'}   #  Add  an  item.   people.add('Steven')   #  Remove  an  item.   people.remove('Zack')   #  Duplicates  are  discarded.   #  This  does  nothing.   people.add('Matt')

Slide 70

Slide 70 text

Loops cities  =  [          'Taipei',  'Xinbei',  'Taichung',            'Tainan',  'Kaohsiung',   ]   for  city  in  cities:          print('{}  City'.format(city)) 㔋⦐瑠涯

Slide 71

Slide 71 text

But How Do I…? $  python  loop_five.py   0   1   2   3   4  

Slide 72

Slide 72 text

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

Slide 73

Slide 73 text

for  i  in  range(5):          print(i)

Slide 74

Slide 74 text

range() • Takes up to three arguments • range(end)   • range(start,  end)   • range(start,  end,  step)

Slide 75

Slide 75 text

for  i  in  range(4,  -­‐1,  -­‐1):          print(i) for  (int  i  =  4;  i  >  -­‐1;  i-­‐-­‐)  {          printf("%d",  i);   } C-like Python

Slide 76

Slide 76 text

Bad!! cities  =  [          'Taipei',  'Xinbei',  'Taichung',            'Tainan',  'Kaohsiung',   ]   for  i  in  range(len(cities)):          city  =  cities[i]          print('{}  City'.format(city))

Slide 77

Slide 77 text

dataset  =  {          'uid':  5,          'name':  'Battambang',          'temperature':  31.5,          'coordinates':  (104.756,  11.028),   }   for  key  in  dataset:          print('{key}:  {val}'.format(                  key=key,  val=dataset[key],          ))

Slide 78

Slide 78 text

$  python  accountant3.py   What  to  buy:  Apples   Price:  10   Enter  'y'  to  continue:  y   What  to  buy:  Oranges   Price:  8   Enter  'y'  to  continue:   Item                                Price   -­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐   Apples                                  10   Oranges                                  8

Slide 79

Slide 79 text

flag  =  'y'   items  =  []   while  flag  ==  'y':          name  =  raw_input('What  to  buy:  ')          price  =  raw_input('Price:  ')          items.append({'name':  name,  'price':  price})          flag  =  raw_input("Enter  'y'  to  continue:  ") accountant3.py (1/2)

Slide 80

Slide 80 text

#  Header.   print('{name:20}{price:<5}'.format(          name='Item',  price='Price',   ))   print('-­‐'  *  25)   #  Contents.   for  item  in  items:          print('{name:20}{price:<5}'.format(                  name=item['name'],                    price=item['price'],          )) accountant3.py (2/2)

Slide 81

Slide 81 text

Flow Control if  2  >  5:          print('2  >  5')   elif  2  <  5:          print('2  <  5')   else:          print('2  ==  5')

Slide 82

Slide 82 text

What is False? • False • 0 and 0.0 • None • Empty containers • Empty strings

Slide 83

Slide 83 text

if  i  !=  0:          print('i  =  {}'.format(i)) if  i:          print('i  =  {}'.format(i)) Good Bad

Slide 84

Slide 84 text

if  i  !=  None:          print('i  =  {}'.format(i)) if  i  is  not  None:          print('i  =  {}'.format(i)) Good Bad

Slide 85

Slide 85 text

$  python  accountant4.py   What  to  buy:  Apples   Price:  10   What  to  buy:  Oranges   Price:  8   What  to  buy:   Item                                Price   -­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐   Apples                                  10   Oranges                                  8

Slide 86

Slide 86 text

items  =  []   while  True:          name  =  raw_input('What  to  buy:  ')          price  =  raw_input('Price:  ')          if  not  name  or  not  price:                  break          items.append({'name':  name,  'price':  price}) accountant4.py (1/2)

Slide 87

Slide 87 text

Building Blocks • Variable • Function • Class

Slide 88

Slide 88 text

def  hi():          print('Hi  there!')          print('How  are  you?')   hi() $  python  my_program.py   Hi  there!   How  are  you?

Slide 89

Slide 89 text

def  hi(name):          print('Hi'  +  name  +'!')          print('How  are  you?')   hi()

Slide 90

Slide 90 text

$  python  my_program.py   Traceback  (most  recent  call  last):   File  "my_program.py",  line  4,  in        hi()   TypeError:  hi()  missing  1  required   positional  argument:  'name'

Slide 91

Slide 91 text

def  hi(name):          print('Hi'  +  name  +'!')          print('How  are  you?')   hi('Pusheen') $  python  my_program.py   Hi  Pusheen!   How  are  you?

Slide 92

Slide 92 text

items  =  []   while  True:          name  =  raw_input('What  to  buy:  ')          price  =  raw_input('Price:  ')          if  not  name  or  not  price:                  break          items.append({'name':  name,  'price':  price})   print_header()   print_items(items)

Slide 93

Slide 93 text

def  print_header():          print('{name:20}{price:<5}'.format(                  name='Item',  price='Price',          ))          print('-­‐'  *  25)   def  print_items(items):          for  item  in  items:                  print('{name:20}{price:<5}'.format(                          name=item['name'],                            price=item['price'],                  ))

Slide 94

Slide 94 text

Error Handling numbers  =  [18,  20,  24,  16,  25]   i  =  raw_input('Select  an  index:  ')   try:          number  =  numbers[int(i)]   except  IndexError:          print('No  such  index!')   else:          print('numbers[{}]  =  {}'.format(                  i,  number,          ))

Slide 95

Slide 95 text

try:          do_something_that_might_error()   except  SeriousError:          print('Oh  no!')   except  (ThisError,  ThatError)  as  e:          print('There  was  an  error:',  e)   else:          print('It  works!')   finally:          print('All  done.')

Slide 96

Slide 96 text

try:          do_something_that_might_error()   except  (ThisError,  ThatError)  as  e:          print('Error:  {}'.format(e))   #  Both  else  and  finally  blocks  can   #  be  omitted  if  you  don't  need  them.   print('Done!')

Slide 97

Slide 97 text

Common Exceptions • IndexError • KeyError • ValueError • TypeError • NameError • AttributeError • OSError • RuntimeError https://docs.python.org/3/library/exceptions.html

Slide 98

Slide 98 text

Raising Errors def  ask_for_name():          name  =  raw_input('Give  me  a  name:  ')          if  not  name:                  raise  ValueError          return  name   try:          name  =  ask_for_name()   except  ValueError:          print('No  valid  name!')   else:          print('The  name  is  {}'.format(name))

Slide 99

Slide 99 text

items  =  []   while  True:          try:                  item  =  get_item()          except  ValueError:                  break          items.append(item)   print_header()   print_items(items)

Slide 100

Slide 100 text

def  get_item():          name  =  raw_input('What  to  buy:  ')          price  =  raw_input('Price:  ')          if  not  name  or  not  price:                  raise  ValueError          item  =  {'name':  name,  'price':  price}          return  item

Slide 101

Slide 101 text

Modules import  os   import  sys   print(os.getcwd())   #  /home/pi   print(sys.platform)   #  linux2

Slide 102

Slide 102 text

from  time  import  sleep   for  i  in  range(5):          print(i)          sleep(1)   print('Done!')

Slide 103

Slide 103 text

Style Guide • PEP 8 • Zen of Python • import  this • But… why?

Slide 104

Slide 104 text

www.python.org/dev/ peps/pep-0008

Slide 105

Slide 105 text

www.python.org/dev/ peps/pep-0020