Humans can actively interpret and understand what is happening around us. We take vague, incomplete instructions and fill them in using our prior experiences.
For example, we can ask a human to go to the store and buy us a soda. They’ll figure out that they’ll need some money, they’ll need to know where the closest store is, and whether it’s within walking distance or if they’ll need to drive. They may also figure out that they might need to ask us which type of soda to purchase.
With a computer, however, we’ll need to plan and account for everything. And because of the type of programming we’ll be doing, called procedural programming, we’ll need to make sure we do it all in order.
Luckily, we won’t need to create entire worlds from scratch. We won’t have to invent what money is, or what roads are, or how to move an arm.
Instead, we can leverage the work of other people, through the world of Python libraries.
As mentioned previously, there are more than a hundred thousand free libraries we can incorporate into our Python programs. Each of these extends the capabilities of Python, saving us work.
For most of this book, we’ll use a library meant for creating video games, called Pygame. Pygame gives us a way of drawing to the screen, using shapes and lines and pixels.
But before we jump into using Pygame and getting some real graphics on the screen, we’ll need to understand some fundamental concepts of programming.
For now, let’s reopen our Python terminal (also called a shell), and import the turtle library so we can start playing with the code.
Remember, the shell is executed on its own, outside of our editor:
With this code entered, a new Python Turtle Graphics drawing window should pop up, and from here we can start playing with some new programming ideas interactively in the Python shell.
Of all the tools of computation, the loop is by far the most exciting, so let’s start with it. Loops allow us to tell the computer to do things repeatedly.
When we wrote our first square using the turtle, we ended up writing the same thing over and over a few times. Let’s rewrite our first square using a loop, so we can see how loops work in Python.
In the already-open Python terminal, type the following:
Be careful with the last character at the end of the line. That’s a colon, which you get by holding down the Shift key on your keyboard and pressing the ocolon key next to the L key on an English QWERTY keyboard. After you type this out and press Enter, another line will begin, starting with
…. We’ll need to enter exactly four spaces, and then type out:
Once you hit Enter, Python will still be waiting for one more return to let it know that the code is finished, and that there are no more pieces of code that belong under the four spaces.
If you entered the code properly, and then pressed Enter twice, your turtle should draw a square all on its own!
But looping a single square isn’t really saving us that much work. Let’s see the code for drawing a 12-sided polygon instead:
Now we can really save some work!
Variables are labels used to name the things we create in our programs.
In Python, you can make up new variables out of thin air, just by creating a unique name, and assigning a value to it. Here are a couple examples:
The great thing about variables is that they’re just labels. This means you can change their meaning later, if you need to:
One tricky thing about naming variables is that they can’t begin with some of the special characters, like dashes, quotes, or numbers. Instead, they must have natural names. If you make a mistake in naming a variable, Python will usually tell you with an error that says something like “invalid syntax”.
Another tricky thing is that you shouldn’t name your variables after anything that already exists in Python. Your editor should help prevent you from doing this, but it’s something to be aware of. Try setting for equal to something in your Python terminal now to see what happens.
However, our variables need not be numbers only. In fact, variables can be words, paragraphs, complete ideas, lists of things, and more. They can represent almost any data type in Python.
Python Data Types
As stated previously, variables are just labels for things. But what are these things?
You’ve seen one of the types, called an integer. This is just a number without a decimal. We can also save numbers with decimals in Python, and add numbers with or without decimals, and negative and positive numbers too.
Numbers can also be multiplied and divided. Those both work as you’d imagine:
Remember, if we’re not assigning a value to our variable, it’s not changed by the multiplication being done to it. Our fun variable should still be equal to 18.14.
We can also set variables to be strings, or groups of words. Let’s try that now:
Addition works with strings, but subtraction does not. What happens if we try to add a number to our string?
Whoops! Python doesn’t let us mix between strings and integers. Instead, we need to convert our integer (
int) into a string (
str) for the line to work:
Another Python data type, called a list, lets us store anything in a bunch of slots. We can see an example and create one on our own by putting a bunch of things in brackets.
As with our strings, we can access each of the things in our list, starting from zero for the first thing, or element.
If you try accessing an element past the length of the list, you’ll get an error. Try that now, by entering the following (remember that Python items begin with zero):
Addition doesn’t work with lists, because it would be tricky to know what addition would mean. Instead, we can add new items to lists by using append. We get rid of things inside of lists in two ways: We can pop whatever is at a place in the list and get back that thing, or we can remove the value from the list using remove:
At the end of the list, we added another data type, called a Boolean value. A Boolean value simply represents True or False. It’s a way of saying Yes or No, really. Because it’s a data type, you can assign it to a variable.
One tricky thing about
False is that they must be capitalized in Python. If you don’t capitalize them, they can just be regular old variable names, which can break things in weird ways, when you assume that they should work.
We use Boolean values often when we’re trying to decide between running two distinct parts of our program, or to determine when we should leave a loop. This is called control flow.
How do you get a computer to decide what it should do next? Should it stop, should it loop? Should it skip the next section?
Generally, we use a conditional, or a Boolean value, to represent our decision.
If our user enters square, we draw a square; if our user enters triangle, we draw a triangle.
Boolean logic provides built-in ways to check for conditions in Python.
We can check whether numbers are larger than one another, less than one another, or equal to one another. We can also check whether strings are equal.
The way we ask Python whether two things are equal, instead of assigning the right to the left, is by using two equals in a row, like this:
==. Here are some examples of other comparisons:
To use this Boolean logic to decide which code to run, we have a few special statements.
We use the if statement to decide whether we should do something. If we want to do something else instead, we use an else statement. If we need to check for other conditions besides our if, we can add an elif before our else statement.
Just as with our loop, each of these statements gets its own white space, with four blank spaces before all the things that belong to it that should be executed.
Speaking of loops, we can use while loops to run the same code over and over while something is
In addition to Boolean logic, we can also create little blocks of code we can jump to from anywhere, called functions.
Functions get the same four spaces to let the Python interpreter know which code belongs to them. They can receive and return their own variables, depending on what you pass them.
In fact, when we moved our turtle, we were calling functions. These functions were written in the turtle library as bunches of instructions to be executed. They don’t return anything, but other functions do.
Don’t worry if you don’t yet really understand functions or
if statements. We’ll address them more later. Just know that they exist, and that they can return values, or not.
The first thing you learn from writing code is how different it is from writing in the English language. This is because programming languages have what’s called a formal syntax.
Our formal language, Python, is supposed to be different from our so-called “natural language,” because it tries to get rid of any vagueness we might accidentally create with our systems. So, as much as possible, we try to make it very clear what we want our programs to do, exactly, with very specific names, and very specific syntax.
Syntax is the way our lines are formatted, and the way we use our punctuation. In Python, our “whitespaces” are very important, as is our punctuation. If we forget a colon (:), it completely changes what a line means, and can break thousands of other lines of code that are otherwise fine.
Punctuation and spacing must be precise. Coding is not like English, where commas and periods can be used wherever and still convey mostly the same meaning. As an example, each of the indents in Python code must be blocks of exactly four spaces at a time. All lines of code that belong together must use the exact same indentation, or the program won’t run at all.
The reason behind this strict spacing rule is to make Python as easy to read as possible. This is one of the core goals of the Python programming language, compared to other languages.
The way we get feedback about when we have broken syntax is through our debugger. It tries running our code, and if something goes wrong, tries to help. The debugger will usually dump out an error message, along with a line number. The line number it dumps out might contain the error within it, or it might be in the preceding line.
Bringing It All Together
Before we jump into writing our first advanced program, let’s write one more turtle program that incorporates all the ideas we’ve addressed in this chapter.
This is a much longer program than our first!
Take your time writing it out, and check very carefully for your quote marks, making sure each one you open is closed properly. Your editor should assist with typing it out, and each of the special commands should be displayed in different colors if you’re using Visual Studio Code to type it out.
We’ve used our else statements here, along with
elif is a way of saying “or else if.” We have a while loop, which runs the same thing repeatedly until the thing that follows is False. We let the user enter exit to determine that we’ve finished.
We also got the user’s input from our terminal with the input() function. Because it has the parentheses at the end, this lets Python know input is something that needs to be run. We’ll see functions more soon, but for now just know that this means to execute input’s code.
When input gets executed, it creates a prompt and then returns what’s entered by the user. The input() function is built into Python, so we don’t have to import anything before using it.
Once you’ve got this code running, try adding more shapes. A pentagon has five sides, and each turn is 72 degrees. A hexagon has six sides, and each turn is 60 degrees.
Do a search for “Python turtle library.” Can you find the function for drawing a circle? Can you add it to the program?
What else can you make?