Skip to content

Instantly share code, notes, and snippets.

View fabsta's full-sized avatar

Fabian Schreiber fabsta

View GitHub Profile

Regex

import re
pattern = re.compile("\w.?\w+@\w[.\w+]")

finds subpatterns

DEFINING FUNCTIONS

define a function with no arguments and no return values

def print_text():
    print 'this is text'

call the function

FOR LOOPS AND WHILE LOOPS

range returns a list of integers

range(0, 3)     # returns [0, 1, 2]: includes first value but excludes second value
range(3)        # same thing: starting at zero is the default
range(0, 5, 2)  # returns [0, 2, 4]: third argument specifies the 'stride'

COMPARISONS AND BOOLEAN OPERATIONS

comparisons (these return True)

5 > 3
5 >= 3
5 != 3
5 == 5

CONDITIONAL STATEMENTS

if statement

if x > 0:
    print 'positive'

if/else statement

if x > 0:

DICTIONARIES

  • properties: unordered, iterable, mutable, can contain multiple data types
  • made up of key-value pairs
  • keys must be unique, and can be strings, numbers, or tuples
  • values can be any type

create an empty dictionary (two ways)

empty_dict = {}

TUPLES

  • like lists, but they don't change size
  • properties: ordered, iterable, immutable, can contain multiple data types

create a tuple

digits = (0, 1, 'two')          # create a tuple directly
digits = tuple([0, 1, 'two'])   # create a tuple from a list
zero = (0,)                     # trailing comma is required to indicate it's a tuple

LISTS

properties: ordered, iterable, mutable, can contain multiple data types

create an empty list (two ways)

empty_list = []
empty_list = list()

create a list

SETS

  • like dictionaries, but with keys only (no values)
  • properties: unordered, iterable, mutable, can contain multiple data types
  • made up of unique elements (strings, numbers, or tuples)

create an empty set

empty_set = set()

STRINGS

(properties: iterable, immutable)

create a string

s = str(42)         # convert another data type into a string
s = 'I like you'

examine a string