The import statement

Import statements are used to bring in external modules or libraries into your code. Modules are pre-written code files that contain functions, classes, and variables that you can use in your program. Importing modules allows us to access their functionality and leverage their capabilities.

To use an import statement, you simply write the import keyword followed by the name of the module you want to import. Here are some examples:

  1. Importing the random module to generate random numbers:
    import random
    
    print(random.randint(1, 10))  # Output: Random number between 1 and 10
  2. Importing the datetime module to work with dates and times:
    import datetime
    
    current_time = datetime.datetime.now()
    print(current_time)  # Output: Current date and time
  3. Importing the os module to interact with the operating system:
    import os
    
    print(os.getcwd())  # Output: Current working directory
  4. Importing the csv module to read and write CSV files:
    import csv
    
    # Data to be written to the CSV file
    data = [
       ['Name', 'Age', 'City'],
       ['Alice', 25, 'New York'],
       ['Bob', 30, 'Los Angeles'],
       ['Charlie', 35, 'Chicago']
    ]
    
    # Specify the file name
    file_name = 'example.csv'
    
    # Write data to the CSV file
    with open(file_name, mode='w', newline='') as file:
       writer = csv.writer(file)
       writer.writerows(data)
    
    # Read content from the generated file
    with open(file_name, 'r') as file:
        reader = csv.reader(file)
        for row in reader:
            print(row)  # Output: Each row of the CSV file

There are numerous modules available in the Python standard library and in external libraries that can be imported to to access their specific functionality in your code.

Next, learn how importing the math module makes it easy to perform mathematical operations in Python.