Python basics — study guide
The concept's fragments, read in order.
For your capstone A tool for a competitive team
The tracker is a running record of who owns which ticket and how long it took, and every one of those facts is a value with a type. A good share of the tracker's bugs start here, with a number that is secretly text.
Say two people log hours on BUG-12 as "3" and "2". The + between two strings joins them, so the total comes out "32", and type(total) reports str where you expected int. Converting first, int("3") + int("2") gives 5. The average over two entries, 5 / 2, is 2.5, a float, because / always gives one.
The moving parts of a program
A program is not magic. A running Python program holds values (a number, a piece of text, a plain yes-or-no) and gives them names so it can refer to them again. Everything larger is built by combining those values with a small set of operators and looking at the result. Master the values and the combining, and the rest of the language has something to hold onto.
Two habits make all of this approachable. First, every value has a type that decides what you can do with it, so knowing which type you hold is the first thing to check when a line misbehaves. Second, you can try a single line at a time and see its result immediately, before committing it to a saved program. That quick cycle (write a little, see what it does) is how you build trust in the pieces one at a time.
This concept is the vocabulary the whole language rests on: naming values, knowing their types, combining them with operators, dropping them into readable text, reading the yes-or-no every value quietly carries, using that yes-or-no to choose which lines run, and repeating lines with loops. None of it is throwaway. The concepts that follow assume you can already do these small things without thinking about them.
A name for a value
A variable is a name that refers to a value. You create one by writing the name, an equals sign, and a value: price = 19 makes the name price refer to the number 19. From then on, writing price anywhere means the value the name currently refers to, and Python substitutes 19 in its place.
The equals sign here is not the equals of arithmetic; it does not claim two things are already equal. It is an instruction: make this name refer to this value like a name tag you can peel off one object and stick on another: the tag is the same, but which thing it points to is up to you. Because it is an instruction and not a fact, you can point the same name at a new value later: price = 24 moves the name to a different number, and the old one is forgotten if nothing else refers to it.
Names are how a program stays readable. A value worked out once can be stored under a clear name and used in ten later lines, and a reader sees the name rather than the raw number, which says what the value is for. Choose names that describe the value (price, attempts, user_name) and the code begins to explain itself.
int, float, str, and bool
Every value in Python has a type, and the type decides what the value can do. Four types cover almost everything a first program touches: int, a whole number like 19; float, a number with a decimal point like 1.5; str, a piece of text written in quotes like "hello"; and bool, one of the two truth values True and False.
The type belongs to the value, not to the name that refers to it. 19 is an int wherever it appears, and the difference between 19 and 19.0 is exactly that one is an int and the other a float, even though they sit at the same spot on the number line. You can ask Python a value's type directly with type(19), which reports int, a useful move when a result surprises you and you want to know what you are actually holding.
Types matter because they change what an operation means and whether it is allowed at all. Two int values added give their sum; wrapping a number in quotes makes it a str, and text and numbers do not mix without a deliberate conversion such as str(19) or int("19"). Checking which type you hold is the first thing to do when a line does not behave the way you expected.
Combining values
An operator combines values into a new value. The arithmetic ones read as you would expect: + adds, - subtracts, * multiplies, and ** raises to a power, so 2 ** 3 is 8. Division has two forms: / always produces a float, so 3 / 4 is 0.75, while // divides and drops the fraction and % gives the remainder left over.
Comparison operators ask a question and answer it with a bool. 3 < 4 evaluates to True, 3 == 3 to True, and 3 == 4 to False. The double equals == tests whether two values are equal, and it is a completely different thing from the single = that binds a name to a value; confusing the two is one of the first mistakes everyone makes, and worth catching early.
What an operator does depends on the types it is given. + between two numbers adds them, but + between two strings joins them end to end, so "py" + "thon" is "python". The same symbol, read against different types, means different things, which is why keeping track of your types pays off the moment you start combining values.
Expressions and the REPL
An expression is any piece of code that evaluates to a value. 19, price, 3 + 4, and "py" + "thon" are all expressions, because Python can reduce each one to a single value. Most lines you write are expressions or contain them, and running code is, at bottom, Python evaluating expressions down to the values they stand for.
Python ships with an interactive prompt: the REPL, short for read-eval-print loop. It reads a line you type, evaluates the expression, prints the resulting value, and loops back for the next one. Type 3 + 4, press enter, and it shows 7 at once, with no ceremony. That instant feedback makes the REPL the fastest place to check what a single line actually does before it goes into a program.
A saved program does not print on its own. When Python runs a script from top to bottom, it evaluates each expression but shows you nothing unless you ask, and asking is what print is for: print(3 + 4) evaluates the expression and writes 7 to the screen. The REPL echoing a value and print displaying one look alike at the prompt, but only print produces output in a script you run later, a distinction that saves confusion the first time a program runs silently.
Values inside text
Often you want a line of text with a value dropped into it. An f-string does this directly: write the letter f immediately before the opening quote, and inside the string a name wrapped in curly braces is replaced by the value it refers to. With name referring to "Ada" and score to 91, the f-string f"{name} scored {score}" becomes the finished text Ada scored 91.
The f prefix is what switches on the substitution; without it, "{name}" is just those literal characters, braces and all. Anything not inside braces is copied through unchanged, so the surrounding words, spaces, and punctuation appear exactly as written. You can drop in as many values as you like, each in its own pair of braces.
f-strings are the ordinary way to build readable output and messages. Rather than gluing text and numbers together with + and converting types by hand, you write the sentence the way you want it read and let each pair of braces pull in its value. The intent of the line stays visible instead of being buried in concatenation.
Every value carries a yes or no
Beyond its own value, every Python value also counts as either truthy or falsy, a built-in yes-or-no that Python reads whenever a value is used as a condition. Most values are truthy. The falsy ones are a short, learnable list: False itself, the number 0 and its float 0.0, an empty string "", and the special value None. Everything else (any non-zero number, any string with characters in it) is truthy.
You can see the verdict directly by asking bool for it: bool("Ada") is True, bool("") is False, and bool(0) is False. Reading a value as truthy or falsy is like flipping a switch and seeing which way it points like reading which way a light switch points: a single glance gives a clean on-or-off without changing the switch itself; the value itself is untouched, but Python now has a clean yes or no to act on.
This yes-or-no is the raw material decisions are built from, so it is worth knowing which values are falsy before you lean on them. The usual surprise is the empty string and the number zero: both are perfectly good values, yet both count as no. Knowing that an empty piece of text reads as falsy quietly explains a great deal of everyday behavior.
Choosing which lines run
Without a way to choose, a program does exactly the same thing on every run. An if statement gives it the choice: Python evaluates the condition after if, runs the indented lines beneath it when the result is truthy, and skips them when it is falsy. With temp = 30, the line if temp > 25: followed by an indented print("hot") prints hot. Set temp = 10 instead and nothing prints; the program carries on with the next line that is not indented.
Truthy and falsy are the yes-or-no every value carries: among the values met so far, False, 0, 0.0, the empty string "", and None count as no, and the rest count as yes. The usual condition is a comparison, because temp > 25, name == "Ada", and score != 0 (!= means not equal) each evaluate straight to True or False. But any expression will do, so if name: runs its block only when name holds a non-empty string, which is either a handy shorthand or a quiet bug, depending on whether you meant it.
Two more keywords extend the choice. elif (short for else if) adds another condition, checked only when every condition before it was falsy, and else takes no condition at all and catches whatever is left. Python tests the branches in order and runs only the first one whose condition is truthy, so with temp = 18, the chain if temp > 25:, elif temp > 15:, else: runs the elif block alone. An if with an else always runs exactly one of its blocks; an if without one may run none.
Indentation is what marks a block. The colon at the end of the if, elif, or else line opens it, the lines indented beneath it belong to it, and the first line back at the outer indentation, other than an elif or else that continues the chain, is outside it and runs whatever the condition said. Python has no braces or closing keyword to fall back on, so the indentation is the structure. Indent a line by mistake just after a block and it quietly joins that block and becomes conditional. Indent one anywhere else, or put nothing indented after the colon, and Python stops with an IndentationError, which in a saved program comes before any line has run.
Repeating work
A loop runs the same indented block more than once, so a program can repeat work without repeating code. A for loop takes its values one at a time from whatever follows in. The line for i in range(3): with an indented print(i) beneath it prints 0, then 1, then 2, because range(3) counts from 0 up to but not including 3; range(1, 4) starts at 1 instead and gives 1, 2, 3.
The loop variable, here i, is an ordinary name that the loop rebinds at the start of every pass, so on each pass it holds exactly one value: the next one in line. A string can be walked the same way, one character per pass. for ch in "cat": runs its block three times, with ch referring to "c", then "a", then "t", and once the loop has finished, ch is left referring to the last value it was given, "t". The block can use the variable to build something up, so total = 0 followed by for n in range(1, 5): with an indented total = total + n leaves total at 10: on each pass Python works out the right side first, using the old value of total, then points the name at the result.
A while loop has no values to walk through, only a condition. It checks the condition before every pass, runs the block while the condition is truthy, and stops the first time it is falsy. With count = 3, a while count > 0: loop whose block prints count and then sets count = count - 1 prints 3, 2, 1 and stops, because count > 0 is False once count reaches 0. Something in the block has to move the condition toward false; if nothing does, the result is an endless loop that runs until something outside the program stops it.
The two divide the work cleanly. A for loop fits when you know what to go through, a range of numbers or the characters of a string, and a while loop fits when all you know is when to stop. Either way, the indented block under the colon is what repeats, and the first line back at the outer indentation runs once, after the loop is done.
Where this leads
These few moving parts (values with types, names that refer to them, operators that combine them, text that displays them, the truth value each one carries, and the branches and loops that decide which lines run and how often) are the entire raw material of programming. Everything more advanced is a way of organizing these parts, not a replacement for them. A large program is still, at the bottom, values being named, combined, and shown.
The concepts that come next each take one of these parts and give it more reach. Grouping many values under one name, wrapping a computation so it can be reused, checking that code does what it claims: every one of them assumes you can already name a value, know its type, and read a result. Time spent here is not throwaway beginner material; it is the ground the rest of the language stands on.
It is also enough to build something with right away. A page that greets a visitor by name, a tool that totals a team's hours, a car that reacts to a distance reading, a script that counts an agent's steps: each is, underneath, variables holding values, operators combining them, a branch or a loop deciding what runs, and f-strings turning the result into something a person can read. Learn to see programs as those pieces and the larger builds stop looking like magic.
Next on your path to A tool for a competitive team: Functions ▸