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

Python Introduction (for Raspberry Pi Course)

Python Introduction (for Raspberry Pi Course)

Tzu-ping Chung

August 20, 2015
Tweet

More Decks by Tzu-ping Chung

Other Decks in Programming

Transcript

  1. Introduction to Python

    View Slide

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

    View Slide

  3. $  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.  
    >>>

    View Slide

  4. $  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.  
    >>>

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  12. #  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

    View Slide

  13. $  python  ex0.py  
    $
    ???

    View Slide

  14. #  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

    View Slide

  15. $  python  ex0.py  
    2  
    $

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  23. $  python  ex1.py  
    319.0  
    $

    View Slide

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

    View Slide

  25. $  python  ex1.py  
    319  
    $

    View Slide

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

    View Slide

  27. '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!\""

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  31. $  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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  37. $  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

    View Slide

  38. 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

    View Slide

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

    View Slide

  40. >>>  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

    View Slide

  41. >>>  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.  

    View Slide

  42. • b'Byte  literal'  
    • u'Unicode  literal'  
    • r'Raw  string  literal'  
    • '''Multiline

    string'''  
    • """Another  multiline

    string"""

    View Slide

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

    View Slide

  44. 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

    View Slide

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

    View Slide

  46. 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

    View Slide

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

    View Slide

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

    View Slide

  49. 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

    View Slide

  50. 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

    View Slide

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

    View Slide

  52. 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

    View Slide

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

    View Slide

  54. 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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  63. #  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'}

    View Slide

  64. #  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',]

    View Slide

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

    View Slide

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

    View Slide

  67. 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]

    View Slide

  68. 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]

    View Slide

  69. 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')

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  77. 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],  
           ))

    View Slide

  78. $  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

    View Slide

  79. 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)

    View Slide

  80. #  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)

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  86. 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)

    View Slide

  87. Building Blocks
    • Variable
    • Function
    • Class

    View Slide

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

    View Slide

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

    View Slide

  90. $  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'

    View Slide

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

    View Slide

  92. 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)

    View Slide

  93. 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'],  
                   ))

    View Slide

  94. 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,  
           ))

    View Slide

  95. 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.')

    View Slide

  96. 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!')

    View Slide

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

    View Slide

  98. 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))

    View Slide

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

    View Slide

  100. 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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide