Share
Embed
Annual Pro sale · Save $30
Have presentations of your own?
Share with private links, password protection, and more control over your work.
Transcript
105 slides
-
Interactive Shell • Interpreter talks with you • Good for
experiments • The REPL -
$ 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. >>> -
$ 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. >>> -
Practice: Arithmetic • 4 -‐ 2 * 5 •
40 / (7 -‐ 3) * 2 • 2 ** 3 • 3 / 2 • 2 3 + 64 + ( 2) ÷ ( 50) -
Numbers • int • float • bool • True, False
• complex • 1 + 2j -
>>> a = 3 >>> b = 2
>>> c = 3.0 >>> a / b # Integer division. 1 >>> c / b # Auto up-‐casting. 1.5 Mind your types! -
Best Practice >>> a / float(b) #
Always works. 1.5 >>> a // b # Always works. 1 >>> c // b # Still works. 1.0 -
Basic Operators + -‐ * /
% << >> ** // & | ^ ~ -
Basic Operators > < == is
and or not >= <= != <> -
# 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 -
# 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 -
ramen = 200 beer = 90 meal_price =
ramen + beer total_price = meal_price * 1.1 print(total_price) ex1.py -
Type System • Strong typing • Dynamic typing • Duck
typing • Not inferred -
ramen = 200 beer = 90 meal_price =
ramen + beer total_price = meal_price * 1.1 print(total) What Happens? -
$ python ex1.py Traceback (most recent call last):
File "ex1.py", line 7, in <module> print(total) NameError: name 'total' is not defined -
Errors • Happen when the program runs • This is
dangerous and fragile! • Just need to be careful • Errors are not fatal • Except SyntaxError and IndentationError -
ramen = 200 beer = 90 meal_price =
ramen + beer total_price = meal_price * 1.1 print(total_price) ex1.py -
ramen = 200 beer = 95 meal_price =
ramen + beer total_price = meal_price * 1.1 to_pay = int(total_price) print(to_pay) ex1.py -
str • Represents text • Character = string of length
1 • No “char” type • Basic arithmetics -
'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!\"" -
poem = ('Roses are red,\n'
'Violets are blue,') poem += ''' Sugar is sweet, And so are you. ''' message = '\u6211 \u611b \u4f60' print(poem) print(message) -
fruit = 'Apple' print(fruit[0]) print(fruit[1]) print(fruit[-‐1])
print(fruit[10]) ex2.py -
$ python 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 -
fruit = 'Apple' print(fruit[0]) print(fruit[1]) print(fruit[-‐1])
print(fruit[:3]) ex2.py -
Slicing • [start]:[end][:step] • 'Python'[0:5:1] • 'Python'[:5]
• 'Python'[-‐2:] • 'Python'[::2] -
Slicing • 'Python'[0:5:1] • 'Python'[:5] • 'Python'[-‐2:]
• 'Python'[::2] 'Pytho' 'Pytho' 'on' 'Pto' -
name = 'Python' greeting = 'Hello ' + name
print(greeting) print(('How old are you?\n') * 3) ex3.py -
name = 'Python' greeting = 'Hello ' + name
print(greeting) print(('How old are you?\n') * 3) age = 24 print("I'm " + age + ' years old.') ex3.py -
$ 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 <module> print("I'm " + age + ' years old.') TypeError: cannot concatenate 'str' and 'int' objects -
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 -
str • Represents text • Character = string of length
1 • No “char” type • Basic arithmetics • Immutable -
>>> 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 -
>>> 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. -
• b'Byte literal' • u'Unicode literal' • r'Raw
string literal' • '''Multiline string''' • """Another multiline string""" -
$ python tip_calc.py Meal price: $290 Please pay:
$319 Practice: Tip Calculator -
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 -
Built-in Functions • You can print() anything • len() calculates
the length • raw_input() asks questions https://docs.python.org/3/library/functions.html -
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 -
$ python accountant1.py What to buy: Apple Price:
10 Item: Apple Price: 10 Practice: Accountant (1) -
name = raw_input('What to buy: ') price = raw_input('Price:
') print('Item: ' + name) print('Price: ' + price) accountant1.py -
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 -
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 -
$ python ex4.py What is your name? pi
Hello pi! Your name is 2 characters long. -
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 -
$ python accountant.py What to buy: Apples Price:
10 Item Price -‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐ Apples 10 Practice: Accountant (2) 20 5 -
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 -
Classes and Objects • Classes describe things • Objects are
instances of a thing • Everything is an object in Python -
Common Built-in Classes • Numbers • str • Errors •
tuple • list • dict Sequences Also a sequence -
tuple • A group of things with ordering • Immutable
• Indexing and slicing • IndexError • Arithmetics • Built-in sorted() function -
list • A group of things with ordering • Mutable
• Similar to tuple (but different!) • insert() and append() • In-place sort() -
dict • Unordered key-value pairs • Hash map • KeyError
• keys(), values(), and items() -
set • Unordered group of things • Immutable variant: frozenset
• add() and remove() • Special arithmetics -
# 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'} -
# 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',] -
empty_tuple = () empty_list = [] empty_dict =
{} # No way to write a literal empty set. # This works. empty_set = set() -
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] -
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] -
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') -
Loops cities = [ 'Taipei', 'Xinbei',
'Taichung', 'Tainan', 'Kaohsiung', ] for city in cities: print('{} City'.format(city)) 㔋⦐瑠涯 -
i = 0 while i < 5:
print(i) i += 1 -
range() • Takes up to three arguments • range(end)
• range(start, end) • range(start, end, step) -
for i in range(4, -‐1, -‐1):
print(i) for (int i = 4; i > -‐1; i-‐-‐) { printf("%d", i); } C-like Python -
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 key in dataset: print('{key}: {val}'.format( key=key, val=dataset[key], )) -
$ 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 -
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) -
# 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) -
Flow Control if 2 > 5:
print('2 > 5') elif 2 < 5: print('2 < 5') else: print('2 == 5') -
What is False? • False • 0 and 0.0 •
None • Empty containers • Empty strings -
if i != 0: print('i =
{}'.format(i)) if i: print('i = {}'.format(i)) Good Bad -
if i != None: print('i =
{}'.format(i)) if i is not None: print('i = {}'.format(i)) Good Bad -
$ python accountant4.py What to buy: Apples Price:
10 What to buy: Oranges Price: 8 What to buy: Item Price -‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐ Apples 10 Oranges 8 -
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) -
def hi(): print('Hi there!')
print('How are you?') hi() $ python my_program.py Hi there! How are you? -
def hi(name): print('Hi' + name +'!')
print('How are you?') hi() -
$ 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' -
def hi(name): print('Hi' + name +'!')
print('How are you?') hi('Pusheen') $ python my_program.py Hi Pusheen! How are you? -
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) -
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'], )) -
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, )) -
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.') -
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!') -
Common Exceptions • IndexError • KeyError • ValueError • TypeError
• NameError • AttributeError • OSError • RuntimeError https://docs.python.org/3/library/exceptions.html -
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)) -
items = [] while True:
try: item = get_item() except ValueError: break items.append(item) print_header() print_items(items) -
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 -
Modules import os import sys print(os.getcwd()) #
/home/pi print(sys.platform) # linux2 -
from time import sleep for i in range(5):
print(i) sleep(1) print('Done!') -
Style Guide • PEP 8 • Zen of Python •
import this • But… why?