beginnerFunctions
Functions
Define reusable blocks of code with def, parameters, and return values.
In this lesson
01Defining Functions
Use the def keyword to create reusable code blocks.
Python
1def greet(name):2 return f"Hello, {name}!"34print(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 ** exp34print(power(3)) # 95print(power(3, 3)) # 276print(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)34def info(**kwargs):5 for key, val in kwargs.items():6 print(f"{key}: {val}")78print(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 ** 22add = lambda a, b: a + b34print(square(5)) # 255print(add(3, 4)) # 767numbers = [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]