Python Base Documentation

website·Indexed 31 days ago

https://anoguchi.github.io/albertonoguchi/

A comprehensive guide to Python fundamentals, covering primary and composite data types (integers, floats, strings, lists, tuples, sets, and dictionaries), function anatomy, lambda functions, built-in functions, and system interactions such as file management, environment variables, and input/output operations.

Tokens
17.3K
Snippets
132
Records
150
Agent score
75%

What's inside Python Base

  1. Use NoneType to represent the absence of a value

    The None object (of type NoneType) is used to initialize a variable when a value is not yet available but the variable must be defined. None is a singleton, meaning all variables assigned to None refer to the same object in memory. It is best practice to check for None using the is operator.
    produto = None
    
    if produto is None:
        produto = funcao_para_definicao_do_produto()
    
    # Demonstrating singleton behavior
    a = None
    b = None
    print(a is b)  # True
  2. Use Boolean types for flags and conditional logic

    The bool class represents two states: True and False. Booleans are typically used as flags to track states (e.g., user permissions or active status). In Python, many objects implement the __bool__ dunder method, allowing them to be evaluated directly in if statements. Comparison operations (like ==) return a bool object.
    # State flags
    is_admin = True
    continuar = False
    active = True
    
    # Conditional expression
    current_language = "en_US"
    if current_language == "pt_BR":
        print("Hello, World!")
    
    # Integers can be evaluated as booleans via __bool__
    if 500:
        print("Ok, 500 is an int that implements __bool__")
  3. Use Float for floating-point numbers in Python

    The float class is used to store numbers with decimal points (fractions). Python automatically treats a number as a float if it contains a decimal point. Common use cases include division results, geographic coordinates, and scoring systems. For monetary data, the specialized Decimal type is preferred over float to avoid precision issues.
    # Division result
    valor = 5 / 2  # 2.5
    
    # Geographic coordinates
    latitude = -37.80467681
    longitude = 144.9659498
    
    # Score balance
    pontos = 355.8
  4. Understand the role of programming languages and abstraction

    Computers and computational units (chips, phones) operate using binary format (sequences of 0s and 1s), where a single digit is a 'bit' and a sequence of 8 bits is a 'Byte'. Because writing binary is difficult for humans, programming languages provide layers of abstraction:

    • Low-Level Languages: Directly convert instructions to binary code; they typically have a more difficult and less natural syntax.
    • High-Level Languages: Use natural language (often English) to simplify instructions, utilizing multiple abstraction layers before reaching the final binary code.
  5. Use the int class for integer numbers in Python

    In Python, integer numbers are represented by the int class. Python uses dynamic type inference, meaning you do not need to explicitly declare the data type; the interpreter determines the class based on the value assigned. While you can explicitly cast a value using int(), it is generally considered redundant for literal integers.
    # Dynamic inference
    age = 25
    product_code = 4587
    quantity = 3
    
    # Verify type
    print(type(age))  # <class 'int'>
    
    # Explicit casting (redundant for literals)
    age = int(25)
  6. Understand Python variable scoping and namespaces

    In Python, a scope is similar to a namespace where names are defined. This prevents naming conflicts between identifiers. Python primarily uses local scopes (inside functions) and a global scope (the main program frame). Variables defined inside a function are local to that function and do not affect variables with the same name in the global scope.
    def func1():
        nome = 'local value'
        return nome
    
    def func2():
        nome = 'different local value'
        return nome
    
    print(func1()) # local value
    print(func2()) # different local value
  7. Compare Imperative and Functional programming styles in Python

    Python supports both imperative (procedural) and functional programming paradigms.

    • Imperative/Procedural: Focuses on step-by-step instructions and uses variable allocation to maintain program state.
    • Functional: Uses functions as first-class citizens (passing functions as arguments), composition, and recursion. It avoids variable allocation to prevent side effects.
    names = ["Bruno", "Joao", "Bernardo", "Barbara", "Brian"]
    
    # Functional Style: Using filter and lambda
    print(*list(filter(lambda text: text[0].lower() == "b", names)), sep="\n")
    
    # Procedural/Imperative Style: Using a named function and a loop
    def starts_with_b(text):
        return text[0].lower() == "b"
    
    filtro = list(filter(starts_with_b, names))
    for name in filtro:
        print(name)
  8. Role of the Python Software Foundation (PSF)

    The Python Software Foundation (PSF) is the international foundation responsible for protecting and managing Python's resources and rights. Because Python is open-source, the PSF handles brand copyright, evaluates language improvement proposals, and supports local communities rather than a single owning company.
  9. Understand Python object properties and memory abstraction

    In Python, every object is represented in memory by three fundamental properties: a value (the binary representation of the data), a type or class (which defines the operations and methods supported for that data), and a memory position (the unique address where the object is stored). This abstraction allows developers to interact with variables via identifiers (labels) without needing to manually manage binary data or specific memory addresses.