# Nakafa Framework: LLM URL: /en/subject/university/bachelor/ai-ds/ai-programming/function Source: https://raw.githubusercontent.com/nakafaai/nakafa.com/refs/heads/main/packages/contents/subject/university/bachelor/ai-ds/ai-programming/function/en.mdx Output docs content for large language models. --- export const metadata = { title: "Functions", description: "Master Python functions: parameters, return values, variable scope, closures, error handling. Complete guide with tested code examples for AI programming students.", authors: [{ name: "Nabil Akbarazzima Fatih" }], date: "09/18/2025", subject: "AI Programming", }; ## Basic Function Concepts Functions in Python are blocks of code that can be used repeatedly to perform specific tasks. Imagine a function like an automatic coffee machine where you provide ingredients (input), then the machine processes and produces coffee (output). Every time you want coffee, you don't need to create a new machine, just use the same machine. In programming, functions help us avoid writing the same code repeatedly. Functions have names, can accept parameters (input data), and can return values. ## Function Structure and Syntax Every function in Python has a basic structure consisting of several important components. Function components consist of: 1. The `def` keyword to start function definition 2. Function name that follows Python variable naming rules 3. Parentheses containing parameter list (can be empty) 4. Colon to end the definition line 5. Indented code block 6. Optional `return` statement to return a value ## How Function Calls Work When you call a function, Python will execute the code inside that function. Let's look at a simple example of how functions work. Process that occurs during function call: 1. Python searches for the function definition with the called name 2. Given arguments are sent to function parameters 3. Code inside the function is executed 4. If there's a `return`, the value is returned to the calling location ## Parameters and Arguments Parameters are variables defined in functions, while arguments are actual values sent when calling functions. Python provides several types of parameters for greater flexibility. ### Positional and Keyword Parameters Important rules in parameter usage: 1. Positional parameters must be given in order 2. Keyword parameters can be given in any order 3. Positional parameters must be written before keyword parameters 4. Parameters with default values are optional ### Variable Number of Parameters Python allows functions to accept unlimited number of arguments using `*args` and `**kwargs`. Parameter `*args` collects additional positional arguments into a tuple, while `**kwargs` collects additional keyword arguments into a dictionary. ## Function Return Values Functions can return values using the `return` statement. If there's no `return` or `return` without a value, the function will return `None`. ## Variable Scope in Functions Variables in Python have scope that determines where variables can be accessed. Understanding variable scope is important to avoid errors in programs. B[Global Scope] B --> C[Enclosing Scope] C --> D[Local Scope] A1[Python built-in functions print, len, range] --> A B1[Variables outside functions can be accessed anywhere] --> B C1[Variables in outer functions for nested functions] --> C D1[Variables inside functions can only be accessed locally] --> D `} /> ### Local and Global Variables Variable lookup rules follow LEGB order: 1. **Local** - inside current function 2. **Enclosing** - in enclosing function (for nested functions) 3. **Global** - at module level 4. **Built-in** - Python built-in names ## Functions as First-Class Objects In Python, functions are first-class objects, meaning functions can be treated like other data. You can store functions in variables, pass functions as arguments, or return functions from other functions. ## Function Documentation with Docstring Docstring is a string literal that appears as the first statement in a function definition. Docstring serves as documentation to explain the purpose and usage of the function. >> calculate_factorial(5) 120 >>> calculate_factorial(0) 1 """ if not isinstance(n, int): raise TypeError("Input must be an integer") if n < 0: raise ValueError("Input must be positive or zero") if n <= 1: return 1 return n * calculate_factorial(n - 1) # Access docstring print(calculate_factorial.__doc__) # Use function print(calculate_factorial(5)) # Output: 120 print(calculate_factorial(0)) # Output: 1` } ]} /> Good docstring writing conventions: 1. First line contains brief function summary 2. If detailed explanation is needed, separate with blank line 3. Explain parameters, return values, and possible exceptions 4. Provide usage examples if helpful ## Nested Functions and Closure Python allows function definitions inside other functions. Inner functions can access variables from outer functions, creating a concept called closure. ## Error Handling in Functions Good functions should be able to handle error situations gracefully. Python provides exception handling mechanisms to handle possible errors.