Before practicum 8
This week we do not have a video lecture. Instead, you should read the following material (based on material from the book “How to Think Like a Computer Scientist”). While reading, try to run the examples in Python yourself and after reading solve the given exercises.
Part I: Turtle
There are many modules in Python that provide very powerful features that we can use in our own programs. A very commonly used module is math. This module allows us to use some well-known mathematical functions so we don’t have to write them ourselves. For example you can try out these commands and see what they do:
from math import * print sin(1) print ceil(3.4)
But there are also modules that allow to do some even cooler things. Some of these can send emails or fetch web pages. The one we’ll look at in this chapter called turtle allows us to draw shapes and patterns.
Our first turtle program
Let’s try out these lines in Python that import the turtle module and start drawing a rectangle.
from turtle import * forward(300) left(90) forward(200) exitonclick()
When you run this program, a new window pops up. You will see a window that looks like this:
Here are a couple of things you’ll need to understand about this program.
- The first line tells Python to load a module named turtle.
- In lines 2-4, we instruct the turtle to move forward, turn left, and move forward again, completing two sides of a rectangle.
- The last line plays a part too. When we invoke
exitonclickfunction, it pauses the execution of the program, and waits for the user to click the mouse in somewhere the window. When this click event occurs, the response is to close the turtle window and exit (stop execution of) the Python program.
Complete the rectangle!
Modify the program by adding the commands necessary to complete the rectangle.
The turtle module contains various functions. For example, you can change the color by calling
color("red") which will cause the next drawed thing to be red.
Besides changing the color you can also change the width of the line, position of the arrow in the window, the way it is facing etc. It is also possible to change the background color, title text, size and position of the window.
Try out the following program where the mentioned functionality is used. We’ve only commented those lines that are different from the previous example.
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 line blue pensize(3) # set the width of the line forward(300) left(120) forward(300) exitonclick()
Running this program will create a graphics window that looks like this:
When we run this program, this new window pops up and will remain on the screen until we click on it.
Extend this program!
- Modify this program so that before it creates the window, it prompts the user to enter the desired background color. It should store the user’s response in a variable, and modify the color of the window according to the user’s wishes. (Hint: you can find a list of permitted color names from here. It includes some quite unusual ones, like “peach puff” and “HotPink”.)
- Do similar changes to allow the user, at runtime, to set the line color.
- Do the same for the line width. Hint: your dialog with the user will return a string, but turtle’s pensize function expects its argument to be an int. So you’ll need to convert the string to an int before you pass it to pensize.
Loops to simplify a turtle program
To draw a square we’d like to do the same thing four times — move forward and turn. Instead of 8 lines to draw the four sides of a square we can do the same using just three lines:
from turtle import * for i in range(4): forward(250) left(90) exitonclick()
The values [0,1,2,3] (
range(4)) were provided to make the loop body execute 4 times. We could have used any four values. For example, consider the following program.
clr will take on each color in the list. We can even take this one step further and use the value of
clr as part of the computation.
from turtle import * for clr in ["yellow", "red", "purple", "blue"]: color(clr) forward(250) left(90) exitonclick()
In this case, the value of
clr is used to change the color. Each iteration causes
clr to change to the next value in the list.
A few more turtle functions and tricks
Turtle can also work with negative angles or distances. So
forward(-100) will move backwards, and
left(-30) turns to the right. Additionally, because there are 360 degrees in a circle, turning 30 to the left will get you facing in the same direction as turning 330 to the right! (The on-screen animation will differ, though — you will be able to tell if turtle is turning clockwise or counter-clockwise!)
This suggests that we don’t need both a left and a right turn method — we could be minimalists, and just have one method. But using both is probably easier to write and understand. There is also 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 a pen) can be picked up or put down. This allows us to move a to a different place without drawing a line. The commands/functions are:
penup() forward(100) # this moves the pen, but no line is drawn pendown()
The arrow can be replaced to have a different shape. The ones available "out of the box" are arrow, blank, circle, classic, square, triangle, turtle. You can change it like this:
You can also speed up or slow down the drawing animation speed. (Animation controls how quickly the pen turns and moves forward). Speed settings can be set between 1 (slowest) to 10 (fastest). But if you set the speed to 0, it has a special meaning — turn off animation and go as fast as possible.
We can "stamp" pen's footprint onto the canvas, and this will remain after it has moved somewhere else. Stamping works, even when the pen is up.
Let’s do an example that shows off some of these new 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() # leave an impression size = size + 3 # increase the size on every iteration forward(size) # move turtle along right(24) # and turn it exitonclick()
which generates this when run:
Turtle module also allows us to draw shapes and fill them with color. When the color is chosen (with
color("red") for example), function
begin_fill shows where to start and
end_fill where to stop filling. Function
circle draws circle.
One example - flag of Japan:
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
Choose one country's flag (with at least three colors or with more complex shape) (http://www.flags.net/) and draw it with turtle.
Part II: EasyGUI
So far we have written programs that are called command line programs. This means that we, as users, have to enter commands as text from command line to interact with the program. But usually all programs that you use daily (Word, Skype, etc) allow you to communicate via buttons and text fields etc. This way of communicating with the program is called GUI (graphical user interface). Now the turtle module was like a drawing canvas. It allows us to draw nice pictures (like in Paint :)) but doesn’t actually make it possible for us to communicate with the program, so this is not a GUI. Just a fun drawing module. :) To make a Python program that has a GUI, we can for example use EasyGUI module. EasyGUI is a module for very simple, very easy GUI programming in Python. Downloand easygui.py and put it to the same folder as your Python code, otherwise Python will not find the file.
Our first easygui program
Let’s try a couple of lines in Python to create a dialog window with 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 was the simplest dialogue window. However, we would like the user to have more options than just pressing OK. The next window has your 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 a messagebox with your selected choice:
When the user clicks on a button,
buttonbox() returns the text of the choice which is then saved into variable
pressed. If the user closes the dialogue window, then
None is returned.
Buttonboxes are 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 is to present them as a list.
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 then shows a message that is different based on what you selected:
Letting the user enter information
To allow the user to enter some information, we can use
enterbox. There is a separate functionality for asking integers, called
integerbox. Nice thing is that you can specify the upper and lower bound for the required input and the
integerbox itself will check if the input is valid. If not, it will ask it 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 + "!")
You will be prompted with 2 questions. First is done with
and second one with
and then a message is shown with
There are more different functions you can use from EasyGUI. For example you can also add images to your GUI. If you liked proramming a GUI with EasyGUI, feel free to check out more things about EasyGUI.
Home Exercise 2: Asking input with GUI
Make a program that asks the user for his/her name and his/her birth month number and then shows message that includes both the name of the user and the number of days in the entered month (for example "John's birth month 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 have written in previous homeworks.
Go to Moodle and do the eight test about this material.
Exercises were already shown in the text above (in yellow boxes). You have to submit Home Exercise 1 and Home Exercise 2.
Go to Moodle and put your solutions into Exercises 8.