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 – Advanced Math Functions
The math
module gives you access to square roots, powers, constants like π, and more.
import math print("Square root of 16 is", math.sqrt(16)) print("Pi rounded to 2 decimals:", round(math.pi, 2))
Explanation:
math.sqrt()
returns the square root.math.pi
gives the value of π.
2. random – Generate Random Values
The random
module helps with simulations, games, and randomized decisions.
import random print("Random number from 1 to 10:", random.randint(1, 10)) print("Random choice from list:", random.choice(["apple", "banana", "cherry"]))
Explanation:
randint(a, b)
gives a random integer in the range [a, b].choice()
selects one item randomly from a list.
3. datetime – Work with Dates and Times
The datetime
module lets you manage dates, times, and durations.
import datetime today = datetime.date.today() print("Today's date is:", today) now = datetime.datetime.now() print("Current time is:", now.strftime("%H:%M"))
Explanation:
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 |
What’s Next?
Next, you’ll learn how to import external modules that don’t come with Python by default.
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