All categories

    Functions

    Definitions, arguments, returns, and lambdas.

    01Simple function

    main.py
    def greet(name):
        return f"Hello, {name}!"
    
    print(greet("World"))
    Output
    Hello, World!

    02Default arguments

    main.py
    def power(base, exp=2):
        return base ** exp
    
    print(power(5))
    print(power(2, 10))
    Output
    25
    1024

    03Keyword arguments

    main.py
    def describe(name, age, city="Unknown"):
        return f"{name}, {age}, from {city}"
    
    print(describe(age=30, name="Eve"))
    print(describe("Tom", 25, city="Berlin"))
    Output
    Eve, 30, from Unknown
    Tom, 25, from Berlin

    04Variable arguments (*args, **kwargs)

    main.py
    def report(*args, **kwargs):
        print("args:", args)
        print("kwargs:", kwargs)
    
    report(1, 2, 3, name="Ada", role="dev")
    Output
    args: (1, 2, 3)
    kwargs: {'name': 'Ada', 'role': 'dev'}

    05Lambda function

    main.py
    square = lambda x: x * x
    print(square(6))
    
    nums = [1, 2, 3, 4]
    print(list(map(lambda n: n * 10, nums)))
    Output
    36
    [10, 20, 30, 40]

    06Recursion (factorial)

    main.py
    def fact(n):
        return 1 if n <= 1 else n * fact(n - 1)
    
    print(fact(6))
    Output
    720