Skip to main content

Command Palette

Search for a command to run...

Python Basics — Day 20 Python Standard Library

Published
3 min read
S

Aspiring Full-Stack Developer | Python · Django · React · SQL | documenting my learning journey

Building skills in Python and full-stack development, with a focus on web apps and system design

Junior developer in training — Python, Django, React — preparing for a career in full-stack engineering

From Python basics to full-stack projects, sharing my progress as I grow into a developer

Future full-stack engineer | Learning in public: Python, APIs, Databases, and Web Development

Day 20 – Python Standard Library

Project: Build a “Lotto Generator & Date Calculator”


Learning Goal

Learn how to use Python’s built-in standard libraries—math, random, datetime, time, and os—by solving real problems in one mini project:
a lotto number generator and a date calculator that performs time-based operations.


01. Problem Scenario

You want to build a small program that can:

  1. Generate random lotto numbers.

  2. Calculate and display important date information (today, tomorrow, or a specific future date).

  3. Save and manage data files automatically.

This project will help you see how Python’s built-in modules simplify common real-world tasks.


02. Step 1 – Mathematical Operations with math

You need to calculate things like circle areas or factorials.
Instead of writing custom formulas every time, Python’s math module does the job instantly.

import math

# Calculate circle area
r = 5
area = math.pi * math.pow(r, 2)
print("Circle Area:", area)

# Calculate factorial
print("5! =", math.factorial(5))

# Round up and down
print("Ceiling:", math.ceil(3.2))
print("Floor:", math.floor(3.9))

Result: You can easily perform complex mathematical calculations with one line.


03. Step 2 – Generate Random Numbers with random

Now let’s create the lotto generator feature using the random module.

import random

def generate_lotto():
    return sorted(random.sample(range(1, 46), 6))

print("Lotto Numbers:", generate_lotto())

Each time you run it, you get a different 6-number combination from 1 to 45.


04. Step 3 – Work with Dates Using datetime

Now you want your app to display today’s date, tomorrow’s date,
and calculate days remaining until a target date (e.g., New Year).

from datetime import datetime, timedelta

# Current date and time
now = datetime.now()
print("Today:", now.strftime("%Y-%m-%d %H:%M"))

# Tomorrow
tomorrow = now + timedelta(days=1)
print("Tomorrow:", tomorrow.strftime("%Y-%m-%d"))

# Days until New Year
new_year = datetime(2026, 1, 1)
diff = new_year - now
print("Days until New Year:", diff.days)

Now your app handles both time display and simple date math.


05. Step 4 – Pause or Measure Time with time

Let’s simulate a loading animation before showing the lotto numbers.

import time

print("Drawing lotto numbers...")
time.sleep(2)
print("Your numbers are:", generate_lotto())

time.sleep() pauses the program for a set number of seconds—useful for animations or rate limiting.


06. Step 5 – File and Folder Management with os

Finally, save your lotto results to a file using the os module.

import os

# Create folder to store results
if not os.path.exists("results"):
    os.mkdir("results")

with open("results/lotto.txt", "a", encoding="utf-8") as f:
    f.write(f"{datetime.now()}: {generate_lotto()}\n")

print("Lotto results saved to /results/lotto.txt")

os lets your program create and manage folders dynamically.


07. Step 6 – Combine Everything

Let’s combine all these modules into a single project file.

import math, random, time, os
from datetime import datetime, timedelta

def generate_lotto():
    return sorted(random.sample(range(1, 46), 6))

def show_dates():
    now = datetime.now()
    tomorrow = now + timedelta(days=1)
    print("Today:", now.strftime("%Y-%m-%d"))
    print("Tomorrow:", tomorrow.strftime("%Y-%m-%d"))

def save_result(numbers):
    if not os.path.exists("results"):
        os.mkdir("results")
    with open("results/lotto.txt", "a", encoding="utf-8") as f:
        f.write(f"{datetime.now()}: {numbers}\n")

def main():
    print("Generating your lucky numbers...")
    time.sleep(2)
    nums = generate_lotto()
    print("Your Lotto Numbers:", nums)
    save_result(nums)
    show_dates()
    print("Good luck!")

if __name__ == "__main__":
    main()

Run this file, and you’ll see your results displayed and saved automatically.


Key Takeaways

ModulePurposeExample Use
mathMathematical operationssqrt, factorial, pi
randomRandom data generationlotto numbers
datetimeDate and time handlingcalculate tomorrow’s date
timeDelays and timingsimulate “loading”
osFile and folder operationssave lotto history

Python Basics

Part 20 of 21

A collection of study notes from my university and self-learning journey. This series covers Python fundamentals step by step — from setup to core concepts — to help both myself and others build a solid foundation in coding.

Up next

Python Basics — Day 21 External Libraries (pip, requests)

🎯 Learning Goal Learn how to install and use external Python libraries with pip,and apply the requests module to communicate with real-world web APIs (e.g. GitHub & Weather APIs).By the end of this lesson, you’ll have a working API data fetcher that...

More from this blog

S

Sabin’s DevLog

21 posts

I plan to upload everything I study and prepare here. I hope it can be helpful to others, and I also want my future self to see the learning journey I’ve been through.