Links to Variables & Lists // Collections // Python editor // Conditions // Loops // Working with text files // Functions // Exercises
A library is a collection of precompiled codes that can be used later on in a program for some specific well-defined operations.
When you write a lot of code, you will want to organise them as modules – bundles of code saved as functions in separate scripts, that can be used repeatedly in different programs. You don’t need to write the same code again and again for different programs.
Multiple interrelated modules are stored in a library. And whenever we need to use a module, we import it from its library. In Python, it’s a very simple job to do due to its easy syntax. We just need to use import. You write the import command at the top of your script.
import random
fruits = ["orange", "lemon", "banana", "apple", "pear"]
fruit = random.choice(fruits)
print(fruit)
You can also choose to only import the function you need.
from random import choice
fruits = ["orange", "lemon", "banana", "apple", "pear"]
fruit = choice(fruits)
print(fruit)
Note for advanced programmers: you can create your own Python library, f.ex.
https://packaging.python.org/en/latest/tutorials/packaging-projects/
https://medium.com/analytics-vidhya/how-to-create-a-python-library-7d5aea80cc3f