beginnerFunctions

Functions

Define reusable blocks of code with def, parameters, and return values.

01Defining Functions

Use the def keyword to create reusable code blocks.

Python
1def greet(name):
2 return f"Hello, {name}!"
3
4print(greet("Alice"))
5print(greet("Bob"))
Output
Hello, Alice!
Hello, Bob!

02Default & Keyword Arguments

Set default parameter values and call with named arguments.

Python
1def power(base, exp=2):
2 return base ** exp
3
4print(power(3)) # 9
5print(power(3, 3)) # 27
6print(power(exp=4, base=2)) # 16
Output
9
27
16

03*args and **kwargs

Accept variable numbers of positional and keyword arguments.

Python
1def total(*args):
2 return sum(args)
3
4def info(**kwargs):
5 for key, val in kwargs.items():
6 print(f"{key}: {val}")
7
8print(total(1, 2, 3, 4))
9info(name="Alice", age=30)
Output
10
name: Alice
age: 30

04Lambda Functions

Small anonymous functions for simple operations.

Python
1square = lambda x: x ** 2
2add = lambda a, b: a + b
3
4print(square(5)) # 25
5print(add(3, 4)) # 7
6
7numbers = [3, 1, 4, 1, 5]
8sorted_nums = sorted(numbers, key=lambda x: -x)
9print(sorted_nums) # [5, 4, 3, 1, 1]
Output
25
7
[5, 4, 3, 1, 1]