Functions

From Biolecture.org

Functions: Relation between input and output values. 

But some functions may not return a value.(such as print() )

There are Built-in functions, User-defined fuctions and Library functions.

<How to define functions>

def functional_name(parameters):

    statement 1

    statement 2

    ...

    return return_value

Ex)

def greeting(person, greeting_word='Hello'):

    print(greeting_word, ',', person)

 

greeting('Alice')                         Hello, Alice

greeting('Bob', 'Hi')                    Hi, Bob

Ex)

def power(base, exponent):

    return base**exponent

 

print(power(base=2, exponent=10))            1024

<Namespace and local variables>

Namespace: a mapping from names to objects.  (Global namespace or Local namespace.)

scope: a region of python program where a namespace is directly accessible.

Ex)

def inc(x):

    x=x+1

x=42

print(x)                      42                      # global value

inc(x)                         inc(42)                #refer to local value (provided x)

print(x)                      42                      # global value. Local value can't change the global value.

<Return statement & return value>

Ex)

def agegroup(age):

    if age<=12:

        return 'childhood'

    elif age<=18:

        return 'adolescent'

    elif age<=65:

        return 'adult'

    else:

        return 'aged'

print(agegroup(42))                          adult