Lecture

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.pi gives 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

ModuleUse Case
mathSquare roots, powers, constants
randomRandom numbers and choices
datetimeDates, times, and formatting
Quiz
0 / 1

Python's built-in random module can generate random integers and select random items from a list.

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result