top of page

A brief overview of the standard library

The standard library consists of modules that Python comes with. Here's a very brief overview of what it can do. All of these modules can also do other things, and you can read more about that in the official documentation.


Random numbers

The official documentation is here.


>>> import random
>>> random.randint(1, 3)      # 1, 2 or 3
3
>>> colors = ['red', 'blue', 'yellow']
>>> random.choice(colors)     # choose one color
'red'
>>> random.sample(colors, 2)  # choose two different colors
['yellow', 'red']
>>> random.shuffle(colors)    # mix the color list in-place
>>> colors
['yellow', 'red', 'blue']
>>>


Things that are built into Python


The module name "sys" is short for "system", and it contains things that are built into Python. The official documentation is here.

sys.stdin, sys.stdout and sys.stderr are file objects, just like the file objects that open() gives us.


>>> import sys
>>> print("Hello!", file=sys.stdout)  # this is where prints go by default
Hello!
>>> print("Hello!", file=sys.stderr)  # use this for error messages
Hello!
>>> line = sys.stdin.readline()  # i will type hello and press enter
hello
>>> line
'hello\n'
>>>
>>> # information about Python's version, behaves like a tuple
>>> sys.version_info
sys.version_info(major=3, minor=7, micro=3, releaselevel='final', serial=0)
>>> sys.version_info[:3]  # this is Python 3.7.3
(3, 7, 3)
>>>
>>> sys.exit()  # exit out of Python

sys.exit() does the same thing as sys.exit(0). The zero means that the program succeeded, and everything's fine. If our program has an error we should print an error message to sys.stderr and then call sys.exit(1). Like this:


if something_went_wrong:
    # of course, we need to make real error messages more
    # informative than this example is
    print("Oh crap! Something went wrong.", file=sys.stderr)
    sys.exit(1)


Mathematics

There's no math.py anywhere, math is a built-in module like sys. The official documentation is here.

>>> import math
>>> math
<module 'math' (built-in)>
>>> math.pi                  # approximate value of π
3.141592653589793
>>> math.sqrt(2)             # square root of 2
1.4142135623730951
>>> math.radians(180)        # convert degrees to radians
3.141592653589793
>>> math.degrees(math.pi/2)  # convert radians to degrees
90.0
>>> math.sin(math.pi/2)      # sin of 90 degrees or 1/2 π radians
1.0
>>>


Time-related things

The official documentation for the time module is here.

>>> import time
>>> time.sleep(1)   # wait one second
>>> time.time()     # return time in seconds since beginning of the year 1970
1474896325.2394648
>>> time.strftime('%d.%m.%Y %H:%M:%S')  # format current time nicely
'07.04.2017 19:08:33'
>>>

You are probably wondering how time.time() can be used and why its timing starts from the beginning of 1970. time.time() is useful for measuring time differences because we can save its return value to a variable before doing something, and then afterwards check how much it changed. There's an example that does this in the example section.


If you want to know why it starts from 1970 you can read something like this. See help(time.strftime) if you want to know about more format specifiers like %d, %m etc. that time.strftime can take.


Operating system related things

The module name "os" is short for "operating system", and it contains handy functions for interacting with the operating system that Python is running on. The official documentation is here.



>>> import os
>>> os.getcwd()        # short for "get current working directory"
'/home/akuli'
>>> os.mkdir('stuff')  # create a folder, short for "make directory"
>>>
>>> os.path.isfile('hello.txt')  # check if it's a file
True
>>> os.path.isfile('stuff')
False
>>> os.path.isdir('hello.txt')   # check if it's a directory
False
>>> os.path.isdir('stuff')
True
>>> os.path.exists('hello.txt')  # check if it's anything
True
>>> os.path.exists('stuff')
True
>>>
>>> # this joins with '\\' on windows and '/' on most other systems
>>> path = os.path.join('stuff', 'hello-world.txt')
>>> path
'stuff/hello-world.txt'
>>> with open(path, 'w') as f:
...     # now this goes to the stuff folder we created
...     print("Hello World!", file=f)
...
>>> os.listdir('stuff')  # create a list of everything in stuff
['hello-world.txt']
>>>


More modules!

Python's standard library has many awesome modules and I just can't tell about each and every module I use here. Here's some of my favorite modules from the standard library. Don't study them one by one, but look into them when you think you might need them. When reading the documentation it's usually easiest to find what you are looking for by pressing Ctrl+F in your web browser, and then typing in what you want to search for.

  • argparse: a full-featured command-line argument parser

  • collections, functools and itertools: handy utilities

  • configparser: load and save setting files

  • csv: store comma-separated lines in files

  • json: yet another way to store data in files and strings

  • textwrap: break long text into multiple lines

  • warnings: like exceptions, but they don't interrupt the whole program

  • webbrowser: open a web browser from Python

There are also lots of awesome modules that don't come with Python. You can search for those on the Python package index, or PyPI for short. It's often better to find a library that does something difficult than to spend a lot of time trying to do it yourself.

 
 
 

Comentários

Avaliado com 0 de 5 estrelas.
Ainda sem avaliações

Adicione uma avaliação

All rights reserved © 2023 by HiDevs.

bottom of page