Dasar Pemrograman Python

website·Indexed 33 days ago

https://dasarpemrogramanpython.novalagung.com/

A comprehensive guide to Python programming basics, covering fundamental concepts such as variables, operators, data types (strings, dictionaries), and control flow (break, continue). It also explores advanced topics including decorators, pattern matching, data classes, duck typing, exception handling (try, except, else, finally), and module/package management using pip.

Tokens
49.9K
Snippets
350
Records
378
Agent score
54%

What's inside Python

  1. Overview of Python CSV API classes

    Python provides four primary classes in the csv module for interacting with tabular data:

    • csv.writer(): Writes sequences (lists/tuples) to a CSV file.
    • csv.DictWriter(): Writes dictionaries to a CSV file, mapping keys to headers.
    • csv.reader(): Reads CSV data as sequences.
    • csv.DictReader(): Reads CSV data as dictionaries, using the header row as keys.
  2. Technical stack for the ebook web-book and PDF generation

    The project uses a serverless architecture to generate both a web-based book and a PDF version. The tech stack consists of:

    • Web-book engine: Docusaurus v2
    • PDF generation: Prince XML, docusaurus-prince-pdf, and PDFtk
    • Repository: GitHub
    • Hosting: GitHub Pages
    • CI/CD: GitHub Actions
    • Search: Algolia DocSearch
  3. Understand Python Decorators basics

    A decorator is a syntax in Python, denoted by the @ symbol, placed immediately before a function or method declaration. It allows a developer to wrap another function to extend its behavior without permanently modifying its source code. Python provides built-in decorators such as @classmethod (to mark a method as a class method) and @staticmethod (to mark a method as a static method).
  4. Implement Duck Typing in Python

    Duck typing is a concept in dynamic programming where an object is validated based on whether it possesses specific methods or attributes (the 'behavior') rather than its actual class type. If an object has the required method name and parameter schema, it is considered valid for the operation, regardless of whether it is an instance method, a closure, a lambda, or a class method.
    # The consumer function only cares if the object has 'calculate_area()'
    def do_the_math(obj):
        area = obj.calculate_area()
        print(f"area of {type(obj).__name__}: {area}")
    
    # Scenario 1: Standard Instance Method
    class Triangle:
        def __init__(self, b, h):
            self.b = b
            self.h = h
        def calculate_area(self):
            return 1/2 * self.b * self.h
    
    # Scenario 2: Attribute containing a closure
    def number_10():
        return 10
    
    class AreaOf2x10:
        def __init__(self) -> None:
            self.calculate_area = number_10
    
    # Scenario 3: Attribute containing a lambda
    import random
    class AreaOfRandomInt:
        def __init__(self) -> None:
            self.calculate_area = lambda : random.randint(0, 10) * 2
    
    # Scenario 4: Class Method (passing the class itself instead of an instance)
    class NotReallyA2dObject:
        @classmethod
        def calculate_area(cls):
            return "where is the number?"
    
    # All of these work because they all provide a 'calculate_area' callable
    do_the_math(Triangle(4, 10))
    do_the_math(AreaOf2x10())
    do_the_math(AreaOfRandomInt())
    do_the_math(NotReallyA2dObject)
  5. Understand and use the None object in Python

    None is a built-in Python object used to represent a null value or an empty state. It is distinct from other 'empty' values such as the integer 0 or an empty string "". A variable is only considered truly empty in this context when it is explicitly assigned the value None.
    def inspect_data(data):
        if data is None:
            print("data is empty. like very empty")
        else:
            print(f"data: {data}, type: {type(data).__name__}")
    
    inspect_data(0)      # output ➜ data: 0, type: int
    inspect_data("")     # output ➜ data: , type: str
    inspect_data(None)   # output ➜ data is empty. like very empty
  6. Understand Python object IDs and memory references

    In Python, the id() function returns a unique identifier for an object, which represents its address in memory. When a sequence (like a list) is assigned from one variable to another, both variables point to the same object in memory. Consequently, mutating the object via one variable (e.g., using .append()) will reflect the change in all variables referencing that same object, and the object ID remains constant during these mutations.
    numbers1 = [1, 2, 3, 4]
    numbers2 = numbers1
    
    print(id(numbers1)) # Example: 2269649131136
    print(id(numbers2)) # Example: 2269649131136
    
    numbers2.append(9)
    print(numbers1) # Output: [1, 2, 3, 4, 9]
  7. Access Python Programming tutorial resources

    The 'Dasar Pemrograman Python' tutorial provides several resources for learning Python 3.12.0, including a downloadable PDF ebook, the website source code, and a dedicated repository for practice program source code.
    - PDF Ebook: https://github.com/novalagung/dasarpemrogramanpython/raw/ebooks/dasarpemrogramanpython.pdf
    - Website Source Code: https://github.com/novalagung/dasarpemrogramanpython
    - Practice Source Code: https://github.com/novalagung/dasarpemrogramanpython-example
  8. Understand Iterables in Python

    An Iterable is any Python object that can be looped over using a for in loop. Common examples of iterables include strings, lists, and tuples. Iteration is the process of accessing these collective data items one by one in sequence.
    condition = "weteng luwe"
    for c in condition:
        print(c)
    
    numbers = [10, 12, 32, 44]
    for n in numbers:
        print(n)
  9. Choose a Python Editor or IDE

    There are numerous editors and Integrated Development Environments (IDEs) available for Python development. Popular options include:

    • JetBrains PyCharm
    • Visual Studio Code (VSCode)
    • Visual Studio
    • Spyder
    • Sublime Text (with Python package)
    • Eclipse (with PyDev plugin)
    • GNU Emacs
    • Vim

    For interactive development and shell-based execution, you can use the Python standard shell (REPL) or Jupyter.

  10. Parse ISO 8601 strings using datetime.fromisoformat()

    For strings that follow the ISO 8601 (ISO Date Time) specification, use datetime.fromisoformat() for a practical and direct conversion to a datetime object.
    from datetime import datetime
    
    # Without timezone
    data_datetime = datetime.fromisoformat('1985-04-12T23:20:50.52')
    
    # With timezone offset
    data_datetime = datetime.fromisoformat('1985-04-12T23:20:50.52+0700')
  11. Use the finally block for cleanup

    The finally block is executed regardless of whether an exception was raised or caught. It is used to mark the end of the exception handling process and is typically used for cleanup actions (e.g., closing files or network connections).
    try:
        # code that might raise exception
        res = 10 / 2
    except Exception as err:
        print(f"Error: {err}")
    finally:
        print("program completed") # Always executes
  12. Add instance methods to a data class

    Data classes support instance methods. They are declared exactly like methods in standard Python classes.
    from dataclasses import dataclass
    
    @dataclass
    class Country:
        name: str
        seasons: list
        number_of_population: float
        
        def info(self) -> str:
            return f"{self.name} | {len(self.seasons)} seasons | {self.number_of_population} million population"
    
    c = Country("Indonesia", ["Rainy", "Dry"], 275.5)
    print(c.info())