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.
>>>
$ 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
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
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.
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
$ python 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 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))
$ 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)
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()
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!')
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))
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