Saturday, April 4, 2026

1.4 Gen AI: Python Refresher

 

1.4 Gen AI: Python Refresher

Sun, 29 Mar 26

Python Functions Overview

  • Functions are collections of related statements for specific actions

  • Execute only when called

  • Support both parameterized and non-parameterized functions

  • Key advantages:

    • Modularity - avoid monolithic code chunks

    • Enhanced comprehensibility and programming quality

    • Promote reusability across application

    • Improve scalability and ease of use

Function Syntax & Structure

  • Basic syntax: def function_name(arguments):

  • Function name can be any valid Python variable name

  • Arguments are optional (zero to multiple allowed)

  • Function calling requires matching the original structure

  • Example: def multiply_numbers(n1, n2): return n1 * n2

Function Arguments Types

  • Positional arguments: must match exact order from function definition

  • Keyword arguments: referenced by name, can be in any order

  • Can mix both positional and keyword arguments

  • Default values can be defined for arguments

  • Arbitrary arguments using *args (non-keyword) and **kwargs (keyword)

    • *args captures variable number of arguments into tuple

    • **kwargs allows named variables, works like dictionary mapping

Return vs Yield Statements

  • Return statement: passes control back to caller, destroys local variables

  • Yield statement: temporary transfer of control, preserves function state

  • Functions with yield statements are called generators

  • Generators return iterator objects with sequence of values

  • Can be used with next() function or for loops

Lambda Functions

  • Anonymous functions defined with lambda keyword

  • Syntax: lambda argument: expression

  • May have any number of arguments but only one expression

  • Reduce code length compared to regular function definitions

  • Example: add_10 = lambda x: x + 10

Built-in Functional Programming Methods

  • Map function: applies function to each element of iterable

    • Syntax: map(function, iterable)

    • Example: converting Celsius to Fahrenheit for temperature list

  • Filter function: filters data based on conditional function

    • Returns boolean values to determine inclusion

    • Example: filtering odd numbers using modulo operation

  • Reduce function: processes iterable to produce single cumulative value

    • Must import from functools: from functools import reduce

Variable Scope

  • Global scope: variables/functions defined outside all classes and functions

    • Accessible anywhere within the program

  • Local scope: variables/functions defined inside function blocks

    • Only accessible within that specific function

  • Analogy: global scope like company database (universal access), local scope like personal Excel file

No comments:

Post a Comment