← Back to Chapters

Python Math, Random & Date

? Python Math, Random & Date

⚡ Quick Overview

Python provides built-in modules to handle common tasks: math for mathematical operations and constants, random for generating randomness, and datetime for working with dates and times. Together, they are used in calculations, games, simulations, scheduling, logging, and more.

? Key Concepts

  • math module → precise mathematical functions like square root, factorial, trigonometry, rounding, and constants like math.pi.
  • random module → random numbers, random choices from sequences, shuffling, and sampling.
  • datetime module → working with dates, times, time differences, and formatting.
  • Always import the module before using it (e.g., import math, import random, import datetime).
  • You can combine these modules, for example: random dates for simulations or games that depend on time-based events.

? Syntax and Theory

? Math Module Basics

  • math.sqrt(x) → square root of x.
  • math.factorial(n)n! (product 1 to n).
  • math.ceil(x) → smallest integer ≥ x.
  • math.floor(x) → largest integer ≤ x.
  • math.pi, math.e → common mathematical constants.

? Random & ? Datetime

  • random.random() → float in range [0.0, 1.0).
  • random.randint(a, b) → integer between a and b (inclusive).
  • random.choice(seq) → random element from a sequence.
  • random.shuffle(list) → shuffle list in place.
  • datetime.datetime.now() → current date and time.
  • datetime.date.today() → current date only.
  • Subtracting dates gives a timedelta (difference in days/seconds).
  • strftime() → format dates (e.g., "%d-%m-%Y").

? Math Module Example

The math module provides functions for square roots, factorials, rounding, logs, and trigonometry.

? View Math Code Example
import math

# Basic mathematical operations
print("Square root of 25:", math.sqrt(25))
print("Factorial of 5:", math.factorial(5))
print("Ceil of 4.3:", math.ceil(4.3))
print("Floor of 4.7:", math.floor(4.7))
print("Value of pi:", math.pi)

# Trigonometric functions
print("sin(pi/2):", math.sin(math.pi/2))
print("cos(0):", math.cos(0))
print("tan(pi/4):", math.tan(math.pi/4))

# Logarithmic functions
print("log(100, 10):", math.log(100, 10))  # log base 10
print("Natural log of 2.718:", math.log(math.e))

? Random Module Example

The random module is useful in games, simulations, sampling, and any situation where you need unpredictability.

? View Random Code Example
import random

# Random float between 0.0 and 1.0
print("Random float:", random.random())

# Random integer between 1 and 10
print("Random integer:", random.randint(1, 10))

# Random choice from a list
fruits = ['apple', 'banana', 'cherry']
print("Random fruit:", random.choice(fruits))

# Shuffle a list in-place
random.shuffle(fruits)
print("Shuffled fruits:", fruits)

# Random sample from a list
sample = random.sample(fruits, 2)
print("Random sample of 2 fruits:", sample)

? Date and Time Example

The datetime module lets you get the current time, create specific dates, find differences between dates, and format them.

? View Datetime Code Example
import datetime

# Current date and time
now = datetime.datetime.now()
print("Current date and time:", now)

# Current date only
today = datetime.date.today()
print("Today's date:", today)

# Create a specific date
birthday = datetime.date(2000, 5, 17)
print("Birthday:", birthday)

# Date difference
delta = today - birthday
print("Days since birthday:", delta.days)

# Formatting dates
print("Formatted date:", today.strftime("%d-%m-%Y"))  # dd-mm-yyyy
print("Day of the week:", today.strftime("%A"))       # e.g., Tuesday

? Use Cases

  • Building math-heavy applications like calculators, statistics tools, and scientific programs using math.
  • Creating games (dice rolls, random enemies, card shuffling) using random.
  • Simulating real-world processes where randomness is involved (Monte Carlo simulations).
  • Tracking events, logs, deadlines, reminders, and age calculations with datetime.
  • Combining random and datetime to generate random dates or timestamps for test data.

? Live Output & Explanation

? What This Program Prints

  • Math example: You will see numeric results such as: Square root of 25: 5.0, factorial values like 120, ceiling/floor operations, and trigonometric values such as sin(pi/2): 1.0.
  • Random example: Every run gives different values. You will see:
    • A random float between 0.0 and 1.0.
    • A random integer between 1 and 10.
    • A random fruit name chosen from the list.
    • The fruits list in a new shuffled order.
    • A random sample of 2 fruits from the list.
  • Datetime example: You will see:
    • The current date and time for your system.
    • Today’s date as a date object.
    • A specific birthday date.
    • The number of days between that birthday and today.
    • A nicely formatted date like 17-05-2000.
    • The name of the weekday (e.g., Tuesday).

If your output looks similar (even if the exact numbers are different for random and time-based values), your code is working correctly.

? Tips & Best Practices

  • Use math for precise mathematical calculations and constants instead of writing your own formulas from scratch.
  • Use random to add randomness for simulations, games, or random selections in your programs.
  • Use datetime to handle dates, times, and differences between them in a clean, readable way.
  • Always import the required module before using its functions (e.g., import math at the top of your file).
  • Combine modules, for example: generate random dates using random with datetime to create test data.

? Try It Yourself

  • Generate a random number between 50 and 100 using random.randint().
  • Shuffle a list of numbers from 1 to 10 using random.shuffle().
  • Calculate the number of days between two dates using datetime.date objects.
  • Use math.ceil(), math.floor(), and math.factorial() in your own calculations.
  • Create a function that generates a random birthday date and calculate how many days until that date.
  • Format a datetime object to display in "Weekday, Month Day, Year" format using strftime().