all_parameters.py

"""
Function parameters

Discuss the calls of 'example' one by one
"""
def example(obligatory, optional=77, *args, **kwargs):
    print("obligatory: ", obligatory)
    print("optional  : ", optional)
    print("args      : ", args)
    print("kwargs    : ", kwargs)
    print()


example()
# example(True)
# example(True, 99)
# example(True, 99, 77)
# example(True, 99, 77, 55)
# example(True, 99, 77, 55, a=33, b=11)

default_parameters.py

"""
Examples of named parameters
"""
def addition(a=2, b=2, c=2):
    return a + b + c


print(addition(3, 3, 3))
print(addition(3, 3))
print(addition(3))
print(addition())
print(addition(b=4))
print(addition(b=4, c=5))

# partial assignment of parameters
from functools import partial

x = partial(addition, c=7, a=2)
print(x(b=5))

exercise_factorial.py

"""
Exercise:
Write a recursive function that calculates factorials (n!)
"""

def factorial(n):
    """Returns a factorial of n."""
    pass


# Test code
assert factorial(0) == 1
assert factorial(1) == 1
assert factorial(2) == 2
assert factorial(3) == 6
assert factorial(7) == 5040

mutable_immutable_parameters.py

# Example: Mutable and immutable parameters.

def change(var1, var2):
    """Change two values."""
    var1 += [7]
    var2 += 7


data = [3,4,5]
number = 6

change(data, number)

print("The list now contains", data)
print("The number is now", number)

scope.py

"""
Example: local variable scope

Guess the value of the variable 'a' at the end of the program?

1) In the code as it is?
2) With the statement 'global a' inserted before the line 'a = number1 + number2'
3) With the statement 'global a' inserted after the line 'a = number1 + number2'

Verify your expectations
"""

def addition(number1, number2):
    """Just adds two numbers."""
    a = number1 + number2
    return a


a = 3
b = 5
c = addition(a, b)

Dr. Kristian Rother

I am a professional Python trainer, developer and author based in Berlin. I believe everybody can learn programming.

Contact me via:
+49 176 3052 4691
krother@academis.eu

Feedback

All participants (and I) agreed that you gave an excellent training. Thank you !

Janick Mathys, VIB Belgium

See also