Welcome to Python Programming!

Since you’re reading this I’m hoping you’re interested in learning how to program in Python. Python is a programming language, which means it’a a language both people and computers can understand. A computer language lets people express what they want a computer to do, and tells a computer how to do it. A computer program is a set of instructions written in a particular computer language. Python was developed by a Dutch software engineer named Guido van Rossum, who created the language to solve some problems he saw in computer languages of the time. Python draws from a lot of good ideas in other languages and pulls them together in one place. Python is a pretty easy computer language to learn, and yet is very powerful.

This course uses Python 3.6.*, but the examples should work with any version of Python 3 and greater.

Elements of Programming

As you learn to program you’ll find you need to do certain things to make the program do what you want: how to make the computer do something, remember things, do things over and over and make decisions. Almost all programming languages provide ways to do these four basic things, and they’re known as:

  • Statements - the things a program can do, like performing calculations, drawing on the screen, etc.
  • Variables - these are the “things” (information) you want your program to work on and remember
  • Loops - doing things over and over again very quickly
  • Conditionals - these are choices a program can make about what to do, this is what makes programs “appear” smart.

Enough of That, Let’s Write Some Python!

Our goal is to create a Python program to draw an image on our computer screen. The image we’re going to create looks like a flower, and we’re going to learn how to use Python to create it. The end results will look something like this:

_images/flower.png

So how do we create a Python program? There are two ways to work with Python; working with it directly, and creating Python program files. This is where we can use a tool called Idle. Idle is a program to work with Python directly and create Python program files. So let’s start Idle. When you installed Python you should also have gotten the Idle program installed, if so, let’s start it up!

Starting Idle should give you a window that looks something like this:

_images/idle_window.png

This window provides a Python command prompt (hit return a couple of times if you don’t see it) that allows you to run Python statements line by line. This is called interactive mode as it allows us to ‘interact’ with Python. The command prompt in interactive mode looks like this:

>>>

Its at this prompt where you enter Python statements to try things out.

Statements

Statements are the program commands to make the computer do something in a Python program. Statements can be as simple or as complicated as we’d like to make them. Here are some examples:

>>> print("Hello there")
Hello there
>>> print(12)
12
>>> 12 * 3
36
>>> 12 / 3
4.0

The above statements print out a welcome string and a number and perform some basic math. What we’ve done above is enter some Python statements at our command prompt, and Python ran them.

Creating Python Program Files

Working with interactive mode, is great for trying things out, however, we want to create a Python program we can run over and over again without having to re-type it every time. This is where creating a Python program and saving it as a file is very handy. Python program files are just like any other text file, but have the file extension “.py”. We can create a Python program file in Idle by clicking the File -> New Window menu item. This opens up a new, empty window to a simple text editor. You’ll notice there is no >>> Python command prompt in the window. In the file window we’re not interacting with Python directly, we’re creating a Python program file. Let’s use our new Python program file to create our first Python program.

Turtle Graphics Module

Python comes with a large library of modules allowing us to do interesting things, and one of those modules is called ‘turtle’. The turtle module is a nice tool for drawing graphics on the screen. You can find the turtle graphics documentation here. The turtle module is based on the idea of a “turtle” on screen drawing a line as it moves around, as if it had a marker taped to it’s shell.

In order to use the turtle module we have to “import” it into our Python program. Importing a module adds the features and capabilities of that module to our Python program. To import the turtle module add this line to our Python program:

import turtle

Drawing With Turtle

Once the turtle module is available to us we can use it to draw things with a turtle. Enter this line into our program:

t = turtle.Turtle()
t.shape("turtle")
t.forward(100)

Saving And Running A Python Program

Once you’ve got this entered, let’s run the program. To do that we have to save the file first, which we can do from the File -> Save menu selection. Give our program a name (don’t save it with the name “turtle” as this will cause a problem) and save it to a directory on the hard disk where you can find it again. To run the program select Run -> Run Module from the Idle screen. If your program runs without any errors (which usually means you have a typo in your program), a window will open up with a turtle shape at the end of a short line. That window should look something like this:

_images/turtle_one.png

This is what our program told Python to do, use the turtle module to create a turtle we’re calling t. Our turtle, t, is the first variable we’ve created with Python in our program. The t variable is a Turtle object, all that means is t knows how to do things. After we created our t variable we told our turtle to do some of the things it knows how to do, like change it’s shape to look like a ‘turtle’ and move it forward 100 pixels.

Variables

In Python things like our turtle are represented by variables, like t. Variables let us give a name to something so you and the program can remember it and use it later. For instance, here’s a variable assignment:

x = 10

This looks a lot like algebra, and that’s actually where the idea of assigning variables came from. This simple Python statement assigns the number 10 to a variable called x. The equal sign in the line above creates the variable x and assigns it a value. In our program we’ve done the same thing using the turtle module to create a turtle (the Python statement ‘turtle.Turtle()’) and assigned the results, a turtle object, to a variable we called t.

Let’s Get Back to Drawing!

Let’s add some more statements to our program to make it draw some more. Let’s edit our Python program to look like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import turtle

t = turtle.Turtle()
t.shape("turtle")
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.color("red")
t.forward(100)
t.right(90)

When you save and run our program the screen your turtle is drawing on should look like this:

_images/turtle_two.png

So what’s going on here? What we’ve done is given our turtle a set of commands (Python program statements), and it has run them. Here’s what the statements we entered were doing:

  • Line 1 - import the turtle module so our program can use it
  • Line 3 - use the turtle module to create our turtle, t
  • Line 4 - change the shape of our turtle to look like a turtle
  • Line 5 - from where the turtle is, move forward 100 pixels
  • Line 6 - from where the turtle is, turn right 90 degrees, a right angle
  • Line 7 - from where the turtle is, move forward 100 pixels
  • Line 8 - from where the turtle is, turn right 90 degrees, a right angle
  • Line 9 - from where the turtle is, move forward 100 pixels
  • Line 10 - from where the turtle is, turn right 90 degrees, a right angle
  • Line 11 - change the color the turtle draws with to red
  • Line 12 - from where the turtle is, move forward 100 pixels
  • Line 13 - from where the turtle is, turn right 90 degrees, a right angle. This brings our turtle back to its original starting position.

These statements made the turtle draw a box with the last side of the box drawn in red. You can see something interesting about drawing with our turtle; what it draws is based on where it is on the screen and which way it’s heading.

More Drawing With Turtles

Let’s learn some more Python statements to draw with our turtles.

Turtle Speed

To make our turtle draw faster we use the turtle speed() method. To use this we’ll add this statement to our program:

t.speed(0)

The number 0 between the parenthesises is called a parameter, which is being given to the turtle’s speed method, making our turtle draw as fast as it can.

Turtle Line Width

We can make our turtle draw with a thicker line, making it easier to see on screen. We do this with the turtle width() method. We can pass a parameter to the width method, expressing a value in pixels. So for example adding this:

t.width(3)

to our program tells our turtle to draw with a line 3 pixels wide.

Filling In Shapes

We can also fill in a shape a turtle draws (like our box) with color using two other turtle methods, begin_fill() and end_fill(), and by modifying our t.color() method. If we use these Python statements:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
t.color("yellow", "red")
t.begin_fill()
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.color("red")
t.forward(100)
t.right(90)
t.end_fill()

We have told our turtle to draw with “yellow” and fill in any closed shapes with “red”. Then we use begin_fill() at the start of drawing a closed shape, draw our box and use end_fill() to fill that box with “red”.

Putting It All together

Taking the things we’ve learned from our box drawing, let’s draw something a little more complicated by drawing a sort of flower. We’ll do this by doing two things; draw multiple boxes, filling the box with color and turning the turtle slightly between each one using the new turtle methods we just learned about.

To draw our flower we’re going to draw multiple boxes, turning each box slightly every time. One way to do that would be to repeat our box code over and over like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import turtle

t = turtle.Turtle()
t.speed(0)
t.color("yellow", "red")
t.width(3)
t.shape("turtle")

# draw our first filled in box
t.begin_fill()
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.end_fill()

t.right(10)

# draw our second filled in box
t.begin_fill()
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.end_fill()

t.right(10)

# keep going till you've drawn your flower

This would work fine, but we’d have to repeat these statements as many times as we want to draw petals for our flower. One thing you should know about being a programmer is we’re very lazy and don’t like to repeat ourselves if we don’t have to. Can Python help us not repeat ourselves? Yes, it can by letting us use a loop to repeat drawing the box multiple times.

By the way, the lines beginning with # are comments and are ignored by Python. I’ve included them to indicate what’s going on in our program when I read this code later.

Loops

One of the elements of programming is being able to create loops. Loops are statements in a programming language allowing us to repeat a set of program statements over and over in a controlled way. In our program we’d like to repeat the statements:

t.begin_fill()
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.end_fill()
t.right(10)

This set of statements creates our outlined, filled in box, and turns the turtle 10 degrees. We’d like to repeat these statements in order to create the petals of our flower. Creating a loop lets us do this. One of the looping statements in Python is called a ‘for loop’, and it’s used to create a loop that repeats a fixed number of times.

Let’s do a little math to figure out how many times we need to repeat this if we want to make a full circle when our turtle is turning right by 10 degrees after every filled in box. There are 360 degrees in a full circle, and dividing a circle of 360 degrees by 10 degrees gives us a value of 36. This means we want to repeat our box 36 times in order to create our flower. How can we do this with Python?

The For Loop

We want to repeat our filled in box 36 times, so we know beforehand how many times we want to loop. This is where the Python for loop comes in handy. It is made for repeating things a known number of times. It looks like this as a Python definition statement:

for <thing> in <list of things>:
        # everything we want to do in the loop

What does this mean? That’s a kind of formal presentation of what a for loop should look like in Python. What it means is this:

  • Take one <thing> from the <list of things> and end the for statement with a : character
  • All the statements indented under the for loop should be run every time through the loop. Indentation is very important to Python by the way.
  • Go back to the start of the for loop, get another <thing> from <list_of_things>
  • Keep doing this until there are no more things in <list_of_things>

This sounds a lot harder than it actually is. In our program we’ll use the for loop like this:

for petal in range(36):
        t.begin_fill()
        t.forward(100)
        t.right(90)
        t.forward(100)
        t.right(90)
        t.forward(100)
        t.right(90)
        t.forward(100)
        t.right(90)
        t.end_fill()
        t.right(10)

Our box code is in there, under the for loop, but what’s that strange looking range(36) thing at the end of our for loop where the <list of things> should go? The range(36) thing is what provides the <list_of_things> from our formal definition of a for loop. Let’s talk about that.

The range function

To Python the range(36) function is going to provide an integer value from 0 to 35 (for a total of 36) when used inside a for loop. Each time through the for loop Python will take a value from the range 0 to 35 (most things start counting from 0 in Python) and assigns it to a variable, in our case that variable is called petal. It will continue this until there are no values left in the range. The way we’ve set things up it will loop 36 times, which is what we want. In our program as it is now we’re not using the petal variable, also known as an index variable, but we will make use of it later.

To create our flower using a for loop make our program look like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import turtle

t = turtle.Turtle()
t.speed(0)
t.color("yellow", "red")
t.width(3)
t.shape("turtle")

for petal in range(36):
    t.begin_fill()
    t.forward(100)
    t.right(90)
    t.forward(100)
    t.right(90)
    t.forward(100)
    t.right(90)
    t.forward(100)
    t.right(90)
    t.end_fill()
    t.right(10)

Let’s go through this line by line.

  • Line 1 - import our turtle module
  • Line 3 - create our turtle object and use our variable t to keep track of it
  • Line 4 - set our turtle drawing speed to fast
  • Line 5 - tell our turtle to draw in “yellow” and fill in closed shapes with “red”
  • Line 6 - set our turtle drawing width to 3 pixels
  • Line 7 - set our tutle shape to be ‘turtle’
  • Line 9 - begin our for loop and tell it to loop 36 times
  • Line 10 through 20 - draw our box, fill it in and then turn slightly right 10 degrees.

Notice how lines 10 through 20 are indented under the for loop. This is important as it tells Python all these lines are included as part of the for loop, and should be run 36 times. In Python indentation is required to tell the program a set of statements are part of a block like this.

Once you’ve got this entered, save our program and then run it. If your program runs without any syntax errors you should get a window like this:

_images/flower_single_color.png

Functions

Functions allow us to use the same set of Python statements over and over again, and even change what the Python code does without having to change the code. We used the range() function as part of our for loop. The range() function is built into Python and it generates a range of numbers we can use inside a for loop. In our program we used range(36) to generate a list of integers from 0 to 35 to draw our 36 flower petals. The 36 inside the parenthesis is called a function parameter, and allows us to change what the range function does. If we created a range statement like this, range(122), it would have generated a list of integers from 0 to 121 (rememeber we’re starting at zero).

We’ve also used functions when working with our turtle. For example when I changed the color of my turtle t with the color() function, like this:

t.color("yellow", "red")

We’re calling the color() function of the turtle variable t and passing it two parameters, “yellow” and “red”. The “yellow” parameter changed the color of the turtle variable t and the color it draws with. The “red” parameter changed the color the turtle used when filling a closed shape.

Flower Drawing Using Functions

Okay, so it’s great Python provides a bunch of functions we can use to do different things, how do functions help me be lazy? Well, Python also lets us create our own functions and use them just like we would any built in function. In Idle let’s open our turtle program code and try something out. Modify your program to look like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import turtle

t = turtle.Turtle()
t.speed(0)
t.color("yellow", "red")
t.width(3)
t.shape("turtle")

def draw_box(the_turtle):
        the_turtle.begin_fill()
        the_turtle.forward(100)
        the_turtle.right(90)
        the_turtle.forward(100)
        the_turtle.right(90)
        the_turtle.forward(100)
        the_turtle.right(90)
        the_turtle.forward(100)
        the_turtle.right(90)
        the_turtle.end_fill()

for petal in range(36):
        draw_box(t)
        t.right(10)

Save and run our program and it should create our flower exactly as it did before. You’re probably thinking “what’s the big deal, it did exactly the same thing”, and you’d be right!

The draw_box function is defined by beginning the program line with the Python keyword def, followed by a string used to name the function, parenthesis and finally a colon character ‘:’. It’s important the name of the function be one string, which is why I used the “_” underline character between the two words, draw and box.

Just like the range(36) function, where I pass it a value of 36 so it generates 36 numbers, here I’m passing a parameter I’m calling the_turtle, and it’s using it to draw with. Inside my for loop I’m calling draw_box with our t variable. This is because the variable name passed to a function as a parameter has nothing to do with the variable name inside the function when it’s defined. Notice all the drawing code in the draw_box function is indented. Just like the for loop this indicates these Python statements are part of the function definition for draw_box().

When our program runs the for loop calls our draw_box function 36 times, passing our t turtle variable 36 times, and using that parameter (the_turtle) inside the function to draw a flower petal and turn 10 degrees to the right.

Let’s Get Our Turtle Thinking!

Let’s add some decision making abilities to our flower program and have the turtle change the color it fills the petals with every so often. How can we make this happen? With the use of another of the main features of all programs mentioned at the beginning of this course, conditionals. A conditional in Python is simply an if statement:

if <condition is True>:
        # do everything indented under the if statement

An example of this at the interactive Python prompt looks like this:

    >>> if count == 4:
...         print('Equal to four')

In the above example if the program executes these statements and the variable count is equal to the integer number 4, then it will print the string ‘Equal to four’. If count is less than 4, or greater than 4 the print statement will be skipped. Notice how count is compared to the number 4, with a == (double equal sign). Using the double equal sign tells Python do perform a comparison rather than an assignment (a single equal sign).

We’ll take advantage of this decision making ability to have our turtle decide when to change the color it uses to fill in the petals of the flower. But first we’re going to learn about lists as we need a list to hold a set of colors for the turtle to pick from.

Lists

Lists are a way of grouping things together so we can work with them all at once using one variable name. There’s nothing magical about this, we can create lists easily with Python. If we enter these statements in the interactive window:

>>> my_list = [4, 2, 3, 0]
>>> print(my_list)
[4, 2, 3, 0]
>>>

We created a variable called my_list containing a list of four integers, [4, 2, 3, 0]. You can see the things in the list don’t have to be in order. Lists are created by surrounding a set of things separated by commas with the ‘[‘ and ‘]’ characters at either end. We can use a list to hold the colors we want our turtle to choose from when changing the color of a petal:

colors = ['red', 'orange', 'lightblue', 'lightgreen', 'pink', 'violet']

This creates a variable called colors containing a list of color names that are valid for turtles (just like ‘yellow’ and ‘red’ in the t.color(…) method call)

Now we have a list of colors, how do we get our turtle to decide to change the color it will use to fill a petal of our flower, and pick a color from our colors list?

First we’ll modify our draw_box function so that it accepts a second parameter called fill_color, and uses that parameter to change the color the turtle variable, the_turtle, uses to fill the petal with. The modified function looks like this:

def draw_box(the_turtle, fill_color):
        the_turtle.color('yellow', fill_color)
        the_turtle.begin_fill()
        the_turtle.forward(100)
        the_turtle.right(90)
        the_turtle.forward(100)
        the_turtle.right(90)
        the_turtle.forward(100)
        the_turtle.right(90)
        the_turtle.forward(100)
        the_turtle.right(90)
        the_turtle.end_fill()

In our main loop that draws the petals we need to make use of an if statement to decide when to change the petal color, and choose a fill color. We modify our main loop like this:

for petal in range(36):
        if petal % 3 == 0:
                color = random.choice(colors)
        draw_box(t, color)
        t.right(10)

We’ve added an if statement, and indented underneath it we’ve created a new variable color. What’s going on here? In the if statement we’re testing whether the result of petal % 3 is equal to zero. What is that doing? The % symbol is the math symbol for the modulus operator. The modulus operator is an integer division operation, but instead of returning how many times the denominator can go into the numerator, it returns the remainder of the operation. So for example 5 % 3 returns the value 2 because 3 goes into 5 one time, and leaves a remainder of 2.

Now because we’re inside the for loop, the value of the variable petal is changing every loop iteration, from 0 to 35 (what we specified with the range(36) function call). The if statement is taking the value of the petal variable and performing a modulus operation of 3 against it, and then comparing the remainder to zero to see if they are equal. The if statement will be True every third time through the loop when the value of petal is 0, 3, 6, 9, etc. This means after drawing three petals the if statement is True, the conditional statement is run and the color used to fill in a petal is changed. This continues all the way around the flower.

Let’s look at our completely modified program before we talk about what the random.choice(colors) function does:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import turtle
import random

t = turtle.Turtle()
t.speed(0)
t.color('yellow', 'red')
t.width(3)
t.shape('turtle')

colors = ['red', 'orange', 'lightblue', 'lightgreen', 'pink', 'violet']

def draw_box(the_turtle, fill_color):
        the_turtle.color('yellow', fill_color)
        the_turtle.begin_fill()
        the_turtle.forward(100)
        the_turtle.right(90)
        the_turtle.forward(100)
        the_turtle.right(90)
        the_turtle.forward(100)
        the_turtle.right(90)
        the_turtle.forward(100)
        the_turtle.right(90)
        the_turtle.end_fill()

for petal in range(36):
        if petal % 3 == 0:
                color = random.choice(colors)
        draw_box(t, color)
        t.right(10)

Looking at our program you can see that I’ve added another import statement near the top of the program at line 2, import random. This imports another Python module into our program to give it additional functionality. As random implies, it gives our program access to generating random things. This is often used in game programming to make game play different every time.

We’ve also added the line that creates our colors list at line 10, right below where we’ve declared and setup our turtle. You’ll also see the modified draw_box(…) function with it’s new second parameter, fill_color.

In our main loop you can see the if statement we’ve added, along with the use of the random.choice(colors) statement at line 27 that gets run when the if statement is True. So what does this line do:

color = random.choice(colors)

Every time it is executed it makes a call to the choice function of the random module, and picks one of the text strings inside the colors list randomly. That randomly picked text string is assigned to the colors variable, which is passed as the second parameter to the call to draw_box(t, color). Each of the text strings in the colors list variable is a valid color name a turtle understands and can use to draw and fill closed shapes with.

This means every third time through the for loop the code will randomly pick a color from our colors list and pass it to our draw_box(…) function to use as the fill color for a petal. If we run this program we should get an image something like this:

_images/flower.png

Congratulations!

We’ve completed our course and I hope you’ve had as much fun as I have! We’ve written some pretty amazing programs and learned quite a bit about programming and Python along the way. My wish is this interested you enough to keep learning about programming and to continue to discover new things you can do with Python!