Using Built-in Modules (math, random, datetime)
Python includes many powerful built-in modules that can be used without installing anything.
Here, we’ll explore three commonly used ones: math, random, and datetime.
1. math: built-in module for math operations
The math module provides mathematical functions and constants, such as square roots, exponents, and π.
math Module
import math
print("Square root of 16 is", math.sqrt(16))
print("Pi rounded to 2 decimals:", round(math.pi, 2))
math.sqrt()returns the square root.math.pigives the value of π.
2. random: built-in module for random numbers and choices
The random module provides tools for generating random numbers and selecting items randomly from lists.
random Module
import random
print("Random number from 1 to 10:", random.randint(1, 10))
print("Random choice from list:", random.choice(["apple", "banana", "cherry"]))
randint(a, b)gives a random integer in the range[a, b].choice()selects one item randomly from a list.
3. datetime: built-in module for working with dates and times
The datetime module provides classes for creating, formatting, and manipulating dates and times.
datetime Module
import datetime
today = datetime.date.today()
print("Today's date is:", today)
now = datetime.datetime.now()
print("Current time is:", now.strftime("%H:%M"))
date.today()returns today's date.now.strftime()formats the current time as a string.
Summary
| Module | Use Case |
|---|---|
math | Square roots, powers, constants |
random | Random numbers and choices |
datetime | Dates, times, and formatting |
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.