04 - Libraries and modules
Libraries and modules
Learning Outcomes
By the end of this lecture, students will be able to:
Explain basics understanding of control structures and functions.
Identify benefits of control structures and functions in Python.
Write control structures and functions in Python.
Modules and the import Statement
We’ll create and use Python code in more than one file.
A module is just a file of any Python code.
You don’t need to do anything special—any Python code can be used as a module by
others.
We refer to code of other modules by using the Python import statement.
This makes the code and variables in the imported module available to your program.
1 import sys
2
3 print([Link])
Import a Module with Another Name.
1 import numpy as np
2 import pandas as pd
3 import [Link] as plt
Import Only What You Want from a Module
1 from sklearn.model_selection import train_test_split
2 from sklearn.model_selection import cross_val_score, cross_val_predict
Modules - The Web
HTTP (Hypertext Transfer Protocol) A protocol for web clients and servers to
interchange requests and responses.
HTML (Hypertext Markup Language) A presentation format for results.
URL (Uniform Resource Locator) A way to uniquely represent a server and a
resource on that server.
Python is a particularly good language for web work at every level:
Clients, to access remote sites
Servers, to provide data for websites and web APIs
Web APIs and services, to interchange data in other ways than viewable web
pages
Python’s Standard Web Libraries
Requests is a simple, yet elegant, HTTP library.
Beautiful Soup is a Python library for pulling data out of HTML and XML files.
Flask is a lightweight WSGI web application framework.
Requests and Beautiful Soup
Try running this code in colab:
1 import requests
2 from bs4 import BeautifulSoup
3
4 scraped_data = [Link]('[Link]
5
6 print(len(scraped_data.content))
7 soup = BeautifulSoup(scraped_data.content, '[Link]')
8 print([Link])
Web Development Prerequisite Tasks
Visual Studio Code - Code Editor
Windows
Microsoft Store
Mac
App Store
Direct Download
miniconda - Python command to install from thousands of packages
Windows
Mac
Intel
Apple Silicon
Run installation
Create conda environment
1 conda create -n is551 python=3.10
2 conda activate is551
Flask
1 pip install -U Flask
1 # save this as [Link]
2 from flask import Flask
3
4 app = Flask(__name__)
5
6 @[Link]("/")
7 def hello():
8 return "Hello, World!"
References
Lubanovic, B. (2019). Introducing Python: Modern Computing in Simple Packages.
O’Reilly Media.