1. Function Basics
Functions are reusable code blocks defined with def. They can take parameters and return values.
def greet():
print("Hello, Python learner!")
greet()
Hello, Python learner!
2. Parameters & Arguments
Pass data to functions using parameters. Positional, keyword, default values all supported.
def welcome(name, greeting="Hi"):
print(f"{greeting}, {name}!")
welcome("Alice") # Hi, Alice!
welcome("Bob", "Hello") # Hello, Bob!
Hi, Alice!
Hello, Bob!
3. Return Values
Use return to send data back. Functions without return return None.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
8
4. *args & **kwargs
*args collects extra positional args as tuple. **kwargs collects keyword args as dict.
def sum_all(*args):
return sum(args)
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print(sum_all(1, 2, 3, 4)) # 10
print_info(name="Alice", age=25)
10
name: Alice
age: 25
5. Scope & Global
Variables inside functions are local by default. Use global keyword for function-wide access.
count = 0
def increment():
global count
count += 1
return count
print(increment()) # 1
print(increment()) # 2
6. Lambda Functions
Anonymous one-line functions using lambda. Great for simple operations.
# Lambda equivalent of def square(x): return x**2
square = lambda x: x**2
print(square(5)) # 25
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, numbers))
print(squares) # [1, 4, 9, 16]
25
[1, 4, 9, 16]
Function Types Quick Reference
| Type | Syntax | Example | Use Case |
|---|---|---|---|
| Basic | def name(): | greet() | Simple tasks |
| Parameters | def name(param=default): | add(2, 3) | Data processing |
| Return | def name(): return value | result = calc() | Calculations |
| *args | def name(*args): | sum_all(1,2,3) | Variable inputs |
| **kwargs | def name(**kwargs): | info(**data) | Named params |
| Lambda | lambda x: value | map(lambda...) | Quick ops |
๐ง Functions Quiz (8 Questions)
Q1: Keyword to define function?
Q2: What does function without return return?
Q3: Call def add(a, b): return a+b
Q4: Default parameter syntax?
Q5: What does *args collect?
Q6: Lambda syntax?
Q7: Access args in function?
Q8: Modify global variable?