PyForge · Python practice library
All topics

Topic 09 of 17

Functions

Define reusable logic — arguments, return values, scope, lambdas.

def & return
*args / **kwargs
Default & keyword args
Lambda
Scope

Basic

2 programs

Program 1

Simple function

Basic

A function that returns a value.

python
def square(n):
    return n * n

print(square(7))

Program 2

Default & keyword args

Basic

Use defaults and named arguments.

python
def greet(name, msg="Hello"):
    return f"{msg}, {name}!"

print(greet("Sara"))
print(greet(name="Ben", msg="Hi"))

Intermediate

2 programs

Program 1

*args and **kwargs

Intermediate

Accept variable numbers of arguments.

python
def show(*args, **kwargs):
    print("args:", args)
    print("kwargs:", kwargs)

show(1, 2, 3, name="Ada", lang="Py")

Program 2

Lambda + map/filter

Intermediate

Use lambdas with functional helpers.

python
nums = [1, 2, 3, 4, 5, 6]
squared = list(map(lambda x: x ** 2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))
print(squared)
print(evens)

Advanced

1 program

Program 1

Recursive factorial

Advanced

A classic recursion example.

python
def fact(n):
    return 1 if n <= 1 else n * fact(n - 1)

print(fact(6))

Output

720