29 Matching Annotations
  1. Feb 2021
    1. >>> spam = {'color': 'red', 'age': 42} >>> for k, v in spam.items(): ...     print('Key: ' + k + ' Value: ' + str(v))

      THis is better than for i in ,dict.items():

    2. >> spam = {'name': 'Zophie', 'age': 7} >>> spam['color'] Traceback (most recent call last):   File "<pyshell#1>", line 1, in <module>     spam['color'] KeyError: 'color'

      what happens if you access a key that dies not exist. Kinda like out of bounds

    3. >>> eggs = {'name': 'Zophie', 'species': 'cat', 'age': '8'} >>> ham = {'species': 'cat', 'age': '8', 'name': 'Zophie'}

      Let's make a new cat, Elliot tell us about yours Compare them they are not equal

      And then let's make two chickens and see if they are equal. they are!

    4. ➊ birthdays = {'Alice': 'Apr 1', 'Bob': 'Dec 12', 'Carol': 'Mar 4'}    while True:        print('Enter a name: (blank to quit)')        name = input()        if name == '':            break     ➋ if name in birthdays:         ➌ print(birthdays[name] + ' is the birthday of ' + name)        else:            print('I do not have birthday information for ' + name)            print('What is their birthday?')            bday = input()         ➍ birthdays[name] = bday            print('Birthday database updated.')

      Keys are unique. Can't have two Bobs

    5. allGuests = {'Alice': {'apples': 5, 'pretzels': 12},              'Bob': {'ham sandwiches': 3, 'apples': 2},              'Carol': {'cups': 3, 'apple pies': 1}} def totalBrought(guests, item):     numBrought = 0   ➊ for k, v in guests.items():       ➋ numBrought = numBrought + v.get(item, 0)      return numBrought print('Number of things being brought:') print(' - Apples         ' + str(totalBrought(allGuests, 'apples'))) print(' - Cups           ' + str(totalBrought(allGuests, 'cups'))) print(' - Cakes          ' + str(totalBrought(allGuests, 'cakes'))) print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches'))) print(' - Apple Pies     ' + str(totalBrought(allGuests, 'apple pies')))

      This is great but we can refactor this

      Why do we hardcore the key when we print out? Can’t we loop over them and add them to a set?

      Could we count the total number of items?

      Could we count how many items each person brought?

    6. turn = 'X' for i in range(9):   ➊ printBoard(theBoard)      print('Turn for ' + turn + '. Move on which space?')   ➋ move = input()   ➌ theBoard[move] = turn   ➍ if turn == 'X':          turn = 'O'      else:          turn = 'X'  printBoard(theBoard)

      We’re gonna make a two player game

      We have the dictionary Let’s make a function to put a x or o in a spot Pass the cell Id and the x or o in as arguments Then take the arguments and use to add to dict

      So we can do that manually. But how do we handle turns? How about we have a turn counter and we check if it’s even or odd If it’s even we pass in d as argument. Else pass o

      How do we know when to stop? Well we could go for 9 turns. Or let the users enter stop or I won Or we could check the board every time and tell the users

    7. theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',             'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',             'low-L': ' ', 'low-M': ' ', 'low-R': ' '}

      What should we call each cell?

    8. Let’s create a function to print the board dictionary onto the screen

      How do they think the row should be printed?

      Show them how you want a row to be printed

      Then get one person to print a row

      Then print the other rows

      Then wrap it in a function

  2. Jan 2021
    1. myPets = ['Zophie', 'Pooka', 'Fat-tail'] print('Enter a pet name:') name = input() if name not in myPets:     print('I do not have a pet named ' + name) else:     print(name + ' is my pet.')

      Can find the largest

    2. >>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam[1] = 'aardvark' >>> spam ['cat', 'aardvark', 'rat', 'elephant'] >>> spam[2] = spam[1] >>> spam ['cat', 'aardvark', 'aardvark', 'elephant'] >>> spam[-1] = 12345 >>> spam ['cat', 'aardvark', 'aardvark', 12345]

      Maybe an example of ordering a list of names by alphabet or by length of name

      Or just replacing someone in a queue.

      Write with functions

    3. >>> spam = ['cat', 'bat', 'rat', 'elephant'] >>> spam[-1] 'elephant' >>> spam[-3] 'bat'

      Good to get the top level domain of a url. or the last element to get the largest item if already sorted.

    4. >>> spam = ['hello', 'hi', 'howdy', 'heyas'] >>> spam.index('hello') 0 >>> spam.index('heyas') 3 >>> spam.index('howdy howdy howdy')

      You want to find the position of a person in line to determine what place they are

      So maybe world records, looking up their rankings

    5. >>> import random >>> people = ['Alice', 'Bob', 'Carol', 'David'] >>> random.shuffle(people) >>> people ['Carol', 'David', 'Alice', 'Bob'] >>> random.shuffle(people) >>> people ['Alice', 'David', 'Bob', 'Carol']

      Maybe an example here could be make an iPod shuffle that doesn't complete

      Get list of songs then random choice then delete the song then next random choice

    6. catNames = [] while True:     print('Enter the name of cat ' + str(len(catNames) + 1) +       ' (Or enter nothing to stop.):')     name = input()     if name == '':         break     catNames = catNames + [name]  # list concatenation print('The cat names are:') for name in catNames:     print('  ' + name)

      Make list of names and then write function to sort them

    7. >>> spam = [['cat', 'bat'], [10, 20, 30, 40, 50]] >>> spam[0] ['cat', 'bat'] >>> spam[0][1] 'bat' >>> spam[1][4] 50

      Good for mazes and games of checkers and tic tac toe

    8. >>> [1, 2, 3]    [1, 2, 3]    >>> ['cat', 'bat', 'rat', 'elephant']    ['cat', 'bat', 'rat', 'elephant']    >>> ['hello', 3.1415, True, None, 42]

      Lists can all have same type or different types

    1. def spam(divideBy):     try:         return 42 / divideBy     except ZeroDivisionError:         print('Error: Invalid argument.') print(spam(2)) print(spam(12)) print(spam(0)) print(spam(1))

      Maybe show how expected argument is a number but we expected a string

    2. The call stack is how Python remembers where to return the execution after each function call. The call stack isn’t stored in a variable in your program; rather, Python handles it behind the scenes. When your program calls a function, Python creates a frame object on the top of the call stack. Frame objects store the line number of the original function call so that Python can remember where to return. If another function call is made, Python puts another frame object on the call stack above the other one.

      Ask elliot