Introduction to Modules and Libraries
Explore how to use Python modules and libraries to add powerful features to your code. Learn to import and utilize tools from modules such as random, math, and datetime to perform tasks like generating random values, calculating mathematical functions, and working with date and time in your programs.
We'll cover the following...
Python is powerful because of its syntax and amazing libraries—prebuilt collections of code that do awesome things, so you don’t have to start from scratch.
In this lesson, we’ll explore how to use these libraries (also called modules) to supercharge your code.
What’s a module?
A module is like a toolbox. We can import it into our code and start using its functions, classes, constants, and more tools.
Let’s use the following:
import turtle
Let’s try a few more built-in modules.
Random module: Make random choices
Let’s flip a coin with random. Run the code below a few times—it changes!
You just used randomness in your code.
Math module: More powerful math
Let’s find the square root of 64 and print the value of pi using the math library:
You now have the power of square roots and π!
Datetime module: Use time
Let’s print the current date and time:
Now your program knows the date and time—useful for logs and trackers!