Python Advanced: Extending Functions & Modules

Level Goal

Today you will learn:

By the end, you will be able to create more flexible functions, reuse code, and use built-in Python modules to solve tasks faster.

Step 1: Functions with Optional Parameters

Optional means that a parameter has a default value.

If nothing is passed during the call, Python uses the default value.


def greeting(name, language="German"):
    return "Hello " + name + "!"

print(greeting("Max"))
print(greeting("Anna", "English"))

Output:


Hello Max!
Hello Anna!

Explanation:

Step 2: Calling Functions Inside Other Functions

You can call a function inside another function to reuse code.


def greeting(name):
    return "Hello " + name

def double_greeting(name):
    text = greeting(name) + "!"
    return text + " Nice to see you!"

print(double_greeting("Max"))

Output:


Hello Max! Nice to see you!

Explanation:

Step 3: Working with External Modules

Python has many built-in modules that provide functions, e.g., math, random, or date functions.

Importing a module:


import math

# Calculate square root
print(math.sqrt(16))

Output:


4.0

More examples:


import random

number = random.randint(1, 10)  # Random number between 1 and 10
print(number)

Practical tips:

Step 4: Practical Example – Evaluating a List

We write a function that returns the sum, maximum, and minimum of a list:


def evaluate(lst):
    total = sum(lst)
    max_value = max(lst)
    min_value = min(lst)
    return total, max_value, min_value

numbers = [3, 7, 1, 9, 4]
t, mx, mn = evaluate(numbers)
print("Sum:", t, "Max:", mx, "Min:", mn)

Output:


Sum: 24 Max: 9 Min: 1

Explanation:

Exercise

Write a function statistics that takes a list of numbers.

The function should return sum, average, maximum, and minimum.

Test the function with any list of numbers:


def statistics(lst):
    total = sum(lst)
    average = total / len(lst)
    max_value = max(lst)
    min_value = min(lst)
    return total, average, max_value, min_value

numbers = [5, 8, 2, 10, 7]
t, avg, mx, mn = statistics(numbers)
print("Sum:", t, "Average:", avg, "Max:", mx, "Min:", mn)