Before session 8
This week we do not have a video lecture. Instead of that, there is some reading material based on the book “How to Think Like a Computer Scientist”. As you go through the material, please run the examples.
and solve two homework tasks (in yellow boxes).
Part I: Turtle
There are many modules in Python that provide very powerful features. One of the widely used modules is math. This module contains implementations of well-known mathematical functions; therefore, we don’t have to code such mathematical functions ourselves. For example, you can try out the following commands and see what they do:
from math import * print(sin(1)) print(ceil(3.4))
Some other modules can send emails or fetch web pages. The one we’ll have a close look at in this chapter is called turtle. The module allows us to draw shapes and patterns.
Our first turtle program
The following lines of code import the module turtle and draw a rectangle.
from turtle import * forward(300) left(90) forward(200) exitonclick()
When you run this program, a new window pops up. You should see a window that looks like this:
Here is a couple of things you need to understand in this program.
- The first line tells Python to load a module named turtle.
- On lines 2-4, we instruct the turtle to draw two sides of the rectangle: move forward, turn left, and move forward again.
- The last line is also very important. When we invoke the function
exitonclick, it pauses the execution of the program, and waits for the user to click on the mouse somewhere in the window. When this click event occurs, Python closes the turtle window and exits (stops execution of) the program.
Complete the rectangle!
Modify the program by adding commands which will complete drawing the rectangle.
The turtle module contains various functions. For example, you can change the color of the line by calling
color("red") - this line of code causes the next line to be red.
Besides changing the color, you can also change the width of the line, the position of the arrow in the window, the angle it is facing etc. It is also possible to change the background color, the title text, the size and position of the window.
Try out the following program.
from turtle import * setup(800, 600) # set the window size to 800 by 600 pixels bgcolor("lightgreen") # set the window background color title("Second program") # set the window title color("blue") # make the line blue pensize(3) # set the width of the line forward(300) left(120) forward(300) exitonclick()
Running this program will create a window that looks like this:
When we run this program, the window pops up and remains on the screen until we click on it.
Extend this program!
Modify this program as follows.
- Before a window pops up, the program has to prompt the user for the desired background color. Next, the program should store the user’s response in a variable, and modify the color of the window according to the user’s wish. (Hint: you can find a list of permitted color names here. The website contains some unusual color names such as “peach puff” and “HotPink”.)
- Modify the program so that the user can set the color of the line.
- Do the same for the line width. (Hint: your dialog with the user returns a string, but turtle’s pensize function expects an integer as an argument. So you’ll need to convert the string into an integer before the value is passed to the pensize function.)
Loops to simplify a turtle program
To draw a square, we need to do the same actions four times — move forward and turn. Instead of 8 lines of code to draw the four sides of a square, it is possible to draw the square in three lines of code:
from turtle import * for i in range(4): forward(250) left(90) exitonclick()
range(4) provides the values of [0,1,2,3] to execute the loop block four times.
We could have used four string values. Consider the following program. On each iteration, variable
clr is assigned one color from the list.
from turtle import * for clr in ["yellow", "red", "purple", "blue"]: color(clr) forward(250) left(90) exitonclick()
In this program, the value of
clr is used to change the color of the line. Each iteration causes
clr to take the next color from the list.
A few more turtle functions and tricks
Turtle can also work with negative values of angles or distances. For example,
forward(-100) forces the turtle to move backwards, and
left(-30) forces the turtle to turn to the right. However, turning 30 degree to the left will produce the same result as turning 330 degrees to the right since there are 360 degrees in a circle! The on-screen rotation animation will be slightly different - check if the turtle turns clockwise or counter-clockwise!
The later observation might indicate that we don’t need to use both methods (to turn either to the left or to the right). We can be minimalists, and use just one of the methods. Nevertheless, the utilisation of both methods can simplify the code and make it easier to understand.
Finally, it has to be mentioned that there is a backward method. (If you are very nerdy, you might enjoy saying
backward(-100) to move forward!)
The pen (yes, we can call this arrow as a pen) can be picked up or put down. This allows us to move the pen to a different place without drawing a line. Check the following lines of code:
penup() forward(100) # this moves the pen, but no line is drawn pendown()
The pen can be assigned a different shape. The ones available "out of the box" are arrow, blank, circle, classic, square, triangle, turtle. You can change the shape of the pen as follows:
You can also speed up or slow down the animation. In other words, you can specify how quickly the pen moves and turns on the screen. The speed settings can be set between 1 (the slowest) to 10 (the fastest). But if you set the speed to 0, it has a special meaning — turn off the animation mode and draw as fast as possible.
We can "stamp" pen's footprint into the canvas, and it remains after the pen has moved to somewhere else. Stamping works even when the pen is up.
Let’s try out an example that shows some of these features:
from turtle import * setup(800, 600) bgcolor("lightgreen") title("Spiral") shape("turtle") color("blue") penup() # this is new size = 20 for i in range(30): stamp() # put a print size = size + 3 # increase the step size on every iteration forward(size) # move the turtle along right(24) # and turn it exitonclick()
The output of the program is shown in the picture below:
Turtle module also allows us to draw shapes and fill them with colors. Choose the color (with
color("red") for example) for the shape to be filled. Function
begin_fill has to be called out before drawing a shape and
end_fill fills the shape with the color.
circle draws a circle.
The flag of Japan can be drawn as follows:
from turtle import * setup(600, 400) title("Flag of Japan") speed(10) penup() right(90) forward(100) left(90) pendown() color("red") begin_fill() circle(100) end_fill() exitonclick()
Home Exercise 1: Flag
The deadline for homework is Sunday. Nevertheless, you can start with homework already before the session.
Choose a flag of any country (with at least three colors or with a complex figure in it) (http://www.flags.net/) and draw the flag with the turtle.
Hint: you can draw all kinds of shapes and lines between
Part II: EasyGUI
So far we have created programs which are called command line programs. This means that we, as users, can interact with the program via the command line. However, usually all programs that we use daily (Word, Skype, etc) allow us to interact with the program via buttons, text fields, etc. This way of communications with the program is called GUI (graphical user interface).
The turtle module is very similar to a drawing canvas. The module allows us to draw nice pictures (like in MS Paint :)) but it doesn’t actually allow us to communicate with the program - the module turtle is not a GUI. It is simply a fun drawing module. :)
To create a Python program with a GUI, we can use EasyGUI module. EasyGUI is a module for creating a very simple and easy GUI in Python. As EasyGUI is 3rd party package, first we have to install it. Select Tools → Manage packages. Write easygui and press Find package from PyPI. Thonny will show some information about the EasyGUI module. Press Install. If the installation succeeds, Thonny will show the text Installed version: 0.98.2.
Our first easygui program
Let’s try to write a couple of lines in Python to create a dialog window with a message.
from easygui import * # in order to use EasyGui, you must import it. msgbox("My first graphical user interface!!") # message box
The output should look like this:
It is the simplest dialogue window. However, we might like to give the user more options than just pressing OK. The next window has our own set of buttons:
from easygui import * buttons = ["easy","ok","difficult"] pressed = buttonbox("Programming is ", choices = buttons) msgbox("You think that programming is " + pressed + "!")
It will ask you this question:
and then show you a message box with the selected choice:
When the user clicks on a button,
buttonbox() returns the text of the choice which is then saved into the variable
pressed. If the user closes the dialogue window, then
None is returned.
buttonbox is good for offering the user a small selection of short choices. But if there are many choices, or the text of the choices is long, then a better strategy would be to use a
from easygui import * mychoices = ["my favorite","easy","ok","difficult"] pressed = choicebox("Programming is ", choices = mychoices) if pressed == None: msgbox("You did not choose anything, you little rebel!") elif pressed == "my favorite": msgbox("Programming is your favorite course! As it should be!") else: msgbox("So you think that programming is " + pressed + ", hmm, interesting!")
This will generate the following dialogue window:
and show a message based on the selected choice:
Letting the user enter some information
To allow the user to enter some information, we can use
enterbox. The module also has a separate function to ask the user for integers -
integerbox. Nice thing is that you can specify the upper and lower case for the required input, and the
integerbox checks automatically if the input is a number. If not,
integerbox will ask the user for an integer once again.
from easygui import * name = enterbox("Hello stranger, what's your name?") age = integerbox("How old are you?", lowerbound = 1, upperbound = 150) if name == None or age == None or name == "": msgbox("Why do you have to rebel, enter things like a normal human!!") else: msgbox("Hello " + str(age) + " year old " + name + "!")
The program asks the user two questions. The first question is created using
and the second one -
Finally, a message is shown with
Home Exercise 2: Asking input with GUI
Write a program that asks the user for his/her name and the number of his/her birthday month. The program then has to show a message that contains both the name of the user and the number of days in that month (for example, "John was born in the month which has 31 days"). All information must be asked and shown with EasyGUI. To calculate the number of days in a month, use the function you wrote in one of the previous homework.
The deadline for homework is Sunday. Nevertheless, you can start with homework already before the session.
Go to Moodle and take the eighth test.
Two exercises have been presented in the text above (in yellow boxes). You have to submit Home Exercise 1 and Home Exercise 2.
Go to Moodle and upload your solutions into Exercises 8.