Python functions

From wikinotes
Revision as of 17:08, 6 May 2018 by Will (talk | contribs) (→‎Basics)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Basics

functions and arguments

def welcome_user(username, studio):
    print('hello {}, welcome to {}'.format(username, studio))

keyword arguments

Keyword arguments are optional arguments. The order that they are used does not matter if you assign their value with an '=' sign.

def insult_age(username, age=None):
    if age:
        print("{}! Hahahaha, you're old {}".format(username, age))
    else:
        print("Don't be shy {}, I already know you're old".format(username))


insult_age('bob')
>>> "Don't be shy bob, I already know you're old"

insult_age('bob', 12)
>>> "12! Hahahaha, you're old bob"

insult_age('bob', age=12)
>>> "12! Hahahaha, you're old bob"

Functions as Parameters

This is very useful, it allows you to package or classify functions

def insult_age(username):
    return "you're old, {}".format(username)

def compliment_age(username):
    return "you look young for your age, {}".format(username)

def welcome_user( fn_welcome, username ):
    print( fn_welcome(username) )


Tools

lambda functions

lambda functions are anonymous functions (functions that are not coded, they are declared on-the-fly).

fn = lambda x,y,z: print(x,y,z)
>>> <function __main__.<lambda>(x, y, z)>

fn(1,2,3)
>>> 1 2 3

partial functions

partial functions are used when currying. You can pre-load a function with some of it's arguments, and pass that along. (this is useful when handling events etc).

import functools

def insult_age(username, age):
    print("{}! Hahahaha, you're old {}".format(username, age))

partial = functools.partial( insult_age, 'bob' )

partial(12)
>>> "12! Hahahaha, you're old bob"