Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Programming · Python · Chapter 04 / 16

Programming learning path

Functions & scope

Defining functions, parameters, return values, defaults and basic scope.

Defining and calling functions

def creates a reusable, named block of code; functions exist to avoid repeating yourself.

def name(parameters): followed by an indented body defines a function; the code inside does not run until the function is called with name(arguments). A function without an explicit return statement implicitly returns None. Functions exist primarily to avoid duplicating the same logic in multiple places — when a calculation or action is needed more than once, wrapping it in a function means a future bug fix or behavior change only needs to happen in one place instead of every copy.

Key points

  • def defines a function; the body only runs when the function is called
  • A function with no return statement implicitly returns None
  • Functions eliminate duplicated logic so fixes only need to happen in one place

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

Two small, single-purpose functions instead of repeating the width*height calculation inline everywhere it's needed.

Common pitfalls

  • Defining a function does not run it — a common early confusion is expecting output before calling it
  • Forgetting return means the function's result is silently None, even if it printed something internally

Practice exercise

Write a function is_palindrome(text) that returns True if text reads the same forwards and backwards, ignoring case, and call it with three different test strings.

Parameters, arguments and returning values

Parameters are placeholders in the definition; arguments are the actual values passed at call time.

A parameter is the name listed in a function's def line; an argument is the actual value supplied when the function is called — the distinction matters when reading error messages that mention one or the other. A function can return any single object, including a tuple, which is how a function appears to "return multiple values": return a, b actually returns one tuple (a, b) that the caller typically unpacks immediately with x, y = func(). return also exits the function immediately, so any code written after a return statement in the same block never executes.

Key points

  • Parameter = name in the def line; argument = actual value passed at call time
  • return a, b returns one tuple (a, b), typically unpacked by the caller
  • return exits the function immediately; later code in the same block never runs

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

Returning a tuple to give the appearance of multiple return values, unpacked at the call site.

Common pitfalls

  • Code placed after a return statement in the same branch is unreachable dead code
  • Calling min_max([4, 1, 9, 3]) but writing result = min_max(...) then treating result as two separate variables raises a mistake — you need explicit unpacking

Practice exercise

Write divide_with_remainder(a, b) that returns both the integer quotient and the remainder as a tuple, and unpack the result into two named variables at the call site.

Function signatures: defaults, args, kwargs, / and

How Python signatures control optional values, positional/keyword calling, variadic arguments and keyword-only or positional-only APIs.

A Python function signature can describe much more than required parameters followed by defaults. A default (timeout=10) makes a parameter optional. *args collects extra positional arguments into a tuple, while **kwargs collects extra keyword arguments into a dictionary. A / in the signature marks every parameter before it as positional-only; a bare * (or the presence of *args) makes following parameters keyword-only. These markers are useful when an API should prevent ambiguous calls or preserve freedom to rename an internal parameter later. At the call site, the reverse unpacking forms func(*sequence) and func(**mapping) spread positional and keyword arguments into a call. Variadic parameters should not be used merely to avoid designing a clear signature — explicit named parameters remain easier to discover and validate.

Key points

  • Defaults make parameters optional; args becomes a tuple and *kwargs becomes a dict
  • / marks earlier parameters positional-only, while * makes later parameters keyword-only
  • At the call site, sequence and *mapping unpack arguments into a function call
  • Prefer an explicit signature when the accepted inputs are known instead of hiding everything in args/*kwargs

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

One signature demonstrates positional-only input, args, a keyword-only timeout, *kwargs, and call-site unpacking.

Common pitfalls

  • A mutable default such as items=[] is created once and reused across calls; use None and create a new object inside
  • Passing a positional-only parameter by name or a keyword-only parameter positionally raises TypeError
  • Accepting arbitrary **kwargs can hide misspelled option names unless you validate the keys deliberately

Practice exercise

Write execute(command, /, args, cwd=None, timeout=30, *labels), call it directly, then call it once more by unpacking a tuple of positional values and a dictionary of keyword options.

Variable scope: local versus global

A variable created inside a function only exists inside that function, unless declared global.

A variable assigned inside a function is local to that function by default: it is created fresh on each call, and once the call ends its local name is no longer directly accessible from outside — though objects it referenced can still live on if something else keeps a reference to them (a returned value, or a closure, covered later in this path). A function can freely read a variable defined at module level (global scope) without any special declaration, but assigning to a name inside a function makes Python treat that name as local for the entire function body unless you explicitly write global name first — this is exactly the source of the common UnboundLocalError beginners hit when they try to modify a global counter from inside a function.

Key points

  • A variable assigned inside a function is local by default; its name is no longer accessible once the call ends
  • Reading a global variable from inside a function needs no special syntax
  • Assigning to a global variable from inside a function requires an explicit global declaration

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

Explicitly declaring global to modify a module-level counter from inside a function.

Common pitfalls

  • Removing global total_calls here makes total_calls += 1 raise UnboundLocalError
  • Overusing global variables makes functions harder to test and reason about in isolation — prefer passing values as arguments and returning results

Practice exercise

Write a function that tries to increment a global counter without declaring global, observe the UnboundLocalError, then fix it, and explain in one sentence why the error happened.

Source registry

2 chapter references
The Python Tutorial

Baseline syntax, control flow, functions and module basics

Python Software Foundation · Official documentation
Source ↗
The Python Language Reference

Precise scoping, evaluation order and expression semantics

Python Software Foundation · Official reference
Source ↗