Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Learn Python, the Right Way

Learn Python, the Right Way

Python Introduction for tutorial track at PyCon APAC 2015. Should be used in conjunction with the Learn Python, the Right Way (Workshop) presentation.

(Contact me if you’re interested in using this for your presentation. The source of the presentation contains some extra useful notes.)

Tzu-ping Chung

May 31, 2015
Tweet

More Decks by Tzu-ping Chung

Other Decks in Programming

Transcript

  1. Prerequisites • Python 3.4 installation • An editor • Proper

    editor settings • Tab = 4 spaces • Save as UTF-8
  2. C:\Users\Tzu-­‐ping  Chung>python3   Python  3.4.1  (v3.4.1:c0e311e010fc,  May  18   2014,

     10:38:22)  [MSC  v.1600  32  bit  (Intel)]   on  win32   Type  "help",  "copyright",  "credits"  or   "license"  for  more  information.   >>>
  3. uranusjr@ubuntu:~$  python3   Python  3.4.0  (default,  Apr  11  2014,  13:05:11)

        [GCC  4.8.2]  on  linux   Type  "help",  "copyright",  "credits"  or   "license"  for  more  information.   >>>  
  4. uranusjr:~  uranusjr$  python3   Python  3.4.1  (default,  Aug  24  2014,

     21:32:40)     [GCC  4.2.1  Compatible  Apple  LLVM  5.1   (clang-­‐503.0.40)]  on  darwin   Type  "help",  "copyright",  "credits"  or   "license"  for  more  information.   >>>
  5. Practice: Arithmetic • 4  -­‐  2  *  5   •

    40  /  (7  -­‐  3)  *  2   • 2  **  3   • 3  /  2   •   2 3 + 64 + ( 2) ÷ ( 50)
  6. >>>  3  /  2          #  "True"

     division.   1.5   >>>  3  //  2        #  Integer  division.   1
  7. Basic Operators +   -­‐   *   /  

    % <<   >>   **   //   &   |   ^   ~  
  8. Basic Operators >   <   ==   is  

    and   or   not   >=   <=   !=   <>  
  9. #  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
  10. #  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
  11. ramen  =  200   beer  =  90   meal_price  =

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

     ramen  +  beer   total_price  =  meal_price  *  1.1   print(total) What Happens?
  13. $  python3  ex1.py   Traceback  (most  recent  call  last):  

       File  "ex1.py",  line  7,  in  <module>          print(total)   NameError:  name  'total'  is  not  defined
  14. Errors • Happen when the program runs • This is

    dangerous and fragile! • Just need to be careful • Errors are not fatal • Except SyntaxError and IndentationError
  15. ramen  =  200   beer  =  90   meal_price  =

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

     ramen  +  beer   total_price  =  meal_price  *  1.1   to_pay  =  int(total_price)   print(to_pay) ex1.py
  17. str • Represents text • Sequence of Unicode code points

    • No “char” type • Basic arithmetics
  18. '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!\""
  19. poem  =  ('Roses  are  red,\n'          

           'Violets  are  blue,')   poem  +=  '''   Sugar  is  sweet,   And  so  are  you.   '''   message  =  '\u6211  \u611b  \u4f60'   print(poem)   print(message)
  20. $  python3  ex2.py   A   p   e  

    Traceback  (most  recent  call  last):      File  "ex2.py",  line  7,  in  <module>          print(fruit[10])   IndexError:  string  index  out  of  range
  21. Slicing • 'Python'[0:5:1]   • 'Python'[:5]   • 'Python'[-­‐2:]  

    • 'Python'[::2] 'Pytho'   'Pytho'   'on'   'Pto'
  22. name  =  'Python'   greeting  =  'Hello  '  +  name

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

      print(greeting)   print(('How  old  are  you?\n')  *  3)   age  =  24   print("I'm  "  +  age  +  '  years  old.') ex3.py
  24. $  python3  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  <module>          print("I'm  "  +  age  +  '  years  old.')   TypeError:  cannot  concatenate  'str'  and   'int'  objects
  25. 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
  26. str • Represents text • Sequence of Unicode code points

    • No “char” type • Basic arithmetics • Immutable
  27. >>>  intro  =  'My  name  is  Tim.'   >>>  print(intro)

      My  name  is  Tim.   >>>  print(intro[12])   i   >>>  intro[12]  =  'o'   Traceback  (most  recent  call  last):      File  "<stdin>",  line  1,  in  <module>   TypeError:  'str'  object  does  not  support   item  assignment
  28. >>>  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.  
  29. • b'Byte  literal'   • u'Unicode  literal'   • r'Raw

     string  literal'   • '''Multiline
 string'''   • """Another  multiline
 string"""
  30. 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
  31. Built-in Functions • You can print() anything • len() calculates

    the length • input() asks questions https://docs.python.org/3/library/functions.html
  32. name  =  input('What  is  your  name?  ')   name_length  =

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

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

     len(name)   print('Hello  '  +  name  +  '!')   print('Your  name  is',  end='  ')   print(name_length,  end='  ')   print('characters',  'long.',  sep='  ') ex4.py
  35. $  python3  accountant1.py   What  to  buy:  Apple   Price:

     10   Item:    Apple   Price:  10 Practice: Accountant (1)
  36. name  =  input('What  to  buy:  ')   price  =  input('Price:

     ')   print('Item:    '  +  name)   print('Price:  '  +  price) accountant1.py
  37. 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
  38. name  =  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
  39. $  python3  ex4.py   What  is  your  name?  TP  

    Hello  TP!   Your  name  is  2  characters  long.
  40. 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
  41. $  python3  accountant.py   What  to  buy:  Apples   Price:

     10   Item                                Price             -­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐   Apples                                  10 Practice: Accountant (2) 20 5
  42. item  =  input('What  to  buy:  ')   price  =  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
  43. Classes and Objects • Classes describe things • Objects are

    instances of a thing • Everything is an object in Python
  44. Common Built-in Classes • Numbers • str • Errors •

    tuple • list • dict Sequences Also a sequence
  45. tuple • A group of things with ordering • Immutable

    • Indexing and slicing • IndexError • Arithmetics • Built-in sorted() function
  46. list • A group of things with ordering • Mutable

    • Similar to tuple (but different!) • insert() and append() • In-place sort()
  47. set • Unordered group of things • Immutable variant: frozenset

    • add() and remove() • Special arithmetics
  48. #  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'}
  49. #  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',]
  50. empty_tuple  =  ()   empty_list  =  []   empty_dict  =

     {}   #  No  way  to  write  a  literal  empty  set.   #  This  works.   empty_set  =  set()
  51. Loops cities  =  [          'Taipei',  'Xinbei',

     'Taichung',            'Tainan',  'Kaohsiung',   ]   for  city  in  cities:          print('{}  City'.format(city)) 㔋⦐瑠涯
  52. i  =  0   while  i  <  5:    

         print(i)          i  +=  1
  53. range() • Takes up to three arguments • range(end)  

    • range(start,  end)   • range(start,  end,  step)
  54. for  i  in  range(4,  -­‐1,  -­‐1):        

     print(i) for  (int  i  =  4;  i  >  -­‐1;  i-­‐-­‐)  {          printf("%d",  i);   } C-like Python
  55. Bad!! cities  =  [          'Taipei',  'Xinbei',

     'Taichung',            'Tainan',  'Kaohsiung',   ]   for  i  in  range(len(cities)):          city  =  cities[i]          print('{}  City'.format(city))
  56. 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],          ))
  57. dataset  =  {          'uid':  5,  

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

           'name':  'Battambang',          'temperature':  31.5,          'coordinates':  (104.756,  11.028),   }   for  key,  value  in  dataset.items():          print('{key}:  {val}'.format(                  key=key,  val=value,          )) Auto unpacking
  59. Auto Unpacking coordinates  =  (104.756,  11.028)   lng,  lat  =

     coodinates   print('Longitude:  ',  lng)   print('Latitude:    ',  lat)
  60. students  =  [...]      #  A  lot  of  students.

      #  `others`  will  contain  all  students   #  except  the  first  and  last.   first,  *others,  last  =  students   #  Kind  of  equivalent,  but  not  as  good.   first  =  students[0]   last  =  students[-­‐1]   others  =  students[1:-­‐1]
  61. $  python3  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
  62. flag  =  'y'   items  =  []   while  flag

     ==  'y':          name  =  input('What  to  buy:  ')          price  =  input('Price:  ')          items.append({'name':  name,  'price':  price})          flag  =  input("Enter  'y'  to  continue:  ") accountant3.py (1/2)
  63. #  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)
  64. Flow Control if  2  >  5:        

     print('2  >  5')   elif  2  <  5:          print('2  <  5')   else:          print('2  ==  5')
  65. What is False? • False • 0 and 0.0 •

    None • Empty containers • Empty strings
  66. if  i  !=  0:          print('i  =

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

     {}'.format(i)) if  i  is  not  None:          print('i  =  {}'.format(i)) Good Bad
  68. $  python3  accountant4.py   What  to  buy:  Apples   Price:

     10   What  to  buy:  Oranges   Price:  8   What  to  buy:   Item                                Price   -­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐-­‐   Apples                                  10   Oranges                                  8
  69. items  =  []   while  True:        

     name  =  input('What  to  buy:  ')          price  =  input('Price:  ')          if  not  name  or  not  price:                  break          items.append({'name':  name,  'price':  price}) accountant4.py (1/2)
  70. def  hi():          print('Hi  there!')    

         print('How  are  you?')   hi() $  python3  my_program.py   Hi  there!   How  are  you?
  71. def  hi(name):          print('Hi'  +  name  +'!')

             print('How  are  you?')   hi()
  72. $  python3  my_program.py   Traceback  (most  recent  call  last):  

    File  "my_program.py",  line  4,  in        hi()   TypeError:  hi()  missing  1  required   positional  argument:  'name'
  73. def  hi(name):          print('Hi'  +  name  +'!')

             print('How  are  you?')   hi('Pusheen') $  python3  my_program.py   Hi  Pusheen!   How  are  you?
  74. class  Cat:          def  meow(self):    

                 print('Meow!')  
  75. class  Cat:          def  meow(self):    

                 print('Meow!')   pusheen  =  Cat()   pusheen.meow() $  python3  cat.py   Meow!
  76. class  Cat:          def  __init__(self,  name):  

                   self.name  =  name          def  meow(self):                  print(self.name  +  '  Meow!')   pusheen  =  Cat()   pusheen.meow()
  77. $  python3  cat.py   Traceback  (most  recent  call  last):  

       File  "cat.py",  line  8,  in            pusheen  =  Cat()   TypeError:  __init__()  missing  1  required   positional  argument:  'name'
  78. class  Cat:          def  __init__(self,  name):  

                   self.name  =  name          def  meow(self):                  print(self.name  +  '  Meow!')   pusheen  =  Cat()   pusheen.meow()  
  79. class  Cat:          def  __init__(self,  name):  

                   self.name  =  name          def  meow(self):                  print(self.name  +  '  Meow!')   pusheen  =  Cat('Pusheen')   pusheen.meow()   $  python3  cat.py   Pusheen  Meow!  
  80. class  Cat:          def  __init__(self,  name):  

                   self.name  =  name          def  meow(self):                  print(self.name  +  '  Meow!')   pusheen  =  Cat('Pusheen')   pusheen.meow()   print(pusheen) $  python3  cat.py   Pusheen  Meow!   <__main__.Cat  object  at  0x1006f15c0>
  81. class  Cat:          def  __init__(self,  name):  

                   self.name  =  name          def  __str__(self):                  return  'Cat:  '  +  self.name          def  meow(self):                  print(self.name  +  '  Meow!')   pusheen  =  Cat('Pusheen')   pusheen.meow()   print(pusheen)
  82. class  PetCat(Pet,  Animal):          """A  pet  cat

     that  can  meow.          """          sound  =  'meow'          def  __init__(self,  name):                  super().__init__(name)          def  make_sound(self):                  print(self.name,  self.sound)          def  meow(self):                  self.make_sound()
  83. Error Handling numbers  =  [18,  20,  24,  16,  25]  

    i  =  input('Select  an  index:  ')   try:          number  =  numbers[i]   except  IndexError:          print('No  such  index!')   else:          print('numbers[{}]  =  {}'.format(                  i,  number,          ))
  84. 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.')
  85. try:          do_something_that_might_error()   except  (ThisError,  ThatError)

     as  e:          print('Error:',  e)   #  Both  else  and  finally  blocks  can   #  be  omitted  if  you  don't  need  them.   print('Done!')
  86. Common Exceptions • IndexError • KeyError • ValueError • TypeError

    • NameError • AttributeError • OSError • RuntimeError https://docs.python.org/3/library/exceptions.html
  87. Style Guide • PEP 8 • Zen of Python •

    import  this • But… why?
  88. Finishing Words • Where and how to ask questions •

    Recommended Reading • Practicing