🐍 Function

function

Good to know

⭐️ Functions let you group reusable logic into named blocks. Use def to define a function, and return to send a value back. Functions can take parameters, have default values, and accept variable numbers of arguments.


Basic Function

Defines a function and calls it.

def say_hi():
    print("Hello User")
 
say_hi()

Parameters

Function With Parameters

Parameters receive values when the function is called. Inside classes, you might wanna use: the self parameter

def say_hi(name):
    print("Hello " + name)
 
say_hi("Alain")

Function With Multiple Parameters

def say_hi(name, age):
    print("Hello " + name + " you are " + str(age))
 
say_hi("Alain", 33)

Default Parameters

Useful when callers may omit some arguments.

def greet(name="User"):
    print("Hello", name)
 
greet()          # Hello User
greet("Alain")   # Hello Alain

Keyword Arguments

Call a function using name=value for flexibility.

def say_hi(name, age):
    print(name, "is", age)
 
say_hi(age=30, name="Alain")

Variable-Length Arguments (args)

If the number of arguments can change, use args.


Docstrings (Function Documentation)

Use triple quotes to describe what your function does. This text will be shown, when hovered with the mouse over the function.

def add(a, b):
    """Returns the sum of two numbers."""
    return a + b

Returning Values

return sends a value back to the caller.

def cube(num):
    return num * num * num
 
result = cube(3)
print(result)   # 27

Lambda Functions (Small Anonymous Functions)

Useful for short one-line operations.

square = lambda x: x * x # lambda parameter: logic
print(square(5))   # 25

Functions Calling Other Functions

def greet():
    print("Hello!")
 
def welcome_user():
    greet()
    print("Welcome!")
 
welcome_user()