Skip to content

Instantly share code, notes, and snippets.

@neilmock
Created April 21, 2010 20:08
Show Gist options
  • Save neilmock/374328 to your computer and use it in GitHub Desktop.
Save neilmock/374328 to your computer and use it in GitHub Desktop.

Python

Python is an interpreted, dynamically typed, object-oriented programming language. It is open-source, and was originally released in 1991 by Guido van Rossum.

Language Overview

Here's a sample Python method to get started with syntax:

def say_goodnight(name):
    result = "Good night, " + name
    return result

>>> say_goodnight("John-Boy")
'Good night, John-Boy

Python syntax uses whitespace indentation instead of braces to delimit blocks, so in the example above the method is ended by the final line having a decrease in indentation (4-space indentation is recommended by most standards documents.). This tends to inherently promote code style consistency.

Methods are defined with the keyword def, followed by the method name (in this case, say_goodnight) and the method’s parameters between required parentheses. All Python statements that allow code blocks to follow are ended with a colon to signify the beginning of the code block.

Data Structures

Lists:

A Python list is an object that contains an ordered collection of objects. For example,

a = [1, 2, 3, 4, 5]

creates a Python list that comprises five plain integers and assigns it to the variable a.

The elements of a Python list are accessed using zero-based integer-valued indices. Python also supports the use of negative indices to index into a list from the right. Here's some examples:

>>> a[0]
1
>>> a[-1]
5
>>> a[-2]
4

Python also has support for fetching a subset of a list, called a “slice”, by specifying two indices separated by a colon. The return value is a new list containing all the elements of the list, in order, starting with the first slice index up to but not including the second slice index.

>>> a[0:3]
[1,2,3]

>>> a[3:4]
4

Lists can be added to in several ways:

>>> a.append(1)
[1, 2, 3, 4, 5, 1]

>>> a.extend([1,2,3])
[1, 2, 3, 4, 5, 1, 2, 3]

>>> a.insert(2, 'thisisastring')
[1, 2, 'thisisastring', 3, 4, 5]

As you can see, lists are not limited to elements of the same data type--a list can contain integers, strings, objects, etc.

List comprehensions are a concise and powerful way to create lists, which normally might be constructed from loops. For example:

>>> fruits = ['apples', 'oranges', 'blueberries']
>>> upcased = [fruit.upper() for fruit in fruits]
['APPLES', 'ORANGES', 'BLUEBERRIES']

Sets:

A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket)               # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])

Dictionaries:

A dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).

>>> fruits = {'apple': 'red', 'orange': 'orange'}
>>> fruits['apple']
red    

>>> fruits['apple'] = 'RED'
>>> fruits['apple']
RED

You can retrieve lists all keys and values in a dictionary:

>>> fruits.keys()
['apple', 'orange']

>>> fruits.values()
['red', 'orange']

And test that a key is present in a dictionary:

>>> 'apple' in fruits
True

Looping Techniques

The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object:

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for fruit in fruits:
...     print fruit
...
apple
orange
apple
pear
orange
banana

A break statement terminates the loop. A continue statement continues with the next item.

>>> for fruit in fruits:
...    if fruit == 'orange':
...        continue
...    print fruit
...
apples
oranges
blueberries

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the iteritems() method.

>>> fruits = {'apple': 'red', 'orange': 'orange'}
>>> for k, v in fruits.iteritems():
...     print k, v
...
apple red
orange orange

Classes and Modules

coming soon...

Built-in functions

coming soon...

For Windows

Docs, Tutorials, Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment