Interactive Computer Science Tutoring

Learn programming concepts interactively

AHA Schools Logo

Python Functions

Learn function definition, parameters, and lambda expressions

Learning ModulesInteractive
Choose an interactive example to explore Python functions
Function CalculatorParameters
Build and test functions with different parameter types
add(a, b)

Sum of two numbers

power(base, exponent=2)

Base raised to exponent power

calculate_average(*numbers)

Average of all numbers

Function Calls
Global Actions
Python Functions Code
Live Python code showing function definitions and usage
# Python Functions - Interactive Examples
# Learn function definition, parameters, and lambda expressions
# === CALCULATOR BUILDER ===
# Examples of different parameter types
def add(a, b):
"""Sum of two numbers"""
return a + b
def power(base, exponent=2):
"""Base raised to exponent power"""
return base ** exponent
def calculate_average(*numbers):
"""Average of all numbers"""
return sum(numbers) / len(numbers) if numbers else 0
# === TEXT PROCESSOR ===
# Examples of *args and **kwargs
def process_text(*args, **kwargs):
"""Flexible text processing with *args and **kwargs"""
# args contains all positional arguments
text = ' '.join(str(arg) for arg in args)
# kwargs contains all keyword arguments
if kwargs.get('capitalize'):
text = text.upper()
if kwargs.get('reverse'):
text = text[::-1]
return text
def format_names(*names, **options):
"""Format multiple names with optional title and case"""
formatted = []
for name in names:
result = name
if 'title' in options:
result = f"{options['title']} {result}"
if options.get('uppercase'):
result = result.upper()
formatted.append(result)
return ', '.join(formatted)
# === LAMBDA WORKSHOP ===
# Lambda expressions and functional programming
square = lambda x: x ** 2
# Square a number
is_even = lambda x: x % 2 == 0
# Check if number is even
string_length = lambda s: len(s)
# Get string length
# Using lambdas with built-in functions
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Higher-order function example
def apply_operation(func, values):
"""Apply a function to a list of values"""
return [func(x) for x in values]
# Using with lambda
results = apply_operation(lambda x: x * 3, [1, 2, 3])
# Results: [3, 6, 9]
# Key Concepts:
# - def keyword for function definition
# - Positional, keyword, and default parameters
# - *args for variable positional arguments
# - **kwargs for variable keyword arguments
# - lambda expressions for simple functions
# - Higher-order functions and functional programming
History0/5
Recent function operations with results

No operations yet

Start by adding or modifying elements