Python Functions

1. Defining a Basic Function

def greet():
    print("Hello, Python!")

greet()

A function is defined using the def keyword followed by the function name and parentheses.


2. Function with Parameters

def greet_user(name):
    print(f"Hello, {name}!")

greet_user("Alice")

Parameters allow functions to accept external input.


3. Function with Return Value

def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # Output: 8

The return statement sends a value back to the caller.


4. Default Parameters

Default values are used when no argument is provided.


5. Keyword Arguments

Arguments can be passed by name for clarity.


6. *Variable-Length Arguments (args)

Allows passing multiple positional arguments.


7. **Keyword Variable-Length Arguments (kwargs)

Accepts arbitrary keyword arguments.


8. **Function with Both *args and kwargs

Supports flexible function signatures.


9. Lambda (Anonymous) Functions

Used for short, inline function definitions.


10. Recursive Functions

A function calling itself to solve repetitive problems.


Last updated