Python for The Patient

Table of Contents

Yet Another Python Tutorial

A quick search will show that there is no shortage of quality introductory Python resources for the total beginner, both free and paid. Most of them presents a panorama of the language in byte-sized lessons that are not meant to be exhaustive. These resources usually have few drilling exercises, prioritizing challenges and independent reasoning. That is in contrast with beginner resources from other disciplines, such as physics and mathematics, which features dozens of simple exercises with the goal of helping the student introject the content.

Python for the Patient is a book for slow learners that favor a methodical approach instead of an overdose of micro-projects that you follow along with imperfect understanding. Every concept is explained with reasonable detail, abundant examples and exercises. Our proposed strategy differs from mere memorization because it's repetition with understanding. I have no rush to finish this book, and you should be in no rush to read it. This approach may not be hip, but is the most productive in my own use case. To me, quick introductions feel like a waste of time. I go through them as fast as I forget everything they teach. My brain requires repetition and a more reflexive pace. If that's also your case, you may find this book useful. If not, A Byte of Python, Automate the Boring Stuff with Python or Python Crash Course will probably be more efficient alternatives.

1 Conventions

01_conventions-100dpi.png

2 Installation

You can download Python for Windows, macOS, and Ubuntu Linux for free at https://python.org/downloads/.

64bit vs 32bit

Be sure to download a version of Python 3.6 or more (preferrably 3.8.0).

On the download page, you’ll find Python installers for 64-bit and 32-bit computers for each operating system, so first figure out which installer you need. If you bought your computer in 2007 or later, it is most likely a 64-bit system. Otherwise, you have a 32-bit version, but here’s how to find out for sure:

  • On Windows, select Start ▸ Control Panel ▸ System and check whether System Type says 64-bit or 32-bit.
  • On macOS, go the Apple menu, select About This Mac ▸ More Info ▸ System Report ▸ Hardware, and then look at the Processor Name field. If it says Intel Core Solo or Intel Core Duo, you have a 32-bit machine. If it says anything else (including Intel Core 2 Duo), you have a 64-bit machine.
  • On Ubuntu Linux, open a Terminal and run the command uname -m. A response of i686 means 32-bit, and x8664 means 64-bit.

Windows

Download the Python installer (the filename will end with .msi) and double-click it. Follow the instructions the installer displays on the screen to install Python, as listed here:

  1. Select Install for All Users and click Next.
  2. Accept the default options for the next several windows by clicking Next.

macOS

Download the .dmg file that’s right for your version of macOS and double-click it. Follow the instructions the installer displays on the screen to install Python, as listed here:

  1. When the DMG package opens in a new window, double-click the Python.mpkg file. You may have to enter the administrator password.
  2. Accept the default options for the next several windows by clicking Continue and click Agree to accept the license.
  3. On the final window, click Install.

Ubuntu Linux

Install Python from the Terminal by following these steps:

  1. Open the Terminal window.
  2. Enter sudo apt-get install python3.
  3. Enter sudo apt-get install idle3.
  4. Enter sudo apt-get install python3-pip.

Attribution

3 The Interactive Shell

The interactive shell is a kind of REPL (Read Eval Print Loop): a program that, once started, will standby to Read all the commands you supply it, Evaluate them according to Python's syntax1, Print the results and Loop back to its standby state.

The REPL runs on a terminal: an interface in which you enter textual commands. Commands must be exact: the computer won't guess what you mean if you type a wrong character. After typing each command, you must press Enter (sometimes called Return) in order to submit for evaluation. In this book, the character $ precedes terminal commands. Example:

$ python3 # press Enter
# the tree ">>>" signals that you're now in the Python
# shell, which is ready to accept your commands
# This is the READ phase.
>>>
# The python interpreter will parse the symbols "2" "+" and "2"
# according to its syntax, EVALUATE the expression and return its result
>>> 2 + 2
# PRINT phase
4 
# Now the interpreter LOOPs back to the initial state
>>>

In sum, Python's interactive shell will automatically respond to everything you type in it.

Opening the Interactive Shell

To open the interactive shell on Windows 10, click the Start button, type “cmd” into the search box and press Enter. Type python3 in the command prompt and press Enter.

On Ubuntu Linux, hit the Super key (sometimes called Windows Key), type "terminal" and press Enter. You can also use the keyboard shortcut Control+Alt+t. Type python3 in the Terminal and press Enter.

On macOS, open Finder, select Applications from the left side, click the arrow to expand the Utilities folder and double-click Terminal. Type python3 in the Terminal and press Enter.

You should see something like this:

Python 3.8.0 (default, Dec 17 2019, 18:31:28)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

It is very important that Python, on the first line, is followed by a number started with 3 instead of 2 (the older version). That's your system's Python version, and it must the one I'm using in this series of tutorials.

Now that you have a shell open, let's try a simple command just to see if everything is working.

>>> 2 + 2
4

4 Basic Math

Python performs all basic mathematics operations, and standard mathematics's principles are respected.

Operators

# Operator Operation Example Result
1 + Addition 2 + 2 4
2 - Subtraction 2 - 2 0
3 * Multiplication 3 * 2 6
4 / Division 3 / 2 1.5
5 // Floor Division 3 // 2 1
6 ** Exponent 3 ** 2 9
7 % Modulus/Remainder 3 % 2 1

1 to 4: work exactly like a regular calculator.

5: Works like regular division but discards everything after the dot.

6: Exponent (**) exponentiates the first operand to the power of the second.

7: returns the remainder of an integer division (non-decimal).

Order of Operations

Numerical expressions are evaluated (executed) according to the standard mathematics order, which corresponds to the mnemonic PEMDAS, from left to right:

  1. Parentheses
  2. Exponents
  3. Multiplication/Division/Modulus2
  4. Addition/Subtraction3

Numerical Examples

# 1. 
>>> (1 + 2) ** 2
9

# 2. 
>>> 1 + 2 ** 2
5

# 3. 
>>> (3 + 1) + 5 % 3
6

# 4. 
>>> (3 + 1 + 5) % 3
0

# 5. 
>>> (8 * 3) - (7 % 3)
23

# 6. 
>>> (5 - 2 ** 2) + 10
11

# 7. 
>>> (12 - 6) - 15
-9

# 8. 
>>> 3 ** 2 / 4 + 5 / 8
2.87

# 9. 
>>> 50 - 12 - 8 * 4
6

# 10. 
>>> 2 ** 3 - 5
3

Word Problems Examples

  1. Find the product of 6 and 4 and then take away 6
    • Answer: (6 * 4) - 6 = 18
  2. Find the sum of 3 and 2 and then take away 4
    • Answer: (3 + 2) - 4 = 1
  3. Divide 3 by the quotient of 8 divided by 3 to the power 2
    • Answer: 3 / (5 / 2 ** 3) = 4.8
  4. Divide the quotient of 12 by 4 to the to the power of 3 divided by 2
    • Answer: (12 / (4 ** (3 / 2))) / = 1.5
  5. Find the product of 8 times 3 minus the modulus (%) of 9 divided by 6
    • Answer: (8 * 3) - (9 % 6) = 21
  6. Add 12 to the difference between 9 and 7 to the power 2
    • Answer: ((9 - 7) ** 2) + 12 = 16
  7. Find 4 minus 12 and then subtract the difference from 25
    • Answer: (4 - 12) - 25 = -33
  8. Multiply 11 and 2 to the power of 3, divide the product by 5 to the power of 3 and multiply everything by 4
    • Answer: ((11 * (2 ** 3)) / 5 ** 3) * 4 = 2.81
  9. Subtract 2 from the remainder of 7 to the power of 2 divided by 6
    • Answer: 7 ** 2 % 6 - 1 = 0
  10. 5 to the power of 2 divided by 8. Elevate all to the power of 3.
    • Answer: (5 ** 2 / 8) ** 3 = 30.52

Basic Math Exercises

Perform the following calculations using the interactive shell.

  1. Find the sum of 6 and 4 and then take away 2
  2. Find the product of 3 and 2 and then take away 5
  3. Find 6 times 2 divided by 6
  4. Subtract the quotient of 8 divided by 7 from 9
  5. Divide 21 by the difference between 18 and 9
  6. Divide 2 by the quotient of 8 divided by 3 to the power 2
  7. Find the product of 5 times 7 minus the modulus (%) of 9 divided by 6
  8. Add 6 to the difference between 9 and 7 to the power 2
  9. Find 5 minus 18 and then subtract the difference from 22
  10. Multiply 7 and 2 to the power of 3, divide the product by 3 to the power of 2 and multiply everything by 4

Answers

5 Builtin Functions

print()

print() Basics

The print() function displays the string4 inside the parenthesis on screen. It's basic form is: print("This string will printed")

# 1. 
>>> print("Hello world!")
Hello world!
>>>

# 2. 
>>> print("Hello David!")
Hello David!
>>>

print(…, end="")

Python automatically starts a newline after printing. You can disable this functionality by explicitly telling to not add anything after the printed string.

# 3. 
>>> print("Hello world!", end="")
Hello world!>>>

As you can see in 3, Python prints Hello world!, but end="" (meaning: end print statement with empty string) prevents it from adding a newline at its end. For that reason, the prompt (>>>) is written right after the string, with no separation whatsoever.

You can use the same syntax to make print() add whatever you want after displaying the string.

# 4. 
>>> print("Hello world!", end="END-SEQUENCE")
Hello world!END-SEQUENCE>>>

Concatenation

You can concatenate (print together) any number of strings.

# 5. 
>>> print("Davi" + "Lopes" + "Ramos")
DaviLopesRamos

Notice that Python cannot guess where white-spaces should be, you gotta add them manually to each string.

# 6. 
>>> print("Davi " + "Lopes " + "Ramos")
Davi Lopes Ramos

Now my name is printed correctly.

Escaping

Suppose I wish to print the phrase "Never regret anything that made you smile." – Mark Twain. Since they distinguish the citation, I want the double quotes to be printed with the rest of the string. But, inside strings, double-quotes ("") are reserved characters. When I try to used, Python read it like string enclosure.

# 1.
>>> print(""Never regret anything that made you smile." – Mark Twain")
File "<input>", line 1
print(""Never regret anything that made you smile." – Mark Twain")
^
SyntaxError: invalid syntax

# 2.
>>> print("Never regret anything that made you smile. – Mark Twain")
Never regret anything that made you smile. – Mark Twain

As you can see in 1, the interpreter throws a syntax error on the print() statement. This happens because it considers the first set of "" to be the start and end of the string it should print. If there was nothing else inside the parenthesis, print("") would run without any errors, but, since "" represents the empty string (an string with zero characters), nothing would happen. In other words: printing an empty string is equivalent to not printing at all. But that is not what is happening in our example: after "" Python doesn't now what to do with the loose characters Never regret anything that made you smile., followed by " – Mark Twain". This form does not respect Python syntax, and that is why it cannot be executed.

Double quotes are not the only character that Python does not allow to be used inside strings. To correctly print them, we must make use of Escape Characters.

  • Escape Characters

    Escape characters are special sets of two characters that allow you to use reserved characters inside a string. They consist of a backslash (\) followed by the character that needs to be added.

    # Escape Character Description Example Output
    1 \' single quote print("\'") '
    2 \" double quote print("\"") "
    3 \n newline print("Hello\nworld") hello
            world
    4 \\ backslash print("\\") \\
    5 \t horizontal tab print("\thello") ….hello
    6 \b backspace print("abcd\b") abc
    7 \r carriage return print("abc\rdef") def
    8 \f form feed print("abc\fdef") abc

    1: Inserts the literal character ' into the string.

    2: Inserts the literal character " into the string.

    3: Short for newline character. When inserted on a string, opens a newline at that point.

    4: Since \ is itself part of every escape character, how could we insert it on a string? By following the same pattern, it becomes obvious that the backslash can simply escape itself with \\.

    5: Has a similar effect to hitting the Tab key on a text editor or word processor, inserting the amount of Tab whitespaces after the current position.

    6: Inserts a backspace, with the effect of deleting one character backwards from its current position.

    7: Only returns the characters after \r.

    8: Only returns the characters before \f.

    • More Escaping Examples
      # 1.
      >>> print("Name: Davi Ramos\nAge: 38\nNationality: Brazilian")
      # Name: Davi Ramos
      # Age: 38
      # Nationality: Brazilian
      
      # 2.
      >>> print("Let's print three \" in a row: \"\"\"\". Actually, that was 5!")
      # Let's print three " in a row: """". Actually, that was 5!
      
      # 3.
      >>> print("Let's print three \" in a row: \"\"\"\". Actually, that was 4!")
      # Let's print three " in a row: """". Actually, that was 4!
      
      # 4.
      >>> print("Please remove the last word word\b\b\b\b")
      # Please remove the last word
      
      # 5.
      >>> print("Give some space!\tOkay, thanks")
      # Give some space!        Okay, thanks
      
      # 6.
      >>> print("Ignore this\rOkay you can print now")
      # Okay you can print now
      
      # 7.
      >>> print("This message is self destructing\r")
      # NO OUTPUT
      
      # 8.
      >>> print("Print this!\fIgnore the rest...")
      Print this!
      
      # 9.
      >>> print("\fThis message is self destruting")
      # NO OUTPUT
      
      # 10.
      >>> print("Here's 5 backslashes for you!\n\\\\\\\\\\")
      # Here's 5 backslashes for you!
      

6 Variables and Data Types

Variables are an easy way to store and retrieve information from the computer's memory. Instead of manually specifying memory addresses, a labor intensive task, most programming languages allow us to designate human-friendly names for our values or set of values.

Assigning a variable in Python is intuitive, using the assignment operator =.

In Python = does means assignment, not equality or comparison. first_name = "Dave" does not compares first_name with Dave: it stores the string Dave under the first_name variable name.

On the REPL:

# 1.
>>> phrase = "Hello, world!" # assignment statement
>>> phrase                   # call variable
'Hello, world!'              # REPL echoes variable value

# 2.
>>> number1 = 10
>>> number1
10
>>> number2 = 5
>>> number2
5
>>> number1 + number2
15

# 3.
>>> txt1 = "Davi "
>>> txt2 = "Lopes "
>>> txt3 = "Ramos"
'Davi Lopes Ramos'

# 4.
>>> txt4 = "Salami"
>>> txt4
'Hello'

>>> txt4 = "Bacon"
>>> txt4
'Bacon'

Notice that the REPL automatically echoes the value of the variable. This only happens on the REPL. Later on, we'll use the print() function to achieve a similar result when running Python code from files.

In the example 1, the string "Hello, word!" is accessed via the identifier phrase. phrase is not identical to Hello, word! — it merely refers to its memory address. Just as my name, Davi Ramos, is not identical to me: it merely refers to a particular individual that, among numerous attributes, lives in Brazil and was once named Davi Ramos. But repeating every entity's attributes every time we refer to them is not very practical. That is why we use proper names, ZIP codes and variable names.

7 Input

8 lists

9 Answers

Basic Math Answers

  1. Find the sum of 6 and 4 and then take away 2
    • Answer: (6 + 4) - 2 = 8
  2. Find the product of 3 and 2 and then take away 5
    • Answer: (3 * 2) - 5 = 1
  3. Find 6 times 2 divided by 6
    • Answer: (6 * 2) / 6 = 2
  4. Subtract the quotient of 8 divided by 7 from 9
    • Answer: 9 - (8 / 7) = 7.85
  5. Divide 21 by the difference between 18 and 9
    • Answer: 21 / (18 - 9) = 2.33
  6. Divide 2 by the quotient of 8 divided by 3 to the power 2
    • Answer: 2 / (8 / 3 ** 2) = 2.25
  7. Find the product of 5 times 7 minus the modulus (%) of 9 divided by 6
    • Answer: (5 * 7) - (9 % 6) = 32
  8. Add 6 to the difference between 9 and 7 to the power 2
    • Answer: (9 - 7 ** 2) + 6 = -34
  9. Find 5 minus 18 and then subtract the difference from 22
    • Answer: (5 - 18) - 22 = -35
  10. Multiply 7 and 2 to the power of 3, divide the product by 3 to the power of 2 and multiply everything by 4
    • Answer: ((7 * 2 ** 3) / (3 ** 2)) * 4 = 24.88

Back

Footnotes:

1

The syntax of a programming language is the set of rules that defines the combinations of symbols that are considered to be a correctly structured fragment in that language. (Wikipedia)

2

The modulus operation (%) returns the remainder of an integer division. Its, therefore, it contains an implicit division. Division itself is nothing more than the inverse of multiplication. By transitive property, the three cases are in fact multiplications, justifying their identical evaluation position.

3

Addition and subtraction are the same operation, since A - B = A + (-B), justifying their identical evaluation position.

4

A string is a data type used to represent text rather than numbers.