Creating a Function
Use thedef keyword.
Syntax
Calling a Function
A function executes only when it is called.Function Parameters and Arguments
Parameter
Variables defined in the function.name is a parameter.
Argument
Actual value passed to the function."Alice" is an argument.
Positional Arguments
Arguments are matched by position.Keyword Arguments
Arguments are passed using parameter names.Default Parameters
A parameter can have a default value.Multiple Parameters
Return Statement
Returns a value to the caller.Returning Multiple Values
print() vs return
print()
Displays output.return
Returns a value.Arbitrary Arguments (*args)
Accepts any number of positional arguments.
Arbitrary Keyword Arguments (**kwargs)
Accepts any number of keyword arguments.
Combining Parameters
Variable Scope
Scope determines where a variable can be accessed.Local Scope
Created inside a function.Global Scope
Created outside every function.global Keyword
Modify a global variable.Nested Functions
A function inside another function.Recursive Function
A function calling itself.Lambda Function (Anonymous Function)
Small one-line function.Higher-Order Functions
Functions can be passed as arguments.Built-in Functions
Some commonly used Python functions.
Example
Function Annotations (Type Hints)
Used to specify expected types.Decorators
A decorator is a function that modifies or extends the behavior of another function without changing its original code. Decorators use the@ symbol.
Simple Decorator
Decorator with Arguments
Multiple Decorators
Decorators are applied from bottom to top.Common Built-in Decorators
@staticmethod
Does not use self or cls.
@classmethod
Receives the class (cls) instead of the object.
@property
Allows calling a method like an attribute.
Quick Revision
def→ Create a function- Call function using
() - Parameters → Variables in function definition
- Arguments → Values passed to function
return→ Returns valueprint()→ Displays value- Default parameters → Optional values
*args→ Multiple positional arguments**kwargs→ Multiple keyword arguments- Local scope → Inside function
- Global scope → Outside function
global→ Modify global variable- Nested function → Function inside another function
- Recursion → Function calls itself
- Lambda → Anonymous one-line function
- Higher-order function → Takes or returns functions
- Type hints → Specify expected parameter/return types
- Decorator → Adds functionality without modifying the original function
@staticmethod→ Noselforcls@classmethod→ Uses class (cls)@property→ Access method like an attribute