$ 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. >>>
Errors • Happen when the program runs • This is dangerous and fragile! • Just need to be careful • Errors are not fatal • Except SyntaxError and IndentationError
poem = ('Roses are red,\n' 'Violets are blue,') poem += ''' Sugar is sweet, And so are you. ''' message = '\u6211 \u611b \u4f60' print(poem) print(message)
$ 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
>>> 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
>>> 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.
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 accountant.py What to buy: Apples Price: 10 Item Price -‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐-‐ Apples 10 Practice: Accountant (2) 20 5
# 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',]
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')
$ 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)
$ 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)
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)
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