Python Field Guide
Get started
-
What you need to write and run Python on your own computer.
-
The basic building blocks every Python program starts with: storing, displaying, and reading in values.
Data types
-
Kinds of values, and what you can do with them.
integers+ - * / **//, %, divmod()+= -= *= /= //= %= **=abs()int()boolean expressionsfloats+ - * / **//, %, divmod()+= -= *= /= //= %= **=abs()float()round()boolean expressionsstrings+ * += *=.capitalize()combine.count().endswith()f-string.find().format()inindex[].isalpha().isdigit().join()len().lower().replace()slice[:].split().startswith()step[::]str().strip().title().upper()boolean expressions -
Multiple related values grouped into one container, so you can work with them together.
lists+.append().clear()comprehensioncopy()count()createdel.extend()inindexindex().insert()itemlen()list operationslist()loopmax()min().pop()remove()reverse()slice.sort()sorted()stepsum()boolean expressionsdictionariesaccess a valueclear()copy()del()dict().get().items()keylen()looppop()popitem()update()value.values()boolean expressionstuplesaccess itemscount()immmutableindexindex()len()loopmax()min()packingsum()tuple operationstuple()unpackingboolean expressionssets| & - ^add()clear()copy()discard()isdisjoint()issubset()issuperset()len()loopmax()min()pop()remove()set()sum()updateboolean expressions
Control flow
-
Lets a program make decisions, running different code depending on whether something is true.
if, elif, elseboolean expressionsand, or, not -
Repeats a block of code multiple times.
forloop through a collectionloop a set number of timesrange()enumerate()reversed()zip()whileflagsentinelboolean expressionsand, or, notcounter and flag names
Code organization
-
Packages a block of code under a name, so it can be run again with different inputs.
defreturndefault parameter valueskeyword argumentsdocstrings -
Bundles related data and functions into a reusable blueprint, so a program can create many similar objects without duplicating code.
class__init__()selfobject methodsinheritancesuper()overriding __init__()adding attributes and methodsoverriding methodspolymorphismsame method name, unrelated classespolymorphism via inheritance
External files and resources
-
Splitting code across files, and using someone else's code.
-
Reads and writes text files to save data outside the program itself.
Robust programming practices
-
Conventions for writing standardized and readable Python code.
PEP 8namingdocstringsorderconstantsquote styleindentationblank lineswhitespacecommentsPythonic patternscommon patternsbest practicestype hintscatch exceptionskeep functions focusedreadable print output -
How to read error messages, handle them, and track down what went wrong.
tracebackshow to read a tracebackdebuggerset breakpointsrun in debug modewhat you can do at a breakpointdebugging strategiesrubber duck debuggingprint debuggingisolate the problemTODO, FIXME
Add-On Libraries
Utilities
-
Specialized containers: counting items, grouping with defaults, named tuples, fast queues.
Countercounts[item]most_common()total()elements()update()subtract()+ - & |defaultdictdefault_factory.get()namedtupledefaults=_make()_asdict()_replace()_fields_field_defaultsdequeappend()appendleft()extend()extendleft()insert()pop()popleft()remove()clear()count()index()copy()rotate()reverse()maxlen=OrderedDictmove_to_end()popitem()== -
Calculating and formatting dates and times.
-
Random numbers, random picks, shuffled order.
Data analysis
-
Reading and writing spreadsheets.
-
Charts and plots: line, bar, and scatter, built directly from plain Python data.
-
Fast numeric arrays, with math applied to a whole array at once instead of item by item.
-
Tabular data: rows and columns, like a spreadsheet, built on top of NumPy.
APIs
-
Reading and writing JSON data: nested dicts and lists, saved to a file or a string.
-
Fetching data over the internet, like asking a website or API for information.
Image editing
-
Opening, editing, and saving images, built around one
Imageobject.Imageopening and saving imagesbasic operationsimage modesresizecroprotate and flipImageOpscommon ImageOps functionsImageColorconverting color namesImageEnhanceenhancing an imageImageChopscomparing and combining imagesconvert()converting between formats
Computer vision
-
Real-time image and video analysis, built directly on NumPy arrays: color spaces, edge detection, face detection.
reading, displaying, saving imagesimread()displaying a windowsaving a fileCascadeClassifierdetecting and labeling facesbasic operationsresize()croppingrotating
Desktop UIs
-
Creating desktop applications: text, buttons, dropdowns, forms, output, etc.
configure()reading and changing optionscommandcommand callbacksbinding events
FAQ
Why learn to code yourself, if AI can do it for you?
| Learn to do it yourself | Have AI do it for you | |
|---|---|---|
| Writing & struggling with code | Productive struggle is what builds understanding
|
Being handed the answer skips the friction that builds understanding
|
| Reading & verifying code | Understanding programming fundamentals makes AI more useful — you can read code you didn't write, and check it before you trust it
|
Inefficient communciation with AI if you don't fully understand what's going on, and AI code can look correct while being wrong and insecure
|
| On the job | Employers are still hiring for understanding, not prompting
|
AI will likely be available at work too — but it isn't what's being tested |
References
- The friction that builds understanding — E. Bjork & R. Bjork, on desirable difficulties in learning
- Students who rely on AI code generation before building their own foundation — the documented skill gap
- Stanford study — developers using AI wrote less secure code, but were more confident it was secure
How to use AI to support your learning
swimlane-beta TB
accTitle: Using AI to learn
accDescr: AI walks you through setup before you start. You attempt each problem yourself with autocomplete off, then check whether you can explain why it works and whether it actually holds up — if either check fails, you describe what you tried rather than handing over your code, so AI explains the concept instead of fixing it, and you try again. Passing both checks means you understand it well enough for a practice problem, or for the code review, debugging, and interviews that are what your job actually tests.
subgraph You
you_help_setup(Need help setting up your computer to start programming?)
you_have_project(Do you have a project to work on?)
you_attempt(Attempt it yourself, autocomplete off so you understand everything that's there, utilize debug strategies)
you_writeup(Stuck? Write out your problem: what you expect to happen, what you're observing, what you've tried already, see if this helps you process or rethink your strategy)
you_finish("Learning to program means making mistakes, getting stuck, and eventually figuring things out and forming a mental model. That's the process that builds skills you can rely on to continue solving problems and detecting issues — ready for code review, debugging, and interviews, where AI won't be tested, your reasoning will. ")
end
subgraph AI
ai_help_setup(AI can help guide you through setup on your exact device — which could make getting started more accessible for beginners)
ai_suggest_problem(Suggests a problem based on your skill level, interests, and what you're trying to improve)
explain(With that context AI can provide more targeted, efficient help. Don't just paste the code/error, ask AI to explain what a line does, or what an error means — an explanation to help you understand concepts, be clear you do NOT want it to write code, just explain)
end
ai_help_setup ~~~ you_help_setup
ai_suggest_problem ~~~ you_have_project
you_help_setup -->|Yes| ai_help_setup
you_help_setup -->|No| you_have_project
ai_help_setup --> you_have_project
you_have_project -->|No| ai_suggest_problem
you_have_project -->|Yes| you_attempt
ai_suggest_problem --> you_attempt
you_attempt <--> you_writeup
you_attempt -->|Done!| you_finish
you_writeup --> |still stuck?| explain
explain --> you_attempt
explain ~~~ you_finish
%% Edge label text colored red if it leads into the AI lane, green
%% if it leads into the You lane, matching the lane colors. This is
%% linkStyle's "color" property (not background) — the one styling
%% mechanism mermaid applies from inside its own closed shadow
%% root, so it's the only thing that actually reaches the label.
linkStyle 0 color:#a33f3f
linkStyle 1 color:#3f6b52
linkStyle 3 color:#3f6b52
linkStyle 4 color:#a33f3f
linkStyle 7 color:#3f6b52
linkStyle 8 color:#a33f3f
classDef you fill:#3f6b521f,stroke:#3f6b52,stroke-width:2px,color:#3f6b52
classDef ai fill:#a33f3f1a,stroke:#a33f3f,stroke-width:2px,color:#a33f3f
class you_writeup,you_help_setup,you_have_project,you_attempt,you_finish you
class explain,ai_help_setup,ai_suggest_problem ai
style You fill:#3f6b521f,stroke:#3f6b52,color:#3f6b52
style AI fill:#a33f3f1a,stroke:#a33f3f,color:#a33f3f
Fig. 1a — when to use AI while learning to program
What is Python, and what is this guide?
Readable, and quick to write. Python is a general-purpose language built for code that's easy to read back later — even by someone who didn't write it. No compiling: write a .py file, run it directly.
- Shows up everywhere — web backends, data analysis and machine learning, automating repetitive tasks, scientific computing, quick glue scripts. Several of these are covered on this site's Libraries pages.
- The skills transfer. Variables, conditionals, loops, functions, classes — the fundamentals every language shares — read closer to plain English here, so you spend your effort learning to think like a programmer instead of fighting a stricter syntax. Once solid, those fundamentals carry over to whatever language you pick up next.
- Often the fastest language to write correct code in — even though it's not the fastest to run — which is why it's such a common first choice for a new project.
This guide. Python Field Guide is a free, in-browser reference — most code blocks are editable and runnable directly on the page.
- For learners — self-taught, students in an intro course, or anyone who wants one combined reference to work through start to finish, instead of a scattered pile of search results.