beginnerPython Framework • Core Concepts

Functions & Modules

Join 1.2k+ learners

The Power of Dry Code

DRY (Don't Repeat Yourself) is a core principle. Functions let you write logic once and use it everywhere. They are the building blocks of every great program.

Python
def analyze_text(text): words = text.split() return len(words) print(analyze_text("Hello World")) # 2 print(analyze_text("Python is awesome")) # 3

Flexible Arguments

Python functions are incredibly flexible. You can use positional arguments, keyword arguments, and even set default values for optional parameters.

Python
def create_user(name, role="guest", active=True): return f"{name} ({role}) - Active: {active}" print(create_user("Alice")) print(create_user("Bob", role="admin", active=False))

Scope: Who Sees What?

Variables have a lifecycle. 'Local' variables live and die inside the function. 'Global' variables live forever. Understanding this prevents nasty bugs.

Python
score = 0 # Global def update_score(points): # global score <-- Needed to modify global new_score = score + points # Local 'new_score' return new_score print(update_score(10))

Lambda: The One-Liner

Sometimes you need a tiny function for a short time, like for sorting or filtering. Lambdas are perfect for this 'throwaway' logic.

Python
users = [{'name': 'A', 'age': 25}, {'name': 'B', 'age': 20}] # Sort by age using lambda users.sort(key=lambda u: u['age']) print(users)

The Standard Library

Python isn't just a language; it's a toolbox. Convert dates, generate random data, or do complex math instantly with built-in modules.

Python
import random import math from datetime import datetime print(f"Correct answer: {math.sqrt(144)}") print(f"Lucky number: {random.randint(1, 100)}") print(f"Time now: {datetime.now().strftime('%H:%M')}")

Master this concept

Hands-on practice is the fastest way to learn. Head over to our interactive workspace to solve this topic's challenge.

Launch Editor

Visual Lab

The Function Machine

Input Arguments
if
Transformation
Return Value
Start/End
Condition
Action

New Challenge available!

Master Functions & Modules with a hands-on task.