Python Modules

Python Modules

Python Modules

Introduction

  • Modules are files containing Python code.
  • They help organize code logically and enable code reuse.
Python Modules

The import Statement

  • Use import to include a module.
  • Syntax:
    import module_name
    
  • Example:
    import sys
    print(sys.argv)
    
Python Modules

from ... import Statement

  • Import specific attributes from a module.
  • Syntax:
    from module_name import attribute_name
    
  • Example:
    from math import sqrt
    print(sqrt(16))
    
Python Modules

as Keyword

  • Alias module or attribute names.
  • Syntax:
    import module_name as alias
    
  • Example:
    import math as m
    print(m.sqrt(16))
    
Python Modules

Built-in Modules

  • Python includes many useful built-in modules.
  • Examples: sys, os, time, math, csv, random, re, datetime, and more...
Python Modules

Writing Modules

  • Create a mymodule.py file with functions and variables.

    def say_hi():
        print('Hello!')
    
  • Usage:

    import mymodule
    mymodule.say_hi()
    
Python Modules

__name__ Attribute

  • Check if a module is run directly or imported.
  • Example:
    if __name__ == "__main__":
        # This block runs only when the module is executed directly
        print("Module is run directly")
    else:
        print("Module is imported")
    
  • You won't see this in Google Colab, but you will if you start writing Python for things like games and web apps.
Python Modules

JSON

  • Encode and decode JSON data.
  • Example:
    import json
    
    data = {'name': 'Alice', 'age': 25}
    json.dumps(data)
    
    '{"name": "Alice", "age": 25}'
    
Python Modules

PPrint

  • Pretty print data structures.
  • Example:
    from pprint import pprint
    
    data = {'name': 'Alice', 'age': 25}
    pprint(data)
    
    {'age': 25,
     'name': 'Alice'}
    
Python Modules

Datetime

  • Work with dates and times.
  • Example:
    from datetime import datetime  # This one is weird
    
    now = datetime.now()
    
    hp_birthday = datetime(1980, 7, 31)
    hp_seconds_alive = (now - hp_birthday).total_seconds()
    
Python Modules

Summary

  • Modules help organize and reuse code.
  • Use import, from ... import, and as to work with modules.
  • Built-in and custom modules enhance functionality.
Python Modules

Exercise

http://gg.gg/1b8kph