Skip to main content

Week 4: Libraries

·426 words·2 mins·

Libraries
#

A piece of code that someone else wrote that you can use in your code.

Modules
#

Is a library that has one or more functions built into it.

Re-usability code.

random
#

random is a built-in module in Python. It has a set of functions to generate random numbers.

Documentation

import
#

To use a module, you have to import it.

import random

coin = random.choice(["head", "tails"])
print(coin)

from
#

Is the keyword to import a specific function from a module.

from random import choice

coin = choice(["head", "tails"])
print(coin)

randint, shuffle
#

randint
#

import random

number = random.randint(1, 10)
print(number)

shuffle
#

import random

cards = ["jack", "queen", "king"]
random.shuffle(cards)
for card in cards:
    print(card)

statistics
#

statistics is a built-in module in Python. It has a set of functions to calculate statistics.

Documentation

import statistics

print(statistics.mean([100, 90]))

Command-line Arguments, sys
#

sys module, provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.

Documentation

  • sys.argv: argument vector, a list of strings representing the arguments.
import sys

if len(sys.argv) < 2:
    print("Too few arguments")
elif len(sys.argv) > 2:
    print("Too many arguments")
else:
    print("hello, my name is", sys.argv[1])

sys.exit
#

Exit from Python.

import sys

if len(sys.argv) < 2:
    sys.exit("Too few arguments")
elif len(sys.argv) > 2:
    print("Too many arguments")

print("hello, my name is", sys.argv[1])

slices
#

A slice is a portion of a list.

import sys

if len(sys.argv) < 2:
    sys.exit("Too few arguments")

for arg in sys.argv[1:]:
    print("hello, my name is", arg)

Packages, PyPI, pip
#

  • Package: is a collection of modules.
  • PyPI: Python Package Index, is a repository of software for the Python programming language.
  • pip: is a package installer for Python.

cowsay
#

Documentation

Install
#

pip install cowsay

Usage
#

import cowsay
import sys

if len(sys.arg) == 2:
    cowsay.cow("hello, " + sys.argv[1])

APIs, requests, JSON
#

  • API: Application Programming Interface.
  • requests: is a simple HTTP library for Python.
  • JSON: JavaScript Object Notation, a language-independent data format.

Pretty print JSON
#

import json
import requests
import sys

if len(sys.argv) != 2:
    sys.exit()

response = requests.get("https://itunes.apple.com/search?entity=song&limit=1&term=" + sys.argv[1])
print(json.dumps(response.json(), indent=2))

Printing the track name from the API
#

import json
import requests
import sys

if len(sys.argv) != 2:
    sys.exit()

response = requests.get("https://itunes.apple.com/search?entity=song&limit=50&term=" + sys.argv[1])

o = response.json()
for result in o["results"]:
    print(result["trackName"]) 

Custom Libraries
#

Create your own library.

sayings.py
#

def main():
    hello("world")
    goodbye("world")


def hello(name):
    print(f"hello, {name}")


def goodbye(name):
    print(f"goodbye, {name}")


if __name__ == "__main__":
    main()

say.py
#

import sys

from sayings import hello

if len(sys.argv) == 2:
    hello(sys.argv[1])
Gael Mora
Author
Gael Mora
IT Security student, Python and Go developer. Specialized in Linux systems administration and automation. Passionate about cloud and network infrastructure, software development and open source technologies.