Functions in Python

Functions

  • A function is a group of related statements performing a specific task.
  • Functions break programs into smaller, manageable parts.
  • They enhance code organization and reusability, avoiding repetition.

Function Example

  • f(x)=15x2+4x+2f(x) = 15x^2 + 4x + 2
  • f(3)f(3) returns 149.
  • f: Function name.
  • Task: Solves the expression.
  • Reusable: Evaluates the expression each time it's called.
  • Actual parameter: The value passed to the function (e.g., 3).
  • Formal parameter: The parameter that receives the actual parameter (e.g., x).
  • Return value: The result of the function (e.g., 149), with a specific data type (e.g., int).

Types of Functions

  • Built-in functions: Pre-defined functions in Python.
  • User-defined functions: Functions created by users.

Python Built-in Functions

  • Always available for use.
  • Examples:
    • print(): Prints to the screen.
    • input(): Reads a line of string.
    • len(): Returns the length of an object.
    • pow(x,y): Returns xx to the power of yy.

User-defined Functions

  • Defined by the users.
  • Examples:
    • isEven(): Checks if a number is even.
    • greatestOfThree(): Finds the greatest of three numbers.

Syntax of a Python Function

def function_name(parameters):
    """docstring"""
    statement(s)
    return [expression_list]
  • def: Keyword marking the start of the function header.
  • function_name: Uniquely identifies the function.
  • parameters: Values passed to the function (optional).
  • :: Marks the end of the function header.
  • docstring: Optional documentation string describing the function.
  • Statements: Python statements forming the function body (same indentation level).
  • return: Optional statement to return a value from the function.

Function Call

  • Call a function from:
    • Another function.
    • The program.
    • The Python prompt.
  • To call: type the function name with appropriate parameters.
  • Example: greet(“Amna”)

Return Statement

  • return [expression_list]
  • A function will always return a value.
  • Can contain an expression to be evaluated and returned.
  • If no expression or return statement, the function returns None.
  • Exits the function and returns to the caller.

Scope and Lifetime of Variables

  • Scope: Portion of the program where the variable is recognized.
    • Variables defined inside a function are not visible outside (local scope).
  • Lifetime: Duration the variable exists in memory.
    • Variables inside a function exist as long as the function executes.
    • Variables are destroyed after the function returns.
    • Functions do not remember variable values from previous calls.

Function Arguments

  • A function can have multiple arguments.
  • Example:
def greet(name, msg):
    print("Hello", name + ', ' + msg)
  • name & msg are the formal arguments.