Python Programming From Zero

03

The 80/20

The 20% of concepts that give you 80% of the results, each with an analogy that sticks.

A small number of ideas do nearly all the work in Python, and every large program is a rearrangement of them. Learn these seven well and you can read most code you encounter and write most code you need.

Concept 1 of 7

Values, names, and types

Almost every beginner error is a name pointing at a value of a type you did not expect.

Everything in Python is an object with a type, and variables are just names that refer to those objects. The type determines the legal operations, so a string of digits is not a number until you convert it, and dividing two integers with / always gives you a float. When something behaves strangely, ask two questions: what does this name currently refer to, and what type is it. print(x) and type(x) answer both in two seconds.

Assignment rebinds names; it does not copy values. Two names can refer to the same mutable list, so a change through one shows up through the other. Immutable values like numbers, strings, and tuples cannot be changed in place, which is why methods like upper return a new string instead of modifying the original.

Analogy

Names are luggage tags, not suitcases. Sticking a second tag on the same suitcase does not create a second suitcase, and cutting a hole in the suitcase is visible from either tag.

Example

You write items = ["pen"], then backup = items, then items.append("pad"), then print(backup) and see both items. Fixing it means backup = items[:] or list(items), which builds a genuinely separate list.

Concept 2 of 7

Control flow: if, for, while

Decisions and repetition are the only two ways a program does more than a calculator can.

An if statement chooses between blocks based on a boolean condition; a for loop repeats a block once per item in a sequence; a while loop repeats until a condition stops being true. Indentation, not braces, defines what belongs to each block, so consistent four-space indentation is part of the language and not a style preference.

Most loop code fits one of a few patterns worth memorizing: accumulate a total, count matches, build a new list, find the best item, or stop early with break when you have what you need. Recognizing which pattern you need turns a blank page into filling in a template.

Analogy

A recipe with a fork in it. If the dough is too dry, add water; for each of the twelve muffin cups, spoon in batter; while the top is not golden, keep baking.

Example

Finding the most expensive item in orders = [("chair", 90), ("lamp", 40), ("desk", 210)] is the find-the-best pattern: set best = None, loop over the pairs, and replace best whenever the current price beats the stored one, which lands on desk at 210.

Concept 3 of 7

Functions and return values

Functions are how you stop repeating yourself and how you break a problem too big to hold in your head into pieces that fit.

A function packages steps under a name, takes inputs as parameters, and sends a result back with return. The discipline that pays off is one job per function and a name that describes that job, so reading the calling code tells you the story without opening the definitions. Parameters are local, so a well-written function depends only on what you pass in and affects only what it returns, which makes it easy to test in isolation.

The distinction beginners must nail is print versus return. Printing writes text for a human and gives back None; returning hands a real value to your program so you can store it, compare it, or feed it to the next function.

Analogy

A vending machine. You put in a coin and a code, the machinery inside is none of your business, and a snack comes out. A machine that only lights up a sign saying "chips" and gives you nothing is a function that prints instead of returns.

Example

Instead of copying three lines of tax math into four places, you define def net_pay(gross, rate): return round(gross * (1 - rate), 2) and call net_pay(4200, 0.28) wherever you need it. Changing the rounding rule later means editing one line.

Concept 4 of 7

Lists and dictionaries

Choosing the right container makes code short and fast, and choosing the wrong one makes it long and slow.

Use a list when order matters and items are of the same kind: a queue of filenames, a sequence of daily temperatures. Use a dictionary when each value needs a name or you need instant lookup by key: settings, a word count, a record with fields. A list of dictionaries is the standard way to hold a table of records, and it is the shape almost all real data arrives in from CSV files and web APIs.

Dictionary lookup by key stays fast no matter how many entries there are, while searching a list means checking items one by one. When you find yourself scanning a list repeatedly to find a matching item, that is the signal to build a dictionary keyed on the thing you keep searching for.

Analogy

A list is a numbered row of lockers; a dictionary is a coat check where you hand over a ticket with a name on it and get the right coat back immediately, however big the cloakroom is.

Example

Matching 5,000 order rows to customer names by scanning a customer list each time is slow and awkward. Building by_id = {c["id"]: c["name"] for c in customers} once turns each match into by_id[order["customer_id"]].

Concept 5 of 7

Strings and formatting

Most real input and output is text, so cleaning and composing strings is a large share of everyday code.

Strings come with methods that solve the boring problems: strip removes surrounding whitespace, lower normalizes case for comparison, split breaks text into a list on a separator, join glues a list back together, replace substitutes text, and startswith or in test for content. All of them return new strings, because strings are immutable.

For output, f-strings are the tool: f"{name}: {amount:.2f}" inserts values and controls formatting in one readable line. Doing comparisons on user-entered text without stripping and lowercasing it first is one of the most common sources of bugs that only appear with real data.

Analogy

Strings arrive like vegetables from the garden, covered in dirt. strip and lower are washing and peeling; split and join are chopping and plating.

Example

A signup form sends " Ana@Example.COM " and your database has "ana@example.com". Comparing them directly fails; comparing raw.strip().lower() succeeds, and one line prevents a duplicate account.

Concept 6 of 7

Errors and debugging

Reading tracebacks turns a wall of red text into a precise map of what broke and where.

When Python fails it tells you the file, the line, the exception type, and a message. Read from the bottom up: the last line names the problem, and the lines above show the chain of calls that led there. The type alone often solves it, since TypeError means wrong kind of value, NameError means a typo or a variable used before assignment, IndexError and KeyError mean you asked for something not there, and ValueError means the right type carrying an impossible value.

Handle expected failures with try and except for that specific exception, and let unexpected ones crash loudly so you find them. To locate a bug, print the variables just before the failing line and compare them to what you assumed, then shrink the input until you have the smallest case that still fails.

Analogy

A traceback is a receipt from a failed delivery. It names the address, the driver's route, and the reason it could not be delivered; ignoring it and reshipping blindly wastes your afternoon.

Example

A script dies with KeyError: 'price' on line 22. Printing the row just above shows the CSV header uses "Price" with a capital P, so the fix is one character, found in under a minute.

Concept 7 of 7

The standard library and pip

The fastest way to write good code is to not write it, because someone already solved the boring part correctly.

Python ships with modules covering most everyday needs: csv and json for data files, pathlib for paths, datetime for dates, re for pattern matching, random for sampling, collections for specialized containers, and math and statistics for calculations. Learning to check whether a module already exists before writing forty lines of your own is a professional habit, not a shortcut.

For everything else, pip installs third-party packages such as requests for web calls or pandas for tabular data. Create a virtual environment per project with python3 -m venv .venv and activate it, so projects do not fight over versions, and record what you installed so the project still runs next year on another machine.

Analogy

You do not forge your own screwdriver before hanging a shelf. The standard library is the toolbox that came with the house; pip is the hardware store down the road.

Example

Parsing dates by slicing strings breaks the moment a file mixes formats. Using datetime.strptime with an explicit format string parses correctly, and subtracting two datetimes gives you a timedelta with the number of days already computed.

Recap

Names hold values of specific types; if, for, and while decide which lines run and how often; functions package those lines under a name so you can reuse and test them; lists and dictionaries hold your data in the shape that makes the work easy; string methods and f-strings clean input and produce output; tracebacks tell you exactly where your assumptions were wrong; and the standard library plus pip means you write the part that is actually yours. Every Python program you will ever read is these seven ideas composed at larger and larger scale.