☰
Python Across Disciplines
with Python + AI Tool   
×
Table of Contents

1.1.   Introduction 1.2.   About the Author & Contact Info 1.3.   Book Conventions 1.4.   What (Who) is a Programmer? 1.5.   Programming Across Disciplines 1.6.   Foundational Computing Concepts 1.7.   About Python 1.8.   First Steps 1.8.1 Computer Setup 1.8.2 Python print() Function 1.8.3 Comments
2.1. About Data 2.2. Data Types 2.3. Variables 2.4. User Input 2.5. Data Structures (DS)         2.5.1. DS Concepts         2.5.2. Lists         2.5.3. Dictionaries         2.5.4. Others 2.6. Files         2.6.1. Files & File Systems         2.6.2. Python File Object         2.6.3. Data Files 2.7. Databases
3.1. About Processing 3.2. Decisions         3.2.1 Decision Concepts         3.2.2 Conditions & Booleans         3.2.3 if Statements         3.2.4 if-else Statements         3.2.5 if-elif-else Statements         3.2.6 In-Line if Statements 3.3. Repetition (a.k.a. Loops)         3.3.1  Repetition Concepts         3.3.2  while Loops         3.3.3  for Loops         3.3.4  Nested Loops         3.3.5  Validating User Input 3.4. Functions         3.4.1  Function Concepts         3.4.2  Built-In Functions         3.4.3  Programmer Defined Functions 3.5. Libraries         3.5.1  Library Concepts         3.5.2  Standard Library         3.5.3  External Libraries 3.6. Processing Case Studies         3.6.1  Case Studies         3.6.2  Parsing Data
4.1. About Output 4.2. Advanced Printing 4.3. Data Visualization   4.4  Sound
  4.5  Graphics
  4.6  Video
  4.7  Web Output
  4.8  PDFs & Documents
  4.9  Dashboards
  4.10  Animation & Games
  4.11  Text to Speech

5.1 About Disciplines 5.2 Accounting 5.3 Architecture 5.4 Art 5.5 Artificial Intelligence (AI) 5.6 Autonomous Vehicles 5.7 Bioinformatics 5.8 Biology 5.9 Bitcoin 5.10 Blockchain 5.11 Business 5.12 Business Analytics 5.13 Chemistry 5.14 Communication 5.15 Computational Photography 5.16 Computer Science 5.17 Creative Writing 5.18 Cryptocurrency 5.19 Cultural Studies 5.20 Data Analytics 5.21 Data Engineering 5.22 Data Science 5.23 Data Visualization 5.24 Drone Piloting 5.25 Economics 5.26 Education 5.27 Engineering 5.28 English 5.29 Entrepreneurship 5.30 Environmental Studies 5.31 Exercise Science 5.32 Film 5.33 Finance 5.34 Gaming 5.35 Gender Studies 5.36 Genetics 5.37 Geography 5.38 Geology 5.39 Geospatial Analysis ☯ 5.40 History 5.41 Humanities 5.42 Information Systems 5.43 Languages 5.44 Law 5.45 Linguistics 5.46 Literature 5.47 Machine Learning 5.48 Management 5.49 Marketing 5.50 Mathematics 5.51 Medicine 5.52 Military 5.53 Model Railroading 5.54 Music 5.55 Natural Language Processing (NLP) 5.56 Network Analysis 5.57 Neural Networks 5.58 Neurology 5.59 Nursing 5.60 Pharmacology 5.61 Philosophy 5.62 Physiology 5.63 Politics 5.64 Psychiatry 5.65 Psychology 5.66 Real Estate 5.67 Recreation 5.68 Remote Control (RC) Vehicles 5.69 Rhetoric 5.70 Science 5.71 Sociology 5.72 Sports 5.73 Stock Trading 5.74 Text Mining 5.75 Weather 5.76 Writing
6.1. Databases         6.1.1 Overview of Databases         6.1.2 SQLite Databases         6.1.3 Querying a SQLite Database         6.1.4 CRUD Operations with SQLite         6.1.5 Connecting to Other Databases
Built-In Functions Conceptss Data Types Date & Time Format Codes Dictionary Methods Escape Sequences File Access Modes File Object Methods Python Keywords List Methods Operators Set Methods String Methods Tuple Methods Glossary Index Appendices   Software Install & Setup
  Coding Tools:
  A.  Python    B.  Google CoLaboratory    C.  Visual Studio Code    D.  PyCharm IDE    E.  Git    F.  GitHub 
  Database Tools:
  G.  SQLite Database    H.  MySQL Database 


Python Across Disciplines
by John Gordon © 2023

Table of Contents

Table of Contents  »  Chapter 3 : Processing : Libraries : Standard Library

Standard Library

Subscribe Contact


Contents

Overview

The Python Standard Library is a collection of modules and packages that come bundled with every installation of Python. These modules and packages contain a wide range of functions and tools used to perform various tasks, from reading and writing files to generating random numbers.

The Standard Library is divided into several categories, each containing modules and packages related to a specific area of functionality. Here are some examples of categories and the modules/packages they contain:

These are just a few examples of the many modules and packages available in the Python Standard Library. By using the Standard Library, developers can save time and effort by reusing pre-existing code rather than writing everything from scratch. Additionally, since the Standard Library is part of the Python distribution, no external dependencies or installation requirements necessary to use it.

For a complete list of the built-in functions and the official Python documentation for each, you can visit docs.python.org.

Date/Time Module

There are many circumstances in programming that require working with dates and times. Working with data types like integers, floats, and strings is straightforward as we saw on the previous pages of this book. Dates and times are a bit different because they are not simply numbers or strings; they embody more complicated concepts like other date formats, for example:

Also, formats are different in different countries for example the standard format in the United States is month/day/year, while some other countries format their dates day/month/year. In addition, we also have to take into account daylight savings time, leap years, and different timezones, as well. To complicate things a bit more, we often need to calculate the span of time between dates and time ranges, setting alarms and scheduling processes, all of which depend on programmatically determining how much time has passed or when a particular date/time has arrived.

The Standard Library Datetime Module provides numerous date/time functions. You can find a complete list of the available functions in the module here. Let's take a look at a few of them (see the comments in the code examples below for explanations). Pay particular attention to the syntax of the import statement and how we call the functions.

# import the datetime module
# Note the use of an alias with "as"
import datetime as dt

# Print the current date
print(dt.date.today())
# Print the current date and time
print(dt.datetime.now())

# Capture the Current date and time in a variable
now = dt.datetime.now()
print(f"Current date and time: {now}")

# Get the Current date
current_date = now.date()
print(f"Current date: {current_date}")

# Get the current time
current_time = now.time()
print(f"Current time: {current_time}")

# Capture and print parts of the date
year = now.year
month = now.month
day = now.day
print(f"Year: {year}")
print(f"Month: {month}")
print(f"Day: {day}")

# Create a date (YYYY, MM, DD)
specific_date = dt.date(2025, 1, 1)
print(f"Specific date: {specific_date}")

# Create a time (HH, MM, SS)
specific_time = dt.time(15, 30, 45)  # 3:30:45 PM
print(f"Specific time: {specific_time}")

# Get a delta (time difference)
delta = dt.timedelta(days=10)  # A difference of 10 days
print(delta)

# Add 10 days to current date
new_date = current_date + delta
print(f"Date after 10 days: {new_date}")

# Subtract 10 days from current date
previous_date = current_date - delta
print(f"Date 10 days ago: {previous_date}")

Output

2023-11-05
2023-11-05 15:50:59.241292
Current date and time: 2023-11-05 15:50:59.241948
Current date: 2023-11-05
Current time: 15:50:59.241948
Year: 2023
Month: 11
Day: 5
Specific date: 2025-01-01
Specific time: 15:30:45
10 days, 0:00:00
Date after 10 days: 2023-11-15
Date 10 days ago: 2023-10-26

Another of the datetime module features is the strftime() method that converts and formats date objects into readable strings through the use of directives. These directives indicate the format you want your converted string to contain. You can find a full list of the strftime() directives here. Here are some examples:

# import the datetime module
# Note the use of an alias with "as"
import datetime as dt
# Get the current date and time
now = dt.datetime.now()
print(now)
print(now.strftime("%a"))  # Weekday, short
print(now.strftime("%A"))  # Weekday, full
print(now.strftime("%w"))  # Weekday, number
print(now.strftime("%d"))  # Day of month
print(now.strftime("%b"))  # Month name, short
print(now.strftime("%B"))  # Month name, full
print(now.strftime("%m"))  # Month number
print(now.strftime("%y"))  # Year, short
print(now.strftime("%Y"))  # Year, full
print(now.strftime("%p"))  # AM or PM
print(now.strftime("%c"))  # Local date, full
print(now.strftime("%x"))  # Local date, short

Output

2023-11-05 16:16:41.428216
Sun
Sunday
0
05
Nov
November
11
23
2023
PM
Sun Nov  5 16:16:41 2023
11/05/23

Math Module

The Standard Library Math Module provides numerous mathematical functions. You can find a complete list of the available functions in the module here. Let's look at a few of them (see the comments in the code examples below for explanations). Please pay particular attention to the syntax of the import statement and how we call the functions.

import math

# math.pow(x, y) raises x to the power of y.
print(math.pow(2, 4))

# math.sqrt(x) returns the square root of x.
print(math.sqrt(144))

# math.pi is a constant (a value that never
# changes). This is an example of using a
# a constant in the module as part of a
# calculation in our program - the area
# of a circle.
circle_radius = 20
print(math.pi * circle_radius**2)

# math.factorial(x) returns the factorial
# value of x. Factorial is annotated as x!
# and is calculated by multiplying all whole
# numbers from x down to 1, like this:
# 5! = 5 * 4 * 3 * 2 * 1 = 120
print(math.factorial(10))

Output

16.0
12.0
1256.6370614359173
3628800

Platform Module

The Standard Library Platform Module provides access to the platform (operating system) that your program is running on. This information can be essential since Python is cross-platform, but different platforms have differences (for example, the way file paths work). We can use the Platform Module to detect what platform our program is running on and adjust accordingly. You can find a full list of the available functions in the module here. Let's take a look at some of them:

import platform

print("\nOperating System:\t" + platform.system())
print("OS Release:\t\t\t" + platform.release())
print("OS Version:\t\t\t" + platform.version())
print("Machine Type:\t\t" + platform.machine())
print("Node Name:\t\t\t" + platform.node())
print("UName Tuple:\t\t" + str(platform.uname()))
print("Platform:\t\t\t" + platform.platform())
print("Processor:\t\t\t" + platform.processor())
print("Python Build:\t\t" + str(platform.python_build()))
print("Python Compiler:\t" + platform.python_compiler())
print("Python Version:\t\t" + platform.python_version())

Example Output: I ran this program on my Windows computer, my Linux computer, and my Mac computer. Here are the results of each (Yes, my computers are named after LOTR characters):

Windows computer

Operating System: Windows
OS Release:       10
OS Version:       10.0.19041
Machine Type:     AMD64
Node Name:        Gandalf
UName Tuple:      uname_result(system='Windows', node='Gandalf', release='10',
  version='10.0.19041', machine='AMD64')
Platform:         Windows-10-10.0.19041-SP0
Processor:        Intel64 Family 6 Model 142 Stepping 12, GenuineIntel
Python Build:     ('tags/v3.9.4:1f2e308', 'Apr  6 2021 13:40:21')
Python Compiler:  MSC v.1928 64 bit (AMD64)
Python Version:   3.9.4

Linux computer

Operating System: Linux
OS Release:       5.4.0-47-generic
OS Version:       #51~18.04.1-Ubuntu SMP Sat Sep 5 14:35:50 UTC 2020
Machine Type:     x86_64
Node Name:        gimli
UName Tuple:      uname_result(system='Linux', node='gimli',
  release='5.4.0-47-generic', version='#51~18.04.1-Ubuntu
  SMP Sat Sep 5 14:35:50 UTC 2020', machine='x86_64')
Platform:         Linux-5.4.0-47-generic-x86_64-with-glibc2.27
Processor:        x86_64
Python Build:     ('default', 'Apr  9 2021 01:10:48')
Python Compiler:  GCC 7.5.0
Python Version:   3.9.4

Mac Computer


Operating System: Darwin
OS Release:       20.3.0
OS Version:       Darwin Kernel Version 20.3.0: Thu Jan 21 00:07:06
  PST 2021; root:xnu-7195.81.3~1/RELEASE_X86_64
Machine Type:     x86_64
Node Name:        Frodo.local
UName Tuple:      uname_result(system='Darwin', node='Frodo.local',
  release='20.3.0', version='Darwin Kernel Version 20.3.0:
  Thu Jan 21 0:07:06 PST 2021;
  root:xnu-7195.81.3~1/RELEASE_X86_64', machine='x86_64')
Platform:         macOS-10.16-x86_64-i386-64bit
Processor:        i386
Python Build:     ('v3.9.4:1f2e3088f3', 'Apr  4 2021 12:32:44')
Python Compiler:  Clang 6.0 (clang-600.0.57)
Python Version:   3.9.4

Example of Using Platform Information in Your Program

As mentioned above, our program might be running on any operating system because Python is cross-platform. If we need to adjust something in our program depending on the OS platform, here's a simple example framework example that we could use to handle this situation:

import platform

if platform.platform().startswith("Windows"):
    # Run Windows-specific code here ...
    print("Windows OS")
elif platform.platform().startswith("Linux"):
    # Run Linux-specific code here ...
    print("Linux OS")
elif platform.platform().startswith("macOS"):
    # Run Mac-specific code here ...
    print("MAC OS")
else:
    # Do something else because this is not
    # running on a Windows, Linux, or Mac computer.
    print("Don't know what OS this is!")

Random Module

The Standard Library Random Module provides pseudo-random number generation. You can find a complete list of the available functions in the module here. Let's look at a couple of examples of using the random module (see the comments in the code examples below for explanations).

import random

# random.randomint(x, y) returns a random integer between
# the values of x and y. Mathematically this would be
# stated as x <= r <= y, where r is a random integer.
# Notice that since this generates random numbers between
# 1 and 6, we could use this as a dice roll simulation.
print(random.randint(1, 6))
print()

# Let's use randomint(x, y) again, this time we'll call it
# numerous times to see the random nature more clearly.
min_num = 1
max_num = 6
for i in range(10):
    print(random.randint(min_num, max_num))
print()

# random.randrange(start, stop[,step]) returns a random
# integer between the values of start and stop. Optionally
# we can add a step value to that limits the possible
# return values to only the values specified by step,
# within the start stop range. Here are a few examples:
print(random.randrange(5, 20))  # returns a random integer
# in this range: 5 <= r <= 20.
print()
print(random.randrange(0, 100, 10))     # returns a random
# integer in the range 0 <= r <= 100, but the possible
# values between 1 and 100 is limited by the step value of
# 10, so we will only get back one of these values in the
# range: 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100.

Example Output

Note: Since we use a random function, the output values will differ each time we run this code.

4

2
5
5
3
2
3
3
3
6
6

8

70

Turtle Module

The Standard Library Turtle Module provides simple graphics capabilities. You can find a complete list of the available functions in the module here. Let's look at a few of them (see the comments in the code examples below for explanations). Please pay particular attention to the syntax of the import statement and how we call the functions.

import turtle

# Turtle graphics allow us to draw lines and
# shapes in various colors. This example uses
# a loop to draw lines and adjust each new
# line's position slightly so that the result
# is a concentric shape.
# We use a list to set some colors. The Turtle
# Module can recognize many colors by name, so
# we use names to select the colors we want
# for our lines.
color_list = ["yellow", "gold", "orange", "red",
        "maroon", "violet", "magenta", "purple",
        "navy", "blue", "skyblue", "cyan",
        "turquoise", "lightgreen", "green",
        "darkgreen", "chocolate", "brown",
        "white"]
# With the turtle module imported, we can
# use its methods to control different aspects
# of how it will appear on the screen, for
# example, we can use .bgcolor() to set its
# background color.
turtle.bgcolor("black")
# The Pen() method of the Turtle module allows
# us to control various attributes of the "pen"
# for our drawing, including its position,
# color, direction, etc.
pen = turtle.Pen()
# Now we use a loop to draw the lines:
for i in range(500):
    # Each time the loop iterates we select
    # one of the colors from the list based
    # on the loop index, the modulus operator
    # and the number of colors in our list.
    pen.pencolor(color_list[i % 12])
    # We also adjust the width of our pen
    # each iteration as well
    pen.width(i / 100 + 1)
    # The pen draws a length equal to our
    # loop index value (i)
    pen.forward(i)
    # And then we shift the position of
    # the pen so the next iteration will
    # begin drawing at a regular interval
    # each time the loop repeats.
    pen.left(59)
# This input statement keeps the
# program from closing our drawing.
input("Press enter in the console to end.")

Example Output: The two examples below were created using the above code, the first with fewer colors and fewer loop iterations in the range(), and the second was created with the code as it appears above.

For a full list of the built-in functions and the official Python documentation for each you can visit docs.python.org.



 





© 2023 John Gordon
Cascade Street Publishing, LLC