How import works

A module is simply a .py file. import runs it once and gives you access to its names:

import math
print(math.sqrt(2))

from math import pi, floor        # import specific names
print(pi, floor(2.7))

import datetime as dt             # alias
print(dt.date.today().year)

# from math import *  <- avoid: pollutes your namespace
1.4142135623730951 3.141592653589793 2 2026

Python looks for modules in the current folder first, then the standard library, then installed packages (sys.path). Never name your own file random.py or math.py — it will shadow the real module and cause baffling errors.

Writing your own module

Save this as shapes.py:

"""Simple geometry helpers."""
PI = 3.14159

def circle_area(r):
    return PI * r * r

def square_area(side):
    return side * side

if __name__ == "__main__":       # runs only when executed directly
    print("self-test:", circle_area(1))

Then in main.py in the same folder:

import shapes
from shapes import square_area
print(shapes.circle_area(2), square_area(3))
12.56636 9

The if __name__ == "__main__": guard lets a file act both as an importable module and as a runnable script. The Coding Python app supports multi-file projects, so you can try this on your phone.

random and datetime

import random
random.seed(42)                     # reproducible results
print(random.randint(1, 6))          # dice roll
print(random.choice(["red", "green", "blue"]))
deck = list(range(1, 11)); random.shuffle(deck); print(deck)
print(random.sample(range(100), 3), round(random.random(), 3))

from datetime import date, datetime, timedelta
today = date(2026, 9, 17)
print(today.strftime("%A %d %B %Y"))
print(today + timedelta(days=30))
launch = datetime(2026, 12, 25, 9, 30)
print((launch - datetime(2026, 9, 17)).days, "days to go")
print(datetime.strptime("2026-01-05", "%Y-%m-%d").month)
6 red [8, 6, 3, 9, 10, 7, 2, 4, 5, 1] [4, 3, 11] 0.219 Thursday 17 September 2026 2026-10-17 99 days to go 1

collections

from collections import Counter, defaultdict, deque, namedtuple

words = "the cat sat on the mat the end".split()
c = Counter(words)
print(c.most_common(2))

groups = defaultdict(list)
for w in words:
    groups[w[0]].append(w)
print(dict(groups))

q = deque([1, 2, 3], maxlen=3)
q.append(4)                 # oldest drops off
q.appendleft(0)
print(q)

Point = namedtuple("Point", "x y")
p = Point(3, 4)
print(p.x, p[1], p)
[('the', 3), ('cat', 1)] {'t': ['the', 'the', 'the'], 'c': ['cat'], 's': ['sat'], 'o': ['on'], 'm': ['mat'], 'e': ['end']} deque([0, 2, 3], maxlen=3) 3 4 Point(x=3, y=4)

itertools and functools

from itertools import combinations, permutations, groupby, count, islice
from functools import lru_cache, reduce

print(list(combinations("ABC", 2)))
print(list(permutations([1, 2, 3], 2))[:4])
print(list(islice(count(10, 5), 4)))     # 10, 15, 20, 25
for key, grp in groupby("aaabbc"):
    print(key, len(list(grp)), end="; ")
print()

@lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(90))                            # instant thanks to caching
print(reduce(lambda a, b: a * b, [1, 2, 3, 4, 5]))
[('A', 'B'), ('A', 'C'), ('B', 'C')] [(1, 2), (1, 3), (2, 1), (2, 3)] [10, 15, 20, 25] a 3; b 2; c 1; 2880067194370816120 120
The app ships the lru_cache and itertools examples ready to run — the Coding Python app runs real Python 3 on your phone, with examples, quizzes and challenges built in.
Get it free

re: regular expressions

import re

text = "Contact: ada@example.com, linus@kernel.org on 2026-09-17"
print(re.findall(r"[\w.]+@[\w.]+", text))
m = re.search(r"(\d{4})-(\d{2})-(\d{2})", text)
print(m.group(0), m.group(1))
print(re.sub(r"\d", "#", "call 555-1234"))
print(bool(re.fullmatch(r"[A-Z][a-z]+", "Python")))
['ada@example.com', 'linus@kernel.org'] 2026-09-17 2026 call ###-#### True

Use raw strings (r"...") for patterns so backslashes are not mangled. Regex is powerful but hard to read — reach for string methods first and regex when patterns genuinely vary.

os, sys and time

import os, sys, time

print(sys.version.split()[0])
print(sys.platform)
print(os.getcwd())
print(os.path.join("data", "file.txt"))
print(os.environ.get("HOME", "n/a"))

start = time.perf_counter()
total = sum(range(1_000_000))
print(f"summed in {time.perf_counter() - start:.3f}s")
time.sleep(0.1)
sys.exit(0)                   # end the program with status 0
3.10.1 linux /data/user/0/app.learnpython.codingpython.pythoncompiler/files/projects/demo data/file.txt n/a summed in 0.021s

That completes the core Learn Python course. From here, the best next step is to build something: the beginner project ideas guide has twelve to choose from, and the practice exercises page has problems with solutions.

Frequently asked questions

What is the difference between a module and a package?

A module is a single .py file. A package is a folder of modules with an __init__.py file (or, since Python 3.3, any folder that Python can import). Both are used with import.

What is the standard library?

The collection of modules that ship with Python itself — math, random, json, datetime, os, re and around 200 more. They need no installation, which is why they all work in the Coding Python app.

What does if __name__ == '__main__' mean?

Python sets __name__ to '__main__' only in the file being run directly. The guard lets you put test or demo code in a module without it running on import.

Can I pip install packages in the Coding Python app?

The app bundles the full standard library. Third-party packages from PyPI are not supported, which keeps the app small and dependable.