background preloader

Google Python Class

Facebook Twitter

Google Python Class Day 1 Part 1. Strings. Python Strings - Educational Materials. Python has a built-in string class named "str" with many handy features (there is an older module named "string" which you should not use).

Python Strings - Educational Materials

String literals can be enclosed by either double or single quotes, although single quotes are more commonly used. Backslash escapes work the usual way within both single and double quoted literals -- e.g. \n \' \". A double quoted string literal can contain single quotes without any fuss (e.g. "I didn't do it") and likewise single quoted string can contain double quotes. Python strings are "immutable" which means they cannot be changed after they are created (Java strings also use this immutable style). Characters in a string can be accessed using the standard [ ] syntax, and like Java and C++, Python uses zero-based indexing, so if str is 'hello' str[1] is 'e'.

S = 'hi' print s[1] ## i print len(s) ## 2 print s + ' there' ## hi there Unlike Java, the '+' does not automatically convert numbers or other types to string form. String Methods String % Google Python Class Day 1 Part 2. Stdtypes (python) Lists. Python Lists - Educational Materials. Python has a great built-in list type named "list".

Python Lists - Educational Materials

List literals are written within square brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0. (See the official list docs.) colors = ['red', 'blue', 'green'] print colors[0] ## red print colors[2] ## green print len(colors) ## 3 Assignment with an = on lists does not make a copy. B = colors ## Does not copy the list The "empty list" is just an empty pair of brackets [ ]. FOR and IN Python's *for* and *in* constructs are extremely useful, and the first use of them we'll see is with lists.

Squares = [1, 4, 9, 16] sum = 0 for num in squares: sum += num print sum ## 30 If you know what sort of thing is in the list, use a variable name in the loop that captures that information such as "num", or "name", or "url". Tuples (Python) Dictionary(python built-in) Python Dict and File - Educational Materials. Dict Hash Table Looking up or setting a value in a dict uses square brackets, e.g. dict['foo'] looks up the value under the key 'foo'.

Python Dict and File - Educational Materials

Strings, numbers, and tuples work as keys, and any type can be a value. Other types may or may not work correctly as keys (strings and tuples work cleanly since they are immutable). Looking up a value which is not in the dict throws a KeyError -- use "in" to check if the key is in the dict, or use dict.get(key) which returns the value or None if the key is not present (or get(key, not-found) allows you to specify what value to return in the not-found case). print dict['a'] ## Simple lookup, returns 'alpha' dict['a'] = 6 ## Put new key/value into dict 'a' in dict ## True ## print dict['z'] ## Throws KeyError if 'z' in dict: print dict['z'] ## Avoid KeyError print dict.get('z') ## None (instead of KeyError) A for loop on a dictionary iterates over its keys by default. ## Get the .keys() list: print dict.keys() ## ['a', 'o', 'g'] Dict Formatting Del Files.

Google Python Class Day 1 Part 3. File Objects (Python) .read([size]) (python--file-object) Google Python Class Day 2 Part 1. Regular Expressions (Python) Google Python Class Day 2 Part 2. Os.path (python) Google Python Class Day 2 Part 3. Python Utilities - Educational Materials. In this section, we look at a few of Python's many standard utility modules to solve common problems.

Python Utilities - Educational Materials

File System -- os, os.path, shutil The *os* and *os.path* modules include many functions to interact with the file system. The *shutil* module can copy files. os module docs filenames = os.listdir(dir) -- list of filenames in that directory path (not including . and ..). The filenames are just the names in the directory, not their absolute paths. ## Example pulls filenames from a dir, prints their relative and absolute pathsdef printdir(dir): filenames = os.listdir(dir) for filename in filenames: print filename ## foo.txt print os.path.join(dir, filename) ## dir/foo.txt (relative to current dir) print os.path.abspath(os.path.join(dir, filename)) ## /home/nick/dir/foo.txt Exploring a module works well with the built-in python help() and dir() functions.

Running External Processes -- commands The *commands* module is a simple way to run an external command and capture its output. Exceptions. Urllib (Python) Urllib.urlretrieve([string]url) python. Urllib.urlopen([string]url) Google Python Class Day 2 Part 4. Tripple Quoted String (Python) Log Puzzle Python Exercise - Educational Materials.

For the Log Puzzle exercise, you'll use Python code to solve two puzzles.

Log Puzzle Python Exercise - Educational Materials

This exercise uses the urllib module, as shown in the Python Utilities section. The files for this exercise are in the "logpuzzle" directory inside google-python-exercises (download the if you have not already, see Set Up for details). Add your code to the "" file. An image of an animal has been broken it into many narrow vertical stripe images. The stripe images are on the internet somewhere, each with its own url. The slice urls are hidden inside apache log files (the open source apache web server is the most widely used server on the internet).

Here is what a single line from the log file looks like (this really is what apache log files look like): Python Regular Expressions - Educational Materials. Regular expressions are a powerful language for matching text patterns.

Python Regular Expressions - Educational Materials

Baby Names Python Exercise - Educational Materials. The Social Security administration has this neat data by year of what names are most popular for babies born that year in the USA (see social security baby names).

Baby Names Python Exercise - Educational Materials

Copy Special Python Exercise - Educational Materials. The Copy Special exercise goes with the file-system and external commands material in the Python Utilities section.

Copy Special Python Exercise - Educational Materials

This exercise is in the "copyspecial" directory within google-python-exercises (download if you have not already, see Set Up for details). Add your code in The program takes one or more directories as its arguments. We'll say that a "special" file is one where the name contains the pattern __w__ somewhere, where the w is one or more word chars.

The provided main() includes code to parse the command line arguments, but the rest is up to you. Suggested functions for your solution(details below): get_special_paths(dir) -- returns a list of the absolute paths of the special files in the given directory copy_to(paths, dir) given a list of paths, copies those files into the given directory zip_to(paths, zippath) given a list of paths, zip those files up into the given zipfile. Python Sorting - Educational Materials. The easiest way to sort is with the sorted(list) function, which takes a list and returns a new list with those elements in sorted order.

Python Sorting - Educational Materials

The original list is not changed. a = [5, 1, 4, 3] print sorted(a) ## [1, 3, 4, 5] print a ## [5, 1, 4, 3] It's most common to pass a list into the sorted() function, but in fact it can take as input any sort of iterable collection. The older list.sort() method is an alternative detailed below. The sorted() function seems easier to use compared to sort(), so I recommend using sorted(). The sorted() function can be customized though optional arguments. Basic Python Exercises - Educational Materials. There are 3 exercises that go with the first sections of Google's Python class.

Basic Python Exercises - Educational Materials

They are located in the "basic" directory within the google-python-exercises directory. Download the if you have not already (see the Set-Up page for details). -- complete the string functions in, based on the material in the Python Strings section (additional exercises available in -- complete the list functions in, based on the material in the Python Lists and Python Sorting sections (additional exercises available in -- this larger, summary exercise in combines all the basic Python material in the above sections plus Python Dicts and Files (a second exercise is available in With all the exercises, you can take a look at our solution code inside the solution subdirectory.