Skip to content

Instantly share code, notes, and snippets.

@fabsta
Created August 28, 2016 20:27
Show Gist options
  • Save fabsta/11febad6aa5cc0c8804ee4f3eb02bd67 to your computer and use it in GitHub Desktop.
Save fabsta/11febad6aa5cc0c8804ee4f3eb02bd67 to your computer and use it in GitHub Desktop.

DEFINING FUNCTIONS

define a function with no arguments and no return values

def print_text():
    print 'this is text'

call the function

print_text()

define a function with one argument and no return values

def print_this(x):
    print x

call the function

print_this(3)       # prints 3
n = print_this(3)   # prints 3, but doesn't assign 3 to n
                    #   because the function has no return statement

define a function with one argument and one return value

def square_this(x):
    return x**2

include an optional docstring to describe the effect of a function

def square_this(x):
    """Return the square of a number."""
    return x**2

call the function

square_this(3)          # prints 9
var = square_this(3)    # assigns 9 to var, but does not print 9

define a function with two 'positional arguments' (no default values) and

one 'keyword argument' (has a default value)

def calc(a, b, op='add'):
    if op == 'add':
        return a + b
    elif op == 'sub':
        return a - b
    else:
        print 'valid operations are add and sub'

call the function

calc(10, 4, op='add')   # returns 14
calc(10, 4, 'add')      # also returns 14: unnamed arguments are inferred by position
calc(10, 4)             # also returns 14: default for 'op' is 'add'
calc(10, 4, 'sub')      # returns 6
calc(10, 4, 'div')      # prints 'valid operations are add and sub'

use 'pass' as a placeholder if you haven't written the function body

def stub():
    pass

return two values from a single function

def min_max(nums):
    return min(nums), max(nums)

return values can be assigned to a single variable as a tuple

nums = [1, 2, 3]
min_max_num = min_max(nums)         # min_max_num = (1, 3)

return values can be assigned into multiple variables using tuple unpacking

min_num, max_num = min_max(nums)    # min_num = 1, max_num = 3

ANONYMOUS (LAMBDA) FUNCTIONS

primarily used to temporarily define a function for use by another function

define a function the "usual" way

def squared(x):
    return x**2

define an identical function using lambda

squared = lambda x: x**2

sort a list of strings by the last letter (without using lambda)

simpsons = ['homer', 'marge', 'bart']
def last_letter(word):
    return word[-1]
sorted(simpsons, key=last_letter)

sort a list of strings by the last letter (using lambda)

sorted(simpsons, key=lambda word: word[-1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment