Prerequisites
• Python 3.4 installation
• An editor
• Proper editor settings
• Tab = 4 spaces
• Save as UTF-8
Slide 9
Slide 9 text
Questions
• Command line knowledge?
• Familiarity with the editor?
• Programming experience?
Slide 10
Slide 10 text
Installation
http://d.pr/1jo9x
Slide 11
Slide 11 text
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.
>>>
Slide 12
Slide 12 text
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.
>>>
Slide 13
Slide 13 text
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.
>>>
Slide 14
Slide 14 text
Interactive Shell
• Interpreter talks with you
• Good for experiments
• Ways to exit
$ python3 ex1.py
Traceback (most recent call last):
File "ex1.py", line 7, in
print(total)
NameError: name 'total' is not defined
Slide 29
Slide 29 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
str
• Represents text
• Sequence of Unicode code points
• No “char” type
• Basic arithmetics
Slide 35
Slide 35 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 36
Slide 36 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 37
Slide 37 text
fruit = 'Apple'
print(fruit[0])
print(fruit[1])
print(fruit[-‐1])
ex2.py
Slide 38
Slide 38 text
fruit = 'Apple'
print(fruit[0])
print(fruit[1])
print(fruit[-‐1])
print(fruit[10])
ex2.py
Slide 39
Slide 39 text
$ python3 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 40
Slide 40 text
fruit = 'Apple'
print(fruit[0])
print(fruit[1])
print(fruit[-‐1])
print(fruit[:3])
ex2.py
name = 'Python'
greeting = 'Hello ' + name
print(greeting)
print(('How old are you?\n') * 3)
ex3.py
Slide 44
Slide 44 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 45
Slide 45 text
$ 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
print("I'm " + age + ' years old.')
TypeError: cannot concatenate 'str' and
'int' objects
Slide 46
Slide 46 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 47
Slide 47 text
str
• Represents text
• Sequence of Unicode code points
• No “char” type
• Basic arithmetics
• Immutable
Slide 48
Slide 48 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 49
Slide 49 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.
Built-in Functions
• You can print() anything
• len() calculates the length
• input() asks questions
https://docs.python.org/3/library/functions.html
Slide 54
Slide 54 text
name = input('What is your name? ')
name_length = len(name)
print('Hello ' + name + '!')
print('Your name is '
+ str(name_length)
+ ' characters long.')
ex4.py
Slide 55
Slide 55 text
name = input('What is your name? ')
name_length = len(name)
print('Hello ' + name + '!')
print('Your name is', name_length,
'characters long.')
ex4.py
Slide 56
Slide 56 text
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
Slide 57
Slide 57 text
print()
Slide 58
Slide 58 text
$ python3 accountant1.py
What to buy: Apple
Price: 10
Item: Apple
Price: 10
Practice: Accountant (1)
Slide 59
Slide 59 text
name = input('What to buy: ')
price = input('Price: ')
print('Item: ' + name)
print('Price: ' + price)
accountant1.py
$ python3 accountant.py
What to buy: Apples
Price: 10
Item Price
-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐
Apples 10
Practice: Accountant (2)
20 5
set
• Unordered group of things
• Immutable variant: frozenset
• add() and remove()
• Special arithmetics
Slide 74
Slide 74 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 75
Slide 75 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 76
Slide 76 text
empty_tuple = ()
empty_list = []
empty_dict = {}
# No way to write a literal empty set.
# This works.
empty_set = set()
Slide 77
Slide 77 text
Sequences
• Can be heterogeneous
• Iterable
• len()
• del obj[key]
Slide 78
Slide 78 text
Loops
cities = [
'Taipei', 'Xinbei', 'Taichung',
'Tainan', 'Kaohsiung',
]
for city in cities:
print('{} City'.format(city))
㔋⦐瑠涯
Slide 79
Slide 79 text
But How Do I…?
$ python3 loop_five.py
0
1
2
3
4
Slide 80
Slide 80 text
i = 0
while i < 5:
print(i)
i += 1
Slide 81
Slide 81 text
for i in range(5):
print(i)
Slide 82
Slide 82 text
range()
• Takes up to three arguments
• range(end)
• range(start, end)
• range(start, end, step)
Slide 83
Slide 83 text
for i in range(4, -‐1, -‐1):
print(i)
for (int i = 4; i > -‐1; i-‐-‐) {
printf("%d", i);
}
C-like
Python
Slide 84
Slide 84 text
Bad!!
cities = [
'Taipei', 'Xinbei', 'Taichung',
'Tainan', 'Kaohsiung',
]
for i in range(len(cities)):
city = cities[i]
print('{} City'.format(city))
dataset = {
'uid': 5,
'name': 'Battambang',
'temperature': 31.5,
'coordinates': (104.756, 11.028),
}
for value in dataset.values():
print('{val}'.format(val=value))
Slide 87
Slide 87 text
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
Slide 88
Slide 88 text
Auto Unpacking
coordinates = (104.756, 11.028)
lng, lat = coodinates
print('Longitude: ', lng)
print('Latitude: ', lat)
Slide 89
Slide 89 text
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]
Slide 90
Slide 90 text
“View” Methods
• keys()
• items()
• values()
• Should I use them?
Slide 91
Slide 91 text
$ 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
Slide 92
Slide 92 text
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)
Flow Control
if 2 > 5:
print('2 > 5')
elif 2 < 5:
print('2 < 5')
else:
print('2 == 5')
Slide 95
Slide 95 text
What is False?
• False
• 0 and 0.0
• None
• Empty containers
• Empty strings
Slide 96
Slide 96 text
if i != 0:
print('i = {}'.format(i))
if i:
print('i = {}'.format(i))
Good
Bad
Slide 97
Slide 97 text
if i != None:
print('i = {}'.format(i))
if i is not None:
print('i = {}'.format(i))
Good
Bad
Slide 98
Slide 98 text
$ python3 accountant4.py
What to buy: Apples
Price: 10
What to buy: Oranges
Price: 8
What to buy:
Item Price
-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐
Apples 10
Oranges 8
Slide 99
Slide 99 text
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)
Slide 100
Slide 100 text
Building Blocks
• Variable
• Function
• Class
Slide 101
Slide 101 text
def hi():
print('Hi there!')
print('How are you?')
hi()
$ python3 my_program.py
Hi there!
How are you?
Slide 102
Slide 102 text
def hi(name):
print('Hi' + name +'!')
print('How are you?')
hi()
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()
Slide 115
Slide 115 text
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,
))
Slide 116
Slide 116 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 117
Slide 117 text
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!')