Python Programming Tutorial

website·Indexed 32 days ago

https://python.yxzl.dev/

A comprehensive Python tutorial covering fundamental concepts including variables, data types, control flow (if, for, while), functions, and object-oriented programming. It includes guides on using the PyPI package manager, virtual environments, and built-in libraries such as os, pathlib, random, and base64, as well as the requests library for HTTP requests.

Tokens
24.1K
Snippets
167
Records
193
Agent score
62%

What's inside Python

  1. Overview of Base64 encoding

    Base64 is a common encoding method used to transmit binary content within text-based protocols (e.g., embedding image binaries directly in HTML). Note that Base64 is easily decoded and must not be used as a form of encryption. Additionally, Base64 encoded strings occupy significantly more space than the original data, making it unsuitable for very large files.
  2. Understand the advantages and use cases of Python

    Python is a versatile interpreted language characterized by a syntax that closely resembles natural language, making it accessible for learners and easy to debug. It is suitable for a wide range of applications, including web development, GUI design, web scraping, and artificial intelligence. A key strength is the PyPI package manager, which simplifies the installation and management of third-party libraries. While it may not be the primary choice for extremely large-scale projects due to its nature as a scripting language, it is highly effective for increasing productivity and is used by major platforms such as Zhihu, Douban, Facebook, and Instagram.
  3. Retrieve path and file metadata

    Use Path object properties to extract details about a file or directory. To get detailed system statistics (like size and modification time), use the .stat() method. Note that .stat() will raise a FileNotFoundError if the path does not exist.
    from pathlib import Path
    
    path = Path(__file__)
    
    # Basic checks
    print(path.exists())   # True/False
    print(path.is_file())   # True if it's a file
    print(path.is_dir())    # True if it's a directory
    
    # Path components
    print(path.name)        # Filename (e.g., 'main.py')
    print(path.stem)        # Filename without extension (e.g., 'main')
    print(path.suffix)       # Extension (e.g., '.py')
    print(path.parent)       # Parent directory
    print(list(path.parents)) # List of all parent directories
    
    # System stats
    stats = path.stat()
    print(stats.st_size)     # File size in bytes
    print(stats.st_mtime)    # Modification time
  4. Use common Python basic data types

    Python supports several fundamental data types:

    • int: Arbitrary-precision integers (no size limit).
    • float: Floating-point numbers (decimals).
    • str: Strings of characters, enclosed in single (') or double (") quotes. Python does not have a separate 'char' type.
    • bool: Boolean values, either True or False.
    • None: A special type representing the absence of a value.
    a = 1           # int
    b = 3.14        # float
    c = 'Hello'     # str
    d = True        # bool
    e = None        # NoneType
  5. Understand the Python tutorial learning path and constraints

    This Python documentation is specifically designed for individuals with no prior coding experience but basic computer literacy. It employs a non-traditional learning sequence to reduce dependency between concepts, introducing strings and lists before loop statements and logical operations. To lower the entry barrier, some concepts are initially simplified (e.g., using functions to explain type conversion before introducing classes), with detailed corrections provided in footnotes to prevent long-term misconceptions.
  6. Extract information from HTTP requests and responses

    After making a request, you can access metadata about both the sent request and the received response using the response object.
    import requests as rq
    
    r = rq.get('https://httpbin.org/get')
    
    # Request Information
    print(r.request.headers)  # Sent headers (dict)
    print(r.request.method)   # HTTP method (str)
    print(r.request.url)      # Request URL (str)
    print(r.request.body)     # Request body (str|None)
    
    # Response Information
    print(r.status_code)      # Status code (int)
    print(r.content)          # Raw binary content (bytes)
    print(r.text)             # Decoded text content (str)
    print(r.json())           # Parsed JSON data (dict)
    print(r.headers)          # Response headers (dict)
    print(r.cookies)          # Response cookies
    print(r.url)              # Final URL after redirects (str)
    print(r.history)          # Redirect history (list)
    print(r.encoding)         # Response encoding (str)
  7. Understand Python Magic Methods

    Magic methods, also known as dunder methods (double underscore methods), are special methods in Python that are called automatically by the interpreter when specific events occur. They allow developers to customize class behavior for built-in operations like arithmetic, iteration, and object lifecycle management. Overriding these methods enables a class to implement standard Python protocols.
  8. Understand the concepts of Classes and Objects

    In object-oriented programming, a Class is an abstract template that describes the behavior and state of a group of objects. An Object is a concrete instance of a class.

    Key distinctions:

    • State: In the real world, state refers to characteristics (e.g., a dog's name, breed, or color). In programming, state is represented by attributes (properties).
    • Behavior: In the real world, behavior refers to actions (e.g., a dog barking or running). In programming, behavior is implemented via methods.

    Crucially, objects must be created based on a class; a class remains an abstract template until it is instantiated into an object.

  9. Retrieve system and hardware information using the platform module

    The platform module is a built-in Python library used to access identifying information about the underlying operating system and hardware. While the documentation notes that production environments can be complex and results may vary, platform.system() is recommended as a reliable way to determine the operating system type.
    import platform
    
    # Get general OS and version information
    print(f"OS Platform: {platform.platform()}")
    
    # Get specific system details
    print(f"System Version: {platform.version()}")
    print(f"System Name: {platform.system()}")
    print(f"Architecture: {platform.architecture()}")
    print(f"Machine Type: {platform.machine()}")
    print(f"Network Node Name: {platform.node()}")
    print(f"Processor Type: {platform.processor()}")
    
    # Get a comprehensive named tuple of system info
    print(f"System Summary: {platform.uname()}")
    
    # Get Python interpreter details
    print(f"Python Build: {platform.python_build()}")
    print(f"Python Version: {platform.python_version()}")
  10. Understand Python's 'Everything is an Object' philosophy

    In Python, all data types—including basic types (str, int, float, bool, list, dict), constants like True, and even functions—are objects instantiated from classes. This means they possess methods defined by their respective classes (e.g., strings have the .upper() method).
    # Basic types are classes
    print(type('abc'))    # <class 'str'>
    print(type(123))      # <class 'int'>
    print(type(True))     # <class 'bool'>
    
    # Functions are also objects
    def f():
        pass
    print(type(f))        # <class 'function'>
    
    # Verifying base types are classes
    print(str, int, float, bool, list, dict)
    # <class 'str'> <class 'int'> <class 'float'> <class 'bool'> <class 'list'> <class 'dict'>
  11. Python study guide for High School Academic Proficiency Test (Shandong)

    For students preparing for the High School Academic Proficiency Test (specifically in the Shandong region), focus on the following Python core concepts: print statements, variables and data types, numerical operations, input statements, logical operations (excluding membership operators), if statements, while loops, and the specific use of 'for i in range' loops.
  12. Implement basic loops using the while statement

    The while statement repeatedly executes a block of code as long as a specified condition expression evaluates to True. If the expression is not a boolean, Python performs a truthiness conversion (similar to if statements). Once the condition becomes False, the loop terminates.
    cnt = 0
    while cnt <= 3:
    	print(cnt)
    	cnt += 1