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.
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:
name → required parameterlanguage="German" → default value, optional during callYou 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:
double_greeting calls greeting(name)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:
import module_name → imports the modulemodule_name.function() → calls functions from the moduleWe 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:
sum(lst) → calculates the summax(lst) → largest valuemin(lst) → smallest valuereturn → returns multiple valuest, mx, mnWrite 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)