Skip to main content

1. Basic Function

2. Function with Arguments

3. Function with Default Arguments

4. Function with Return Statement

5. Function with Multiple Return Statements

6. Function with Keyword Arguments

7. Function with Arbitrary Arguments

8. Function with Docstring

9. Function with Lambda

10. Function with Recursion

11. Function with Global Variables

12. Function with Local Variables

13. Function with Nonlocal Variables

Output:
The nonlocal keyword is used inside a nested function to modify a variable from its enclosing (non-global) scope. Without nonlocal, assigning a new value to a variable inside a nested function creates a new local variable instead of modifying the one from the outer function.

14. Function with Global Keyword

Output:

15. Function with Pass Statement

16. Function with Recursion Limit

17. Function with Annotations

18. Function with Annotations and Return Type

19. Function with Annotations and Default Arguments

20. Function with Annotations and Multiple Return Statements

21. Function with Annotations and Keyword Arguments

22. Function with Annotations and Arbitrary Arguments

23. Function with Annotations and Lambda

Lambda function does not support annotations.

24. Function Decorators

25. Function with Decorator Syntax

26. Function with Multiple Decorators

27. Function with Arguments in Decorator

28. Advanced Function

29. Function with Nested Functions

30. Function with Nested Functions and Closures

  • Closure Concept – inner() is a closure because it captures and retains access to x = 10 from outer() even after outer() has finished executing.
  • Function Reference – outer() returns inner without calling it, so inner becomes a function reference that can be executed later.
  • Execution Flow – Calling outer() assigns x = 10, returns inner, and when inner() is called, it prints β€œValue of x: 10”.
  • Variable Retention – Even though outer() is done executing, Python keeps x = 10 alive inside inner() due to the closure mechanism.
  • Encapsulation – This technique avoids global variables, keeps data within functions, and allows multiple closures to store different values.