Using Built-in Modules (math, random, datetime)
Python comes with many useful built-in modules that you can use without installing anything.
Let's look at three common ones: math
, random
, and datetime
.
1. math: built-in module for math operations
The math
module provides functions and constants for mathematical operations, like square roots, powers, 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.pi
gives the value of π.
2. random: built-in module for random numbers and choices
The random
module provides functions for generating random numbers and selecting random elements from a list.
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 working with dates, times, and durations.
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.