Tzu-ping Chung
August 20, 2015
150

# Python Introduction (for Raspberry Pi Course)

August 20, 2015

## Transcript

1. Introduction to Python

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

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

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

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

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

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

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

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

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

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

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

13. \$  python  ex0.py
\$
???

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

15. \$  python  ex0.py
2
\$

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

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

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

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

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

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

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

23. \$  python  ex1.py
319.0
\$

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

25. \$  python  ex1.py
319
\$

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

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!\""

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)

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

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

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

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

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

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

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

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

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

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

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

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

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.

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

43. \$  python  tip_calc.py
Meal  price:  \$290
Practice: Tip Calculator

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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'}

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',]

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

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

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]

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]

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

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

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

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

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

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

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

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

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

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

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)

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)

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

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

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

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

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

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)

87. Building Blocks
• Variable
• Function
• Class

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

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

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'

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

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_items(items)

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

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

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

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

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

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

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

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

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

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

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

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

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