Visual Summary  /  DVFZ Books

Learn the few ideas Python is built on

A beginner gets stuck on a handful of things, not on the whole language. Here is what each of them actually means.

Practical Python Programming
For Beginners  ·  Selynna Payne
DVFZ Training Consultancy Services, 2022  ·  18 chapters in 7 ideas

Scroll to begin ↓

>>> 0 1 2 3 indent depth variables indentation functions

01 The starting point

Python reads your file one line at a time

Computers are fast, accurate and completely literal. They understand machine language, a pattern of ones and zeros, and nothing else. A programming language exists to sit between you and that.

Python is interpreted, so it does not translate your whole file first and then run it. It reads a line, works out what that line means, prints anything you asked for, then loops round and does the same to the next line. The book calls this REPL: read, evaluate, print, loop.

That single fact settles a lot of early confusion. Your program runs from the top down, one statement at a time, and it goes no further than the first line it cannot make sense of.

Programming languages were developed to act as a bridge between programmers and computers.Introduction
Start here

Open a terminal and type python3. You get a >>> prompt, which is the interpreter waiting for one line. Type 3 + 2 and press enter. You have now used the whole loop.

Your program Interpreter Machine one line REPL 0 1 0 0 1 read evaluate print the result, then loop to the next line
Read a line, work out what it means, print what it produced, then start again on the line below.

02 Variables

A variable is a label on a place in memory

Hold on to this sentence: a variable is not a container that holds a value. It is a name the interpreter reserves for a location in memory, so you can find the value again without knowing where it lives.

The assignment operator does one job. Whatever sits on the right becomes the value. Whatever sits on the left becomes the name for it. You never say what kind of value it is, because the interpreter works that out for itself.

Assign to the same name a second time and you are not editing the old value. You are asking the interpreter to point that name at a new location, and the value it used to point at is released.

Variables are nothing but the memory location that is reserved by an interpreter or compiler to store values of different data types.Chapter 5, Variables
Two lines, then two more

In the shell, run these and watch the name move.

sample = 5
print(sample)
sample = 8
print(sample)
STATEMENT NAME VALUE IN MEMORY sample = 5 sample = 8 sample sample 5 8 names reassign old value released now names
Assigning again moves the label to a new place. It does not change the value the label used to point at.

03 Structure

Indentation is not decoration, it is the grammar

Most languages mark a block of code with curly braces. Python does not. It uses the empty space at the start of the line, which means the shape of your file is also its structure.

A block is a group of statements that belong together. Each time you indent one more step you open a new block that belongs to the line above it, and each time you move back to the left you close one. The interpreter reads what is nearer the left first, then works further right.

This is why a stray space is a genuine error and not a matter of taste. Move a line one step left and it stops being part of the loop above it. Choose one indent width and keep it for the whole file.

Python was designed to solve the messy implementations of the blocks problem with the help of indentation.Chapter 4, Structuring With Indentation
Read your own code from the right

Find the line indented furthest right, then read upwards and name every line it sits inside. All of them have to be running for that line to happen at all. If the answer surprises you, your indentation is wrong, not your logic.

0 1 2 2 2 3 for a in range(1, first): for b in range(a, first): result = a**2 + b**2 result2 = int(sqrt(result)) if (result - result2**2) == 0: print(a, b, result) farthest right, so it runs last each step right opens one more block
The shaded margin is the indent. Every step to the right puts the line inside the block above it.

04 Flow

A condition picks a path, a loop repeats one

These two structures turn a list of statements into a program that does something, and almost every useful program puts one inside the other.

A condition is a logical expression that Python judges to be True or False. An if runs its block when the expression is true, elif offers the next test when the one before it failed, and else catches everything left over. Only one branch ever runs.

A loop repeats a block. A for loop walks an ordered sequence, a list, a tuple or a string, taking one item at a time until there are none left. A while loop keeps going for as long as its expression stays true, which is what you use when you do not know how many turns you need.

Loops are special programming structures that are usually used to automatically iterate over an ordered sequence such as a string, tuple, or list, or to execute a programming block until a certain logical expression is not satisfied.Chapter 10, Loops
Three lines, three depths

This is the shape of most real programs: look at each item, decide, act, move on.

for val in listsample:
    if val % 2 == 0:
        print(val)
sequence items left? else block runs [1, 2, 3, 4] if val % 2 == 0: print(val) take one no yes true false repeat until the sequence is empty
The sequence drives the loop. The condition decides what happens to each item. Both answers lead back to the next one.

05 Types

The type of a value decides what an operator means

You never declare a type in Python. You write x = 56 and the interpreter decides for itself that 56 is an integer. That convenience is what makes Python dynamically typed, and it is also behind one of the most common beginner errors.

The symbol you type is not the whole instruction. A plus sign between two numbers adds them. A plus sign between two strings joins them, so "New" + "York" gives NewYork. A star between a string and a number repeats the string. Same symbol, different job, decided by what is on either side.

When the pair makes no sense, Python refuses instead of guessing. Add the number 3 to the string "Sam" and you get a TypeError, because there is no sensible answer to give you.

In Python, developers don’t need to explicitly mention their value’s data type. Python interpreter is capable enough to understand the data type value automatically.Chapter 6, Data Types
Ask the interpreter

When an operation surprises you, check the types before you check the logic.

x = 56
print(x, "is a", type(x))
56 is a <class 'int'>
what type is each side? 3 + 2 "New" + "York" 3 + "Sam" 5 NewYork TypeError int, int str, str int, str adds joins refuses
One symbol, three different jobs. The interpreter reads the type on each side before it decides what to do.

06 Errors

An error message is an address, not a verdict

Beginners read an error as proof that they cannot do this. It is better read as a short note from the interpreter naming which rule was broken and where you broke it.

Errors arrive at two different moments. A SyntaxError arrives before anything runs, because Python could not make sense of a line at all, so nothing in the file executes. Every other error arrives while the program is running, at the exact line that failed.

The name of the error is the diagnosis. IndexError means you asked a list for a position it does not have. KeyError means the key is not in the dictionary. TypeError means the two values do not go together. ZeroDivisionError means the second number was zero. ModuleNotFoundError means what you imported is not there.

Even while exactly copying the code that is present in this book, you may sometimes get errors because even a small space or indentation error can change the programming logic and, hence, can crash the interpreter that results in an error.Chapter 17, How Do Programmers Clear Errors?
Read it in this order

Line number first, then the error name, then the message. TypeError: must be 'str', not 'int' names the rule; the line number tells you where. When you expect a line to fail, wrap it in try: and handle the failure in except: so the program carries on instead of stopping.

your file every line legal? do the values fit? next line SyntaxError IndexError KeyError TypeError ZeroDivisionError nothing in the file runs raised at the failing line parse no yes, so run it no yes repeat
A syntax error stops the file before it starts. Every other error names the line that failed.

07 Reuse

Break the problem up before you write a line of it

The most useful habit in the book is not about syntax at all. Split the problem into smaller steps, solve each one on its own, then combine them. Functions are how Python lets you do that.

A function is a named block of reusable code. The keyword def starts it, the parentheses name the parameters it needs, the body does the work, and return hands one value back. Once it exists you can call it as often as you like.

Names created inside a function are local. They exist while the function runs and are invisible outside it. That is a feature, not a limit: it means you can finish one step without worrying about what the rest of the program has called things.

Divide your problem into several smaller steps and approach them individually at first. Once the individual steps are completed, you can find a way to combine these to complete your problem.Chapter 1, Good Programming Practices
Before your next program

Write the steps as plain English comments, one line per step. Then turn each line into a def with a clear name. You will write less code, and when something breaks you will already know which step to open.

20 30 50 def sum(num1, num2): result = num1 + num2 return result result is a local name num1 num2 returns local names do not leave
Arguments go in, one value comes back through return, and everything the function named on the way stays inside it.

08 The whole book

Name it, shape it, then reuse it

Python is a large language, but a beginner only gets stuck in a few places. Every one of them is on this page.

Meaning

Names and types

A variable labels a place in memory, and the type of the value there decides what each operator is allowed to do with it.

Structure

Indentation and flow

Indentation says which lines belong together. Conditions choose a path, loops repeat one, and nearly every program nests the two.

Recovery

Errors and functions

An error names the rule you broke and the line you broke it on. Functions cut the problem into steps you can fix one at a time.

The book ends with the part no summary can do for you: practise on small projects, read the official documentation before you start, and keep learning, because the tools change every year.

Get the full book on Amazon  →

Adapted from Practical Python Programming for Beginners
Selynna Payne  ·  © 2022 DVFZ Training Consultancy Services  ·  10 cited sources in the source edition