InterviewPrepKit

Home / Cheat Sheet / Algorithms & Data Structures with Python

Cheat sheet

Functions, Arguments, and Scope

Read the full lesson →

Functions name a block of code so you can reuse it, and scope controls where the names inside are visible.

Defining and calling

  • A function is a named block of code, defined with def name(): and a :-terminated header.
  • The indented lines below the header are the body; they run only when you call the function with name().
  • Defining does not run the body; calling does.

Parameters, arguments, return

  • Parameter: the name in the definition. Argument: the value passed at the call. Same slot, two words.
  • return ends the function and hands a value back to the caller; code after it does not run.
  • No return (or bare return) yields None (not 0, not ""). A function that only prints returns None.

Passing arguments

  • Positional: matched by order, so order is the meaning (power(2,3) != power(3,2)).
  • Keyword: named at the call (power(base=2, exponent=3)); order does not matter.
  • Mixing: all positional arguments must come before any keyword arguments.
  • Default argument: a fallback used when the caller omits it (def greet(name, greeting="hello")). Defaults must come after non-default parameters.
  • *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dictionary.

Gotchas

  • Mutable default arguments: the default is created once at definition, so def f(bag=[]) shares one list across all calls. Default to None and build a new one inside.
  • Reassigning a global without declaring it makes the name local for the whole function, causing UnboundLocalError. Use global only when you truly mean to change the global.
  • Forgetting parentheses: greet is the function value; greet() runs it.

Scope: name lookup

  • Scope: the region where a name is visible. Variables created inside a function are local and vanish when it returns.
  • Top-level names are global; functions can read them, but assigning to a name makes it local unless declared global.
Use a name inside a function
        |
   Assigned in this function?
   /        |             \
 no      yes, no       declared
  |      'global'       'global'
GLOBAL    LOCAL        GLOBAL var
scope   (set before   (assignment
        first use)     updates it)

Extras

  • Docstring: a string as the first line of the body; explains the function, readable via func.__doc__.
  • Functions are values: store them, pass them as arguments (a callback), call with f() vs reference with f.
  • Cost: calling is O(1) (a stack frame); the real cost is what the body does.
Want the full picture? The lesson has the derivations, worked examples, and diagrams this card compresses into bullets. Read the full lesson →
Report a bug