Data Engineering Lab

Define and Call Functions — def, (), parameters, docstrings, and composition

Overview

A function is a named block of code you define once with def and run with name(...). The parentheses matter: greet refers to the function object; greet() executes the body. Parameters receive arguments at call time; return sends a value back to the caller (otherwise the call evaluates to None).

The Practice Lab Define and Call Functions covers: a no-arg print function, reuse with multiple calls, a parameterised greeting, a docstring plus return, and composition of two functions.

Use the flow diagram for definition vs call, reuse, argument binding, docstring + return, and composition. Open the practice map for Q1–Q5 aligned with the autograder.

Enable JavaScript to explore the interactive diagram.

Map to Practice Lab questions

Lab QSkill
Q1def greet(): indented body with print(...); greet() to run — define before call
Q2def print_separator(): once; print_separator() three times — DRY
Q3def say_hello(name): — say_hello("Python"); use f"Hello, {name}!" not a hard-coded name
Q4Docstring first statement: """Return a greeting message for the given name."""; return f"Hello, {name}!"; print(greet("Alice"))
Q5square(n) returns n ** 2; sum_of_squares(a, b) returns square(a) + square(b) → 25

Practice here: Practice Lab → Define and Call Functions.

Enable JavaScript to explore the interactive diagram.

Vocabulary

TermMeaning
Definedef name(...): creates the function and binds name in the current scope
Callname(args) runs the body with arguments bound to parameters
ParameterName in the def header (inside the parentheses)
ArgumentValue (or expression) passed at the call site
Return valueObject sent back by return; implicit None if no return

Industry norms

PracticeWhy
snake_case verbsPEP 8 — load_config, normalize_row, is_valid_id
Docstrings on public APIshelp(), Sphinx/MkDoc, IDE tooltips — one-line summary + Args/Returns for non-trivial code
Prefer return over print in librariesCallers choose logging or UI; print in shared packages complicates tests
Small pure helperssquare-style pieces are easy to unit test and reuse (lab Q5 pattern)
Type hints (later)def greet(name: str) -> str: improves readability and static checking
Idempotency in ETLSame function called twice on the same input should be safe when designing loaders

Key takeaways

  • def + indent defines; () invokes.
  • Define above first use in the file (top-to-bottom execution).
  • return for values you compose or test; print only when the spec asks for stdout.
  • Docstring must be the first statement in the body to count as __doc__.

Examples

Example 1 — Q1: simple greet

def greet():
    print("Hello from a function!")

greet()

Output:

Hello from a function!

Example 2 — Q2: separator reuse

def print_separator():
    print("----------")

print_separator()
print_separator()
print_separator()

Output:

----------
----------
----------

Example 3 — Q3: parameter

def say_hello(name):
    print(f"Hello, {name}!")

say_hello("Python")

Output:

Hello, Python!

Example 4 — Q4: docstring and return

def greet(name):
    """Return a greeting message for the given name."""
    return f"Hello, {name}!"

print(greet("Alice"))

Output:

Hello, Alice!

Example 5 — Q5: composition

def square(n):
    return n ** 2

def sum_of_squares(a, b):
    return square(a) + square(b)

print(sum_of_squares(3, 4))

Output:

25

Example 6 — Production-shaped: function as a value

def double(x):
    return x * 2

transform = double
print(transform(5))

Example 7 — Production-shaped: early return

def safe_div(a, b):
    if b == 0:
        return None
    return a / b

Mistakes

Mistake 1 — Missing () on call

❌ greet — does not run the body.

✅ greet() (Lab Q1).


Mistake 2 — Call before definition

❌ NameError — name not bound yet.

✅ def first, then call.


Mistake 3 — Hard-coding instead of using the parameter (Q3)

❌ print("Hello, Python!") inside say_hello always.

✅ Use {name} from the parameter.


Mistake 4 — Docstring not first (Q4)

❌ Code before the string — not stored as __doc__ the same way.

✅ Triple-quoted string immediately after :.


Mistake 5 — Printing instead of returning (Q5)

❌ print inside square breaks composition.

✅ return from helpers; print only at the top level if required.


Mistake 6 — Expecting a value from a print-only function

❌ x = greet() where greet only prints → x is None.

✅ Use return if you need a value.


Interview

Q1. What does a function without return return?

None implicitly.


Q2. Parameter vs argument?

Parameter is the name in the def; argument is the value passed at the call.


Q3. How do you exit nested loops cleanly?

return from an enclosing function, or refactor — not covered in this lab but pairs with composition.


Q4. Are Python functions objects?

Yes — first-class: assign, pass, return like other values.


Python vs PySpark

Python def runs on the driver (or workers if registered as a UDF). Prefer Column expressions and built-ins in Spark for scale; UDFs cost serialization and row-by-row Python. The comparison table is generated for this topic. Use Try Now for Python and PySpark practice.


Python vs SQL

SQL expresses set-level logic with expressions and optional stored functions; Python def packages imperative steps and return values for reuse in application code. The comparison table is generated for this topic. Use Try Now for Python and SQL practice.