Linguist 278: Programming for Linguists (Stanford Linguistics, Fall 2021)

Class 3: The basics of executing files, homework formatting, dicts, and tuples

Executing Python files

Suppose you've written some code in a text file called foo.py. To run that code, open the terminal and type

python foo.py

This presupposes that the terminal is in the directory containing the file. If it isn't, you can give the full path. For example:

python /Users/cgpotts/Desktop/foo.py

suffices if foo.py is saved on my desktop.

Some notes on homework formatting

There are a bunch of fiddly requirements for homework formatting that I want to explain in a bit more detail (and these are all concepts we will revisit as the quarter goes on):

  1. Please name the homework 1 file ling278_assign01_NAME.py where NAME is a version of your name containing only letters and/or
    underscores. Why? This will allow me to import your file as a Python module. For example, once inside the Python interactive terminal, I could do

    import ling278_assign01_chris_potts
    
    ling278_assign01_chris_potts.mean([1,2,3])
    
  2. Please put all uses of the functions you write – function calls ‐ below (in the scope of if __name__ == '__main__':) at the bottom of the file. You can put anything you want there. That code will be run only if I do

    python ling278_assign01_chris_potts
    

    but not if I do

    import ling278_assign01_chris_potts
    

    Thus, I can test your individual functions without also running any test calls you included. This frees you to write whatever code you want to in that space.

  3. The homework contains functions palindrome_detector_test and csv_parser_test. These will test your palindrome_detector and csv_parser, respectively. Just include

    palindrome_detector_test()
    csv_parser_test()
    

    below if __name__ == '__main__': and keep running things until you get a clean bill of health. And you can write tests for your other functions too. For example,

    def test_mean():
       vals = [1,2,3]
       assert mean(vals) == 2.0
    

    is the start of a good test for your mean function. (You might want to include more cases.)

tuple

  1. Tuples are defined with parentheses: (1, 2, 3), for example.

  2. In essence, you can think of a tuple as a list that is not mutable.

  3. Thus, indexing works as with list objects.

  4. But assignment fails:

    t = (1, 2, 3)
    t[1] = 100
    

    This won't work because it would change t.

  5. If you know that you aren't going to change your object at all, then tuple is probably a good choice over list.

  6. The built-in tuple() function will convert its argument to a tuple, and list() will covert its argument to list. Examples:

    x = (1, 2, 3)
    y = list(x)
    x[1] = 100           ## Throws an exception.
    y[1] = 100           ## Works fine; changes y.
    tuple(list(x)) == x  ## True!
    

dict

Python is built on dicts, and its dict objects are incredibly powerful!

  1. dict are defined by curly braces, with any number of key: value pairs in them. Examples:

    {1: 2, 2: 3, 3: 4}
    
    {'a': 1, 'b': True, 'c': [9, 8, 7]}
    
  2. The keys are the items to left of the colons. They can be any non-mutable Python object.

  3. The values are the items to the right of the colons. They can be any Python object.

  4. Look-ups are done with the keys, using the same syntax as for indexing into str and list:

    d = {'a': 1, 'b': True, 'c': [9, 8, 7]}
    
    d['a']  ## Returns 1
    d['c']  ## Returns [9, 8, 7]
    
  5. d[x] raises an exception of x is not already a key in d.

  6. Dicts are mutable, so you can add things to them with assignment statements: d['new'] = 4 works even if 'new' is not already a key in d.

  7. Dicts map each key to exactly one value.

  8. It is safest to assume that dicts are not ordered!

  9. d.keys() is a list-like object containing the keys. To make it a regular list, use list(d.keys()).

  10. d.values() is a list-like object containing the values. To make it a regular list, use list(d.values()).

  11. d.items() is a list-like object containing the key–value pairs as tuples. To make it a regular list, use list(d.items()), which is a list of tuples.

  12. len(d) gives the number of keys in d.

  13. Iterating over a dict:

    d = {"a": 1, "b": 2, "c": 3}
    
    # Prints the keys:
    for x in d:
       print(x)
    
    # Prints the keys:
    for x in d.keys():
       print(x)
    
    # Prints the values:
    for x in d.values():
       print(x)
    
    # Prints the item (key-value pair) tuples:
    for x in d.items():
       print(x)
    
    # Separate access to key and value objects with bonus fancy printing:
    for k, v in d.items():
       print("{} ==> {}".format(k, v))