📚 Python Libraries
Learning Objectives:
By the end of this lesson, learners should be able to:
- Understand what a Python library is.
- Know how to install and import a library.
- Use popular libraries like
math,random, anddatetimewith simple examples. - Practice with short, fun tasks using these libraries.
What is a Python Library?
A Python library is a collection of pre-written code that you can use to perform common tasks without having to write everything from scratch. Think of it like a toolbox — instead of making your own hammer, you just pull one out from the toolbox! 🛠️
How to Use a Library in Python
1. Importing a Built-in Library:
import math
print(math.sqrt(16)) # Output: 4.0
print(math.pi) # Output: 3.141592653589793
2. Importing Part of a Library:
from math import sqrt, sin, radians, pow
print("Square root of 36:", sqrt(36))
print("Sine of 90 degrees:", sin(radians(90)))
print("Power of 2^3:", pow(2,3))
3. random – Generate random numbers:
import random
print("Random number between 1 and 10:", random.randint(1, 10))
print("Random choice from a list:", random.choice(['apple', 'banana', 'cherry']))
4. datetime – Work with dates and time:
import datetime
today = datetime.date.today()
print("Today's date is:", today)
now = datetime.datetime.now()
print("Current time:", now.strftime("%H:%M:%S"))