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.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 |
Lessons in this chapter · Python Programming Review
- 1. Variables and Data Types
- 2. Expressions and Arithmetic
- 3. String Operations
- 4. Lists in Python
- 5. List Methods and Slicing
- 6. Tuples and Sets
- 7. Dictionaries - Keys and Values
- 8. Dictionary Methods and Nesting
- 9. Conditional Statements (if, elif, else)
- 10. Loops - for and while
- 11. Control Flow & Data Structures Recap
- 12. Multiple-choice quiz
- 13. Loop Controls (break, continue, pass)
- 14. Functions - Defining and Calling
- 15. Function Arguments and Return Values
- 16. Variable Scope and Nested Functions
- 17. Exception Handling with try/except
- 18. File Reading and Writing
- 19. CSV File Parsing
- 20. Using Built-in Modules (math, random, datetime)
- 21. Importing External Modules
- 22. Fill-in-the-blank quiz
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