Values and types

Every value is an object with a type

8080intwhole numbersports, counts0.75floatfractionsratios, seconds'web-01'strtextnames, messagesTrueboolyes or noflags, test resultsNoneNoneTypeno valuenot set yet✗'8080' + 1TypeError: text and a number do not add✓int('8080') + 18081: converted firstEvery value is an object, and every object has a type.The type decides what can be done with it: numbers add, strings join. Python checks this while theprogram runs, so a type mistake only shows when that line executes. type(x) tells you what you have,and int(), float() and str() convert between them.

The type decides what a value can do. Text and numbers do not mix.

Operators · Going deeper

/ always gives a float, // rounds down, and ** binds tightest

ExpressionResultWhy7 / 2 and 6 / 23.5 and 3.0/ is true division: the result is always a float7 // 23// is floor division: it rounds down-7 // 2-4down means towards minus infinity, not towards zero-7 % 21the remainder takes the sign of the divisor2 ** 3 ** 2512** groups from the right: 2 ** 9-2 ** 2-4** binds tighter than the minus sign in front of it0.1 + 0.20.30000000000000004floats are binary fractions: compare with math.isclose()int(3.9) and round(2.5)3 and 2int() cuts off; round() goes to the even neighbour on a tie'10' < '9'Truestrings compare character by character, and '1' comes before '9'bool('False')Trueany string that is not empty counts as trueHighest first: **, then a minus sign in front, then * / // %, then + and -, then comparisons, then not, and, or.When in doubt, add brackets: they cost nothing, and the reader does not need this table. PCEP asks for results likethese by hand. Every result here was produced by Python 3.13.

/ divides exactly, // rounds down, and ** is worked out first, from the right.

Names

A variable is a name tied to an object, not a box

a = [1, 2, 3]a[1, 2, 3]one list objectb = aab[1, 2, 3]one list objectb.append(4)ab[1, 2, 3, 4]one list objectAssignment ties a name to an object. It never copies.After b = a there is still one list, with two names. A change made through either name is seen throughboth, so here a is now [1, 2, 3, 4] as well. To get a separate list, ask for one: b = a.copy(). The sameholds when a list is passed to a function: the function receives the object, not a copy.

b = a adds a second name to one object. Nothing is copied.

Names · Going deeper

Rebinding a name is not changing an object

x = 5x5an int objecty = xxy5an int objecty = y + 1xy56Cannot change in place (immutable)int float str bool tuplean "update" makes a new objectCan change in place (mutable)list dict setevery name tied to it sees the changeWith numbers and strings the surprise cannot happen.y = y + 1 builds a new object, 6, and moves the name y to it. The object 5 is untouched, so x is still 5.

y = y + 1 makes a new object. x keeps the old one.

Conditions

The first true condition wins, and indentation is the syntax

cpu = 87if cpu > 90: state = 'critical'elif cpu > 75: state = 'warning'else: state = 'ok'cpu > 9087 > 90 is Falseblock skippedFalse: try the next testcpu > 7587 > 75 is Truestate = 'warning'this block runselsenever reachedblock skippedPython tests the conditions in order and runs the first block that is true.The rest are skipped, even where they would also be true. Indentation is the syntax: the lines indentedunder an if belong to it, and four spaces is the convention. Empty values count as false: 0, an emptystring, an empty list and None. So "if servers:" reads as "if the list is not empty".

Tests run in order. The first True runs its block; the rest are skipped.

Loops

A for loop hands you each item in turn

servers = ['web-01', 'web-02', 'db-01']for s in servers: print(s, 'ok')print('done')servers'web-01'spass 1 printsweb-01 ok'web-02'spass 2 printsweb-02 ok'db-01'spass 3 printsdb-01 okAfter the loop, once: doneA for loop hands you each item in turn. There is no counter to manage.The indented line runs once per item, 3 times here; the line after the loop runs once. When you do neednumbers, range(5) gives 0 to 4. A while loop repeats as long as a condition holds, for when the numberof passes cannot be known in advance.

The indented line runs once per item. The next line runs once.

Loops · Going deeper · 1 of 2

while: repeat until something changes

wait = 1while not ready() and wait < 16: sleep(wait) wait = wait * 2If the service never answers, the loop waitspass 11 spass 22 spass 34 spass 48 sThen wait is 16, the condition is false and the loop ends after 15 seconds.A while loop tests its condition before every pass. Something inside the loop must change what thecondition looks at, or it never ends. Doubling the wait is called exponential backoff: it gives a busyservice room to recover. break leaves a loop early, and continue skips to the next pass.

A while loop needs a condition that will become false.

Loop control · Going deeper · 2 of 2

break leaves, continue skips, and else means there was no break

CallGivesrange(5)0 1 2 3 4range(2, 6)2 3 4 5range(0, 10, 3)0 3 6 9range(5, 0, -1)5 4 3 2 1range(3, 3)nothing at allrange(start, stop, step): stop itself is never included.continue: skip this itemfor s in servers: if s.startswith('db'): continue print(s)servers is ['web-01', 'db-01', 'web-02']prints web-01 and web-02break, and the else of a loopfor port in [22, 80, 443]: if port == 8080: print('found') breakelse: print('not found')prints not found: no break happenedA loop's else runs only when the loop ended without break.That makes for and else a search: break when the item is found, else when it never was. while has the same else.break leaves the innermost loop only, and continue jumps to its next pass. Because stop is excluded, range(len(x))gives exactly the valid indexes of x, and range(1, 11) counts from 1 to 10.

break leaves the loop, continue skips one pass, and a loop's else runs only if there was no break.

Functions

A function is a named step with its own private names

def state(cpu, limit=75): if cpu > limit: return 'warning' return 'ok'result = state(87)state(87)the callinside this call onlycpu87the argumentlimit75the defaultreturn'warning'resultA function is a named step with its own private names.Arguments go in and one value comes back with return. Names created inside exist only for that call, sotwo functions can both use "cpu" without clashing. A parameter with a default may be left out of thecall. A function that ends without return gives back None.

Arguments go in, return sends one value back.

Arguments · Going deeper

A default value is created once, when def runs, not on each call

✗One list, shared by every calldef add(item, seen=[]): seen.append(item) return seenadd('a') # ['a']add('b') # ['a', 'b']✓A new list for each calldef add(item, seen=None): if seen is None: seen = [] seen.append(item) return seenadd('b') # ['b']Calling def state(cpu, limit=75)state(87)by position; limit takes its default, 75state(limit=90, cpu=87)by keyword, in any orderstate(limit=90)TypeError: state() missing 1 required positional argument: 'cpu'state(cpu=87, 90)SyntaxError: positional argument follows keyword argumentdef runs once and builds each default value then. A mutable default is one object shared by every call.Use None as the default and create the list or dict inside. Numbers, strings and None are safe defaults: they cannot change.In a definition, parameters with defaults come after those without. In a call, positional arguments come before keyword ones.

Never use a list or dict as a default: use None and create it inside.

Lesson complete

You finished “Programming basics with Python”

Nicely done.

Open in a new tab