학습 자료

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

ModuleUse Case
mathSquare roots, powers, constants
randomRandom numbers and choices
datetimeDates, 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.

학습 자료

AI 튜터

디자인

업로드

수업 노트

즐겨찾기

도움말

코드 에디터

코드 실행
코드 생성

실행 결과