Reusing reliable tools — the import statement, namespaces, the math, random, and datetime modules, reading documentation, and writing your own modules
Every professional programmer uses tools that other programmers have already written and tested. Python ships with a large collection of these tools built in — the standard library — organized into modules that you can load into any program when you need them. Learning to find, import, and use modules correctly is one of the most practical skills in Python programming.
This chapter explains what modules are, how the import statement works, and how to use several genuinely useful standard library modules: math for mathematical operations, random for randomness, and datetime for dates and times. It also teaches you how to begin reading Python documentation so you can keep learning on your own, and how to write your own simple module.
Suppose you need to calculate the distance between two GPS coordinates, simulate a thousand dice rolls, or figure out how many days remain until a deadline. None of these problems require you to invent new mathematics, randomness, or calendar logic from scratch — they have already been solved, tested, and packaged for you inside Python itself. The only question is whether you know how to find the right tool and use it correctly. By the end of this chapter, you will.
By the end of this chapter, you should be able to:
import statement correctly and call module functions using dot notation.import module_name and from module import name, and explain why this textbook prefers the former.math module for square roots, rounding, powers, logarithms, trigonometry, and constants.random module to generate random integers and floats, make random choices, and shuffle a list.datetime module to get the current date and time, create specific dates, format dates as strings, and calculate the difference between dates.help() function to explore unfamiliar module functions.import statement; dot notation; placing imports at the top of a file; what happens internally when a module is importedfrom module import name form and its tradeoffsmath ModuleRounding functions; powers and roots; trigonometry in radians; mathematical constants; a worked geometry examplerandom ModulePseudo-randomness; random integers and floats; random choice from a sequence; shuffling a list in place; a dice-rolling simulationdate and datetime classes; getting today's date; creating specific dates; formatting with strftime; subtracting dates to get a timedeltahelp() in the interactive shellif __name__ == "__main__" pattern