Beyond the Basics of Function

Python tutorial · PySpark.in

1 Anonymous (Lambda) Functions

PYTHON
1square = lambda x: x * x
2print(square(5)) # Output: 25
▶ Output will appear here.

Use Case: Useful in functions like map(), filter(), and sorted().

2 Recursion (Function Calling Itself)

PLAINTEXT
1def factorial(n):
2 if n == 1:
3 return 1
4 return n * factorial(n - 1)
▶ Output will appear here.

Use Case: Solving problems like factorial, Fibonacci, or tree traversal.

3  Scope and Lifetime of Variables

PLAINTEXT
1x = 10 # Global
2def show():
3 y = 5 # Local
4 print(x + y)
▶ Output will appear here.

Use Case: Understanding variable access and avoiding name conflicts.

4 The global and nonlocal Keywords

PLAINTEXT
1count = 0
2def increment():
3 global count
4 count += 1
5def outer():
6 x = 10
7 def inner():
8 nonlocal x
9 x += 5
10 print(x)
11 inner()
▶ Output will appear here.

5 Docstrings (Documentation Strings)

PYTHON
1def add(a, b):
2 """Return the sum of two numbers."""
3 return a + b
4print(add.__doc__)
▶ Output will appear here.

Use Case: Improves readability and helps tools like help() and IDE tooltips.

6 Function Annotations (Type Hints)

PLAINTEXT
1def greet(name: str, age: int) -> str:
2 return f"Hello {name}, you are {age} years old!"
▶ Output will appear here.

Use Case: Improves code clarity and helps static type checkers.

7 Higher-Order Functions

PYTHON
1def apply(func, value):
2 return func(value)
3print(apply(lambda x: x**2, 5)) # Output: 25
▶ Output will appear here.

Use Case: Common in functional programming and frameworks.

8 Closures

PYTHON
1def outer(x):
2 def inner(y):
3 return x + y
4 return inner
5add_five = outer(5)
6print(add_five(10)) # Output: 15
▶ Output will appear here.

Use Case: Useful for decorators and encapsulation.

9 Decorators

PYTHON
1def decorator(func):
2 def wrapper():
3 print("Before function")
4 func()
5 print("After function")
6 return wrapper
7@decorator
8def say_hello():
9 print("Hello!")
10say_hello()
▶ Output will appear here.

Use Case: Logging, authentication, timing, etc.

10 Built-in Higher-Order Functions

These built-in functions take other functions as arguments:

PYTHON
1nums = [1, 2, 3, 4]
2squares = list(map(lambda x: x*x, nums))
3print(squares)
▶ Output will appear here.

11 Generator Functions & yield Keyword

PYTHON
1def countdown(n):
2 while n > 0:
3 yield n
4 n -= 1
5for i in countdown(3):
6 print(i)
▶ Output will appear here.

Use Case: Memory-efficient iteration.

12 Function Introspection

You can get information about a function using built-in attributes:

PYTHON
1def sample(x: int) -> int:
2 """Example function"""
3 return x + 1
4print(sample.__name__) # sample
5print(sample.__doc__) # Example function
6print(sample.__annotations__) # {'x': , 'return': }
▶ Output will appear here.

13 Partial Functions (from functools)

PLAINTEXT
1from functools import partial
2def power(base, exp):
3 return base ** exp
4square = partial(power, exp=2)
5print(square(5))
▶ Output will appear here.

Use Case: Simplify frequently used function calls.

14 Async (Asynchronous) Functions

PLAINTEXT
1import asyncio
2async def greet():
3 print("Hello")
4 await asyncio.sleep(1)
5 print("World")
▶ Output will appear here.

Use Case: For non-blocking I/O operations and web apps.

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges