You are on page 1of 112

ITS100 Programming is fun

Python for Absolute Beginners


Introduction to Programming

Assoc. Prof. Dr. Bunyarit Uyyanonvara


Sirindhorn International Institute of Technology (SIIT)
Thammasat University

ITS100 Programming is fun

Overview
This book is the main companion of Sirindhorn International Institute of Technologys ITS100
- Introduction to computer and programming. This edition is free and for academic use only.
This book is available for free download at http://www.siit.tu.ac.th/its100.
ITS100 is one of the biggest subjects at SIIT at about 300-400 students per semester. All
students in SIIT have to pass this subject no matter they are engineering students or
management students. This subject not only teaches students how to code but also get
them to think systematically.
In designing this subject, we take into account that most of student has very little
programming background. Many of them also have limited experience in a computer-like
step-by-step procedural thinking process. Teaching this huge group of students to program
is extremely difficult. Thats why we think Python programming language is the best choice to
get them started with programming.
Python (http://www.python.org/about/gettingstarted/) is introduced and it is now widely
accepted by many universities (such as MIT, http://tinyurl.com/dxk7bsg) as an entry point for
simple programming concept. Not only the traditional lectures and labs that provide in this
subject, we also added a lot of fun activities into this ITS100 curriculum. The subject is
project-based learning subject with extra activities that are designed to make students love
programming. They should feel that programming is fun (even though it might not be easy,
but, at least, its fun.) The key word Programming is Fun will be injected into all the classes
and additional activities. The approach of the course is project-based learning.

Goals
Students who passed this subject will love programming. They will get the feeling that
programming is cool and fun. They will love SIIT for its teaching innovation.

ITS100 Programming is fun

Table of Content

Chapter 1 Introduction to programming with Python

Chapter 2 Turtle

Chapter 3 Variables

Chapter 5 Conditional Structure (if)

Chapter 4 Predefined functions

Chapter 6 Repetition Structure (for, while)

Chapter 7 User-defined function

Chapter 8 List & String Manipulation

Chapter 9 Animation & Games

ITS100 Programming is fun

Chapter 1

First-time Programmer

Learn to code is learn to think


If you choose to read this book, then I assume that you have little experience of writing a
program or, as I shall say from now, coding. I know that many of you have been asking why
do we have to write a program? Why do we have to code?. OK, thats why this chapter is
here. The chapter will get you through the basic knowledge of programming and also
introduce you to a very simple yet powerful programming language, Python.
OK, if you dont know yet why the big institutes set their curriculum so that all the students in
the institutes have to pass at least one programming course before they can graduate, you
will know in a few minutes. In my institute, no matter what major you are, engineering or
management, you will have to start your first year with a programming subject.
Coding is simply a way that we, as a human, talk to a computer. Of course, computer
doesnt understand human language directly, we need to talk (or rather to order) to it by
some specific language. Learning how to code is to learn how to talk to the most stupid
thing in the world, and thats the computer. Computer doesnt have brain like we do, it

ITS100 Programming is fun

follows our instructions exactly. You have to order it command by command. If you give the
wrong instructions, it will not do what you expected or even clash sometimes. So to make it
work for what you wanted, you have to talk to computer with very clear step-by-step
commands. You have to deliver your thought, your idea, to the most stupid thing. That
process is called coding.
If you can succeed in explaining the most stupid thing about your idea, about what you are
thinking, so you learn how to think systematically and you will then have no problem
expressing your idea or thought to someone out of your field. Learn to code is to learn to
think. Thats said by Steve Jobs. But people learn to code for different reasons, some learn
for fun, some learn for money. As you may have heard about many young students like Mark
Zuckerberg from facebook, or the talented Larry Page and Sergey Brin, the cofounder of
Google making their fortune out of coding.
Before we go further, I want to recommend you to watch the VDO on the first page of
code.org (or access it on Youtube at https://www.youtube.com/watch?v=nKIu9yen5nc) Its
just 5 minutes and you will see those great people think about coding.
Its great and inspiring, isnt it? You know what? those great people just started their big
business like you are doing now, they learn how to code for the first time. They are just like
us, know nothing about programming at the beginning. Our computers are the same as their
computers. I believe that if they can, we can. Computing business is depending hugely on
your idea. If you have a great idea, but you can not make it real, you cant translate whats in
your head to a program, then it will only be in your head. These people, they have some
good ideas, like Facebook, Google or Dropbox, and they just made it happen by coding.
Many of the richest men on earth started their fortune with simple programming. Google cofounders start Google program in their dormitory room. Facebook has its beginning in
campus. You dont have to have big computer, or big budget to start building the coolest
companies like Google or Facebook.
Programming is actually very simple. Each programming language contains a set of simple
commands. Each command is simple but by putting these simple commands together, you
can solve extremely complex problems. It is like playing chess. Each chess piece has very
simple movement pattern. You can learn to play chess very quickly in half an hour. But to be
a good chess player, you probably need years of experience. Its more of an art than a
science. Programming is the same.
OK, now you know that programming is great! Its cool! Where do we start? We start with
this chapter, of course.
Python for Beginners

!5

ITS100 Programming is fun

What is Python?
We can code using many different computer languages. We do have many of them today,
languages such as C, C++, Java, PHP, Basic or even Fortran are all in use.

But for this book, we have chosen Python as our main programming language. Python is
very modern computer language, it was developed recently so the difficulties that we found
in the older languages like C are reduced or eliminated.
Python (http://www.python.org/about/gettingstarted/) is introduced and it is now widely
accepted by many universities (such as
MIT, http://tinyurl.com/dxk7bsg) as an
entry point for simple programming
concept (as reference from the graph
to the left).
Python is an easy to learn, powerful
programming language. It has efficient
high-level data structures and a simple
but effective approach to objectoriented programming. Pythons
elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal
language for scripting and rapid application development in many areas on most platforms.
Python is powerful and fast Fans of Python use the phrase "batteries included" to
describe the standard library, which covers everything from asynchronous processing to zip
files. The language itself is a flexible powerhouse that can handle practically any problem
domain. Build your own web server in three lines of code. Build flexible data-driven code
using Python's powerful and dynamic introspection capabilities and advanced language
features such as meta-classes, duck typing and decorators.
Python lets you write the code you need, quickly. And, thanks to a highly optimized byte
compiler and support libraries, Python code runs more than fast enough for most
applications.
Python runs everywhere Python is available for all major operating systems: Windows,
Linux/Unix, OS/2, Mac, Amiga, among others. There are even versions that run on .NET and
Python for Beginners

!6

ITS100 Programming is fun

the Java virtual machine. You'll be pleased to know that the same source code will run
unchanged across all implementations.
Python is friendly... and easy to learn The Python newsgroup is known as one of the
friendliest around. Python also comes with complete documentation, both integrated into the
language and as separate web pages. Online tutorials target both the seasoned programmer
and the newcomer. All are designed to make you productive quickly. The availability of firstrate books completes the learning package.
Python is Open The Python implementation is under an open source license that makes it
freely usable and distributable, even for commercial use. The Python license is administered
by the Python Software Foundation. Most of the modern platform such as Google App
Engine supports Python.
There are lots of online materials available for Python learners. The ones I particularly want to
mention is http://www.learnpython.org/ and http://www.tutorialspoint.com/. With simple
explanations and realistic examples. These 2 webs are highly recommended. Also a live
coding window where you can put the python code and see the live results can be found
there.

Download Python
So, we will talk to computer using a Python language, but what does it really mean? It
means you needs Python interpreter on your computer, so we can write our commands onto
this interpreters editor and it will translate to computer tongue. There many editors for
Python, most of them are free but the one that we will use is IDLE which is the default
Python editor. Normally it already comes with every Mac or Linux computers. But if you are
using Windows or the version on your Mac is not up to date then you want to download and
install it on your computer first. Head for this website, http://www.python.org/download/ and
choose the program that is appropriate to your platform. We will use version 3.4.1 as our
default.
After you finish your install, you should be able to call idle or double click on it. Dont worry
about a book or manual, if you can connect to the internet, everything you need about the
programme support and documentation can be found on the Python website,
www.python.org.

Python for Beginners

!7

ITS100 Programming is fun

Hello World!
OK, everything is set. Lets do something with it.
The first program that all the experience coders coded is Hello World program. We just want
to order the computer to display this simple sentence to the screen. And the command that I
want you to know is the print command. It will just print the message you want to display
onto the screen. OK, lets have a look at some examples.
>>> print ("Hello world!")
Hello world!

>>> print ("Superman")


Superman

This command is simple. It will just display anything in between double quotes to the
screen. (Note that you can use single quotes in place of double quotes , in case you
need to display )
Commands could be sent to computer through Python in 2 different ways. The first is the
way that I just demonstrated, sending a command in the main window which is called the
command window. This way you type your one command at a time, just right after the
command prompt, >>>, and press enter. The Python interpreter will translate it and respond
with appropriate action. This is good because you can use it for quick calculations like this
one,
>>> 25 + 30
55
But this will be very slow for a big program where you need to send many or hundreds of
commands to the editor. If thats the case, you can actually put all your commands in a file.
With the list of commands in the file, you can edit it, save it and send it to run. You can
create a new file with the editors File > New menu. You get a blank editor window, then, all
the commands can be added here, like this following example.

print ("Peter Pan")


print ("Super Man")
print ("Spider Man")

Python for Beginners

!8

ITS100 Programming is fun

You can save the file and HOORAY! thats your first program! You already, officially, are a
programmer. The type for this file is .py and thats for Python. OK, now you can run the
program. You can either choose Run from the menu or press F5 on your keyboard. And the
result of your program will be shown in the command window.
Lets do something more fancy. Lets print a Christmas tree to the screen with this code.

print
print
print
print
print
print

("
*
("
* *
(" * * *
(" * * * *
("* * * * *
("
*

")
")
")
")
")
")

Now you can do lots of things here. Lets create your program and play with it. If you want to
explore further, try challenge yourself with some problems in exercise section.
With your playing, you probably notice that the command print() is very strict. It will give you
various error messages if you misspelled the command or even forgot a tiny . I told you the
you computer is not very clever. It does exactly what its told. Even when you order it with
this command,
>>>print (23+34)
23+34
It will just print exactly everything inside . If you intended to get the result of calculation, you
will have to use the print command without . To do this, everything between ( ) will be
considered as an unfinished statement and need to be processed first before printing the
result to the screen.
>>>print (23+34)
57
Be careful if the statement between ( ) cant be processed, like this following example, then
you will get an error message like this one.
>>>print (HelloWorld!)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
print (HelloWorld)
NameError: name 'HelloWorld' is not defined

Python for Beginners

!9

ITS100 Programming is fun

OK, one last thing for this first and easiest introduction to the print command is that you
have to print out the result of calculation otherwise everything is done in the background and
they will never show up for the user. Try save this example in a new .py file and run it.
print("Hello World!")
25+30
print("Hello World!")

Hello World!
Hello World!

You will only see Hello World! twice but no 55. The command 25+30 did happen but in the
background and if you didnt order the computer to print the result on the screen it will just
remain in the background (which will be extremely convenient when you have a long
calculation and dont want to display every single step of that calculation.)

Extra material
Normally the command print() will end the line with a special character \n which means
a new line. Thats why when you call the print commands for 3 times, it will print result in 3
separate lines as in the following example on the left. We can change this behaviour by
providing the 2nd parameter to the print command, end. This parameter is to specify how
the print command will be ended. In the example on the right, we give the 3rd and 4th
command with , ending and the 5th command with a full stop ending as shown in the
result.
print("Superman")
print("Superman")
print("Superman", end=", ")
print("Superman", end=", ")
print("Superman", end=".")

print("Hello World!")
print("Hello World!")
print("Hello World!")
Hello World!
Hello World!
Hello World!

Superman
Superman
Superman, Superman, Superman.

Python for Beginners

!10

ITS100 Programming is fun

Conclusion
Thats it for the introduction and your very first program. In this chapter, you learned the
easiest basic of Python programming with one commands, print( ). You can order
computer to do things with specific commands in strict patterns. After this one, you will start
to know more of the Python commands and put them together for more complex tasks. I
hope that after this class you get some inspiration and want to start writing program. In the
next chapter, we will have even more fun with some drawing and painting, of course, on
computer with Python.

Python for Beginners

!11

ITS100 Programming is fun

Exercises
1. Write a program to print names of 4 persons sitting next to you.
2. Write a program to display a car made only of *.

3. Write a program to show the ID, name and surnames of 5 people sitting next to
you in the following format.

My name is : Theo Walcott


-----------------------1: 560000001 Peter Pan
2: 560000002 Harry Potter
3: 560000021 Pat The Cat
4: 560000201 Stan The Great
5: 560000031 Super Man

4. Output this shape on the screen:

**********
*********
********
*******
******
*****
****
***
**
*

5. Write a program that prints name of your favourite movie characters in double
quotes. The program output should look like this:

My most favourite is Superman.


I also like Doraemon
And also Harry Potter

6. Write a program to display this little bunny:

(\ /)
(. .)
O(")(")

7. Write a program to show result of this calculation:


4.3533 + 233.23 - 823.144 * 5 + 21.212

Python for Beginners

!12

ITS100 Programming is fun

Chapter 2

Python and Turtles


Python Turtle
OK, you can now write some trivial programs. Now let do something a bit more fun. There is
another great feature of the Python program I want to show you. Its the extensible nature of
the Python. We can extend the core ability of Python by adding libraries into the program.
We use IMPORT command when we want to add some libraries of commands into the
program. For example we can add ability to do some complex mathematical calculations
with import math and after that point you can use all the functions in the added library. We
will discuss about Math functions pretty soon but lets begin now with something fun, the
Turtle library.
So lets begin your program with this line,
import turtle
After this command is called, you will have all functionality of a turtle.
What is Pythons Turtle? (The name sounds pretty funny now). Turtle is a drawing tool that
can be controlled by specific turtle commands. The commands are used to controlled the

ITS100 Programming is fun

movement of the turtle (or pens tip), or control the setting of colour or size of the pen. Some
examples of the commands are shown here,

Turtles movement
turtle.forward(distance) or turtle.fd(distance)
Move the turtle forward by the specified distance, in the direction the turtle is headed.
turtle.back(distance) or turtle.bk(distance) or turtle.backward(distance)
Move the turtle backward by distance, opposite to the direction the turtle is headed. Do not
change the turtles heading.
turtle.right(angle) or turtle.rt(angle)
Turn turtle right by angle units. (Units are by default degrees, but can be set via the degrees()
and radians() functions.) Angle orientation depends on the turtle mode, see mode().
turtle.left(angle) or turtle.lt(angle)
Turn turtle left by angle units. (Units are by default degrees, but can be set via the degrees()
and radians() functions.) Angle orientation depends on the turtle mode, see mode().
turtle.goto(x, y) or turtle.setpos(x, y) or turtle.setposition(x, y)
Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtles
orientation.
turtle.setx(x)
Set the turtles first coordinate to x, leave second coordinate unchanged.
turtle.sety(y)
Set the turtles second coordinate to y, leave first coordinate unchanged.
turtle.setheading(to_angle) or turtle.seth(to_angle)
Set the orientation of the turtle to to_angle. Here are some common directions in degrees:
0 - east, 90 - north, 180 - west, 270 - south
turtle.home()
Move turtle to the origin coordinates (0,0) and set its heading to its start-orientation
turtle.circle(radius, extent=None, steps=None)
radius a number, extent a number (or None), steps an integer (or None)
Draw a circle with given radius. The center is radius units left of the turtle; extent an angle
determines which part of the circle is drawn. If extent is not given, draw the entire circle. If
Python for Beginners

1
! 4

ITS100 Programming is fun

extent is not a full circle, one endpoint of the arc is the current pen position. Draw the arc in
counterclockwise direction if radius is positive, otherwise in clockwise direction. Finally the
direction of the turtle is changed by the amount of extent. As the circle is approximated by an
inscribed regular polygon, steps determines the number of steps to use. If not given, it will be
calculated automatically. May be used to draw regular polygons.
turtle.dot(size, color)
size an integer >= 1 (if given), color a colorstring or a numeric color tuple
Draw a circular dot with diameter size, using color. If size is not given, the maximum of
pensize+4 and 2*pensize is used.
turtle.speed(speed=None)
Parameters: speed an integer in the range 0..10 or a speedstring (see below)
Set the turtles speed to an integer value in the range 0..10. If no argument is given, return
current speed.
fastest: 0, fast: 10, normal: 6, slow: 3, slowest: 1

Pen control
turtle.pendown() or turtle.pd() or turtle.down()
Pull the pen down drawing when moving.
turtle.penup() or turtle.pu() or turtle.up()
Pull the pen up no drawing when moving.
turtle.pensize(width) or turtle.width(width)
Set the line thickness to width or return it. If resizemode is set to auto and turtleshape is a
polygon, that polygon is drawn with the same line thickness. If no argument is given, the
current pensize is returned.
turtle.pencolor(args)
Return or set the pencolor.
Set pencolor to colorstring, which is a Tk color specification string, such as "red", "yellow", or
"#33cc8c".
pencolor((r, g, b))
Set pencolor to the RGB color represented by the tuple of r, g, and b. Each of r, g, and b
must be in the range 0..colormode, where colormode is either 1.0 or 255 (see colormode()).

Python for Beginners

1
! 5

ITS100 Programming is fun

pencolor(r, g, b)
Set pencolor to the RGB color represented by r, g, and b. Each of r, g, and b must be in the
range 0..colormode.
fillcolor(colorstring)
Set fillcolor to colorstring, which is a Tk color specification string, such as "red", "yellow", or
"#33cc8c".
turtle.fill(flag)
Call fill(True) before drawing the shape you want to fill, and fill(False) when done. When used
without argument: return fillstate (True if filling, False else).
turtle.begin_fill()
Call just before drawing a shape to be filled. Equivalent to fill(True).
turtle.end_fill()
Fill the shape drawn after the last call to begin_fill(). Equivalent to fill(False).
turtle.reset()
Delete the turtles drawings from the screen, re-center the turtle and set variables to the
default values.
turtle.clear()
Delete the turtles drawings from the screen. Do not move turtle. State and position of the
turtle as well as drawings of other turtles are not affected.
turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))
arg object to be written to the TurtleScreen
move True/False
align one of the strings left, center or right
font a triple (fontname, fontsize, fonttype)
Write text - the string representation of arg - at the current turtle position according to align
(left, center or right) and with the given font. If move is true, the pen is moved to the
bottom-right corner of the text. By default, move is False.
turtle.hideturtle() or turtle.ht()
Make the turtle invisible. Its a good idea to do this while youre in the middle of doing some
complex drawing, because hiding the turtle speeds up the drawing observably.
turtle.showturtle() or turtle.st()
Make the turtle visible.

Python for Beginners

1
! 6

ITS100 Programming is fun

Tell Turtles state


turtle.position() or turtle.pos()
Return the turtles current location (x,y)
turtle.towards(x, y)
Return the angle between the line from turtle position to position specified by (x,y), the vector
or the other turtle. This depends on the turtles start orientation which depends on the mode
- standard/world or logo).
turtle.xcor()
Return the turtles x coordinate.
turtle.ycor()
Return the turtles y coordinate.
turtle.heading()
Return the turtles current heading (value depends on the turtle mode, see mode()).
turtle.distance(x, y=None)
Return the distance from the turtle to (x,y), the given vector, or the given other turtle, in turtle
step units.

Settings for measurement


turtle.degrees(fullcircle=360.0)
Set angle measurement units, i.e. set number of degrees for a full circle. Default value is
360 degrees.
turtle.radians()
Set the angle measurement units to radians. Equivalent to degrees(2*math.pi).

Python for Beginners

1
! 7

ITS100 Programming is fun

Explore the full functionality of the turtle on the Python official site at https://docs.python.org/
2/library/turtle.html, some useful functions are listed here.
Turtle motion

Pen control

forward() | fd()
backward() | bk() | back()
right() | rt()
left() | lt()
goto() | setpos() | setposition()
setx()
sety()
circle()
dot()
degrees()

pendown() | pd() | down()


penup() | pu() | up()
pensize() | width()
pencolor()
fillcolor()
fill()
begin_fill()
end_fill()
reset()
clear()

The turtle is initialised on the drawing board at location (0,0) and heading in 0 degree
direction. The coordinates are normal cartesian coordinates. You can move the turtle and see
the line on its trail. With this simple setting, you can use it to draw whatever you can imagine.
Now lets start drawing something. How about a rectangle? To draw a rectangle is pretty
simple, just draw a straight line, then turn 90 degree and draw another straight line. Keep on
doing this for 4 iterations and we will get a rectangle.

import turtle
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)

Save the program and run it, you will see the turtle drawing a rectangle slowly on your
screen. If you get tired of typing turtle. then you can give your turtle a nickname. Any name
you would like to call it. For example import turtle as t or even import turtle as kitty. Then
use that name instead of the word turtle.
Now let do something a little bit more complex. In this example, we will see the usage of
commands to change the size of the pen tip and also the colour. In the program, we import
the turtle with a shorter name, t. We then set the size of the pen to 10 pixels. We will draw a
circle with a radius of 100 pixels and then turn left for 90 degrees so that we can draw
another circle with a different orientation. We change the pen colour every time before we
draw a new circle. We can set colour to a specific colour names like red, green, blue or we
can use HTML colour code (more of the colour can be found here, http://

Python for Beginners

1
! 8

ITS100 Programming is fun

www.w3schools.com/html/html_colors.asp). And Keep doing this for 4 times and we get the
output displayed below.
import turtle as t
t.pensize(10)
t.pencolor("red")
t.circle(100)
t.left(90)
t.pencolor("blue")
t.circle(100)
t.left(90)
t.pencolor("yellow")
t.circle(100)
t.left(90)
t.pencolor("#FF55FF")
t.circle(100)

How about something even fancier, like a Mickey mouse. With this one, we have to do a little
bit of planning. A Mickey mouse will consist of 3 filled circle or 3 dots. One dot in the centre
and two smaller dots on the upper left and upper right. Remember, when the turtle is
initialised, it is placed at coordinates (0,0) on a cartesian plane. At that point we place a dot
of size 200 pixels. We then move our turtle to the coordinates (-90,90) which is 90 pixels to
the left and and 90 pixels up compared to the centre (0,0)
import turtle as kitty
kitty.dot(200,"black")
kitty.setpos(-90,90)
kitty.dot(100,"black")
kitty.setpos(90,90)
kitty.dot(100,"black")

Lets try another example by applying colours to many half-circles to make colourful shape.
Normally when we call a command turtle.circle(100), the turtle will draw a full circle. But if we
just want to draw part of a circle, then we have to specify the second parameter, to indicate
the angle of the circle we need to draw. (If that number is 360, it will draw a full circle, of
course). This time we are going to use turtle.circle(100,180) command to draw an arc of
half a circle. To get us a complete enclosed half circle (not just an arc), we instruct the turtle
to draw a straight line back to the original (0,0). Then we fill that half circle with what ever
colour we want. I have chosen, blue, yellow, #FE642E and #FF0040. The last two colours

Python for Beginners

1
! 9

ITS100 Programming is fun

are HTML colour code, which I picked from http://html-color-codes.info/. Then keep doing
the same thing for 4 times with different turtles headings (so that we can have the half circle
in different orientations) and you will get the shape of the right of the following code.
import turtle as t
t.setheading(0)
t.fillcolor("blue")
t.begin_fill()
t.circle(50,180)
t.goto(0,0)
t.end_fill()
t.setheading(90)
t.fillcolor("yellow")
t.begin_fill()
t.circle(50,180)
t.goto(0,0)
t.end_fill()
t.setheading(180)
t.fillcolor("#FE642E")
t.begin_fill()
t.circle(50,180)
t.goto(0,0)
t.end_fill()
t.setheading(270)
t.fillcolor("#FF0040")
t.begin_fill()
t.circle(50,180)
t.goto(0,0)
t.end_fill()

OK, one last example for the turtle. Now I want to draw a BMW logo. We begin with the
setting of the size of the pen to 4 for the line thickness and set the line colour to #C0C0C0
(thats colour of silver. I found it by Google Silver HTML colour code). The BMW logo has a
black circle background, so we draw a big black dot with size of 300 pixels (so it has a
radius of 150 pixels). We then have to conjure another 4 quarters of circle with blue and
white alternately. Lets draw the first one by moving the turtle for 100 pixels to the right
(original heading of the turtle is set to 0, meaning right). We then draw a 90-degree arc of
radius 100 pixels with command circle(100, 90). We then draw a straight line back to the
original (0,0) to close the arc and fill it with blue. For the other 3 quarters we just do the same
thing with different turtle headings and different filling colours.

Python for Beginners

2
! 0

ITS100 Programming is fun

import turtle as t
t.pencolor("#C0C0C0")
t.pensize(4)
t.dot(300,"Black")
t.setheading(0)
t.fillcolor("white")
t.begin_fill()
t.fd(100)
t.left(90)
t.circle(100,90)
t.goto(0,0)
t.end_fill()
t.setheading(90)
t.fillcolor("blue")
t.begin_fill()
t.fd(100)
t.left(90)
t.circle(100,90)
t.goto(0,0)
t.end_fill()
t.setheading(180)
t.fillcolor("white")
t.begin_fill()
t.fd(100)
t.left(90)
t.circle(100,90)
t.goto(0,0)
t.end_fill()
t.setheading(270)
t.fillcolor("blue")
t.begin_fill()
t.fd(100)
t.left(90)
t.circle(100,90)
t.goto(0,0)
t.end_fill()

Now I think you can see lots of possibilities popping up in your imagination. Lets draw those
fancy shapes in your head with Pythons turtle. If you still have no idea what to try then head
straight to the exercise section, there will be many shapes for you to start drawing.

Python for Beginners

2
! 1

ITS100 Programming is fun

Exercises
1. Write a program with Turtle to display this shape (red box in circle) on the screen:

!
2. Write a program with Turtle to display this shape (man) on the screen:

3. Write a program with Turtle to display this shape (star) on the screen:

!
4. Write a program with Turtle to display this shape (face) on the screen:

Python for Beginners

2
! 2

ITS100 Programming is fun

5. Write a program with Turtle to display this shape (rings) on the screen:

!
6. Write a program with Turtle to display this shape (Chain) on the screen:

!
7. Write a program with Turtle to display this shape (House) on the screen:

!
8. Use turtle to draw logos of Mitsubishi and Toyota

Python for Beginners

2
! 3

ITS100 Programming is fun

Chapter 3

Variables
One of the most useful and powerful concept of programming is variable and that's what
we are going to mainly focus in this chapter.
In the previous chapters, you ordered the computer to do something with specific
commands and specific values. For example, you created a square with size of 100 pixels.
You drew circles with specific radiuses. You put dots on specific locations. Imagine that we
are going to write program that let our users specify what size of the square she wants. So at
the time you write your program, you dont know exactly what size of the square the user
wants. During programming, you cant say turtle.circle(100) in your program anymore
because 100 might not be what the user wants. We have to say something like,
turtle.circle(x) instead, where x is the the unknown value the user is going to give us when
the program is run on her computer (which of course might not be the same computer you
use to write that program). So, x is what we call a variable.

ITS100 Programming is fun

Basically, a variable is a place in computers memory where you keep value. It will come into
life when you declare it. By declaration, the computer will reserve memory locations to store
values. This means that when you create a variable you reserve some space in memory.
Depends on what type of data you want for that variable, the Python interpreter allocates
memory and decides what can be stored in the reserved memory. Therefore, by assigning
different data types to variables, you can store integers, decimals or characters in these
variables.

Declaring and Assigning Values to Variables:


Python variables do not have to be explicitly declared to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The equal sign (=)
is used to assign values to variables. You have 2 operands on both sides of the equal sign.
The one on the left of the = operator is the name of the variable and the one one the right of
the = operator is the value to be stored in that variable.

x = 100
peter = 2.4345
headmaster = "John"

x, peter and headmaster are the names of variables. You assigned 100 (which is an
integer), 2.4345 (which is a floating point) and John (which is a string) to those variables
respectively.

Naming
Variable name can be can be nearly anything you want, of course, with a few exceptions.
Those common exceptions are

you cannot begin variable name with number

variable name cannot contain space

Most of special characters are prohibited (Underscore _ is OK)

And one important thing to remember about variable is that its case sensitive. Variable with
the different cases are considered different variables event though they are the same name.

SIIT

2
! 5

ITS100 Programming is fun

For example, peter, Peter and PeTer are 3 different variables. You have 5, 12 and 10 as
results in the following example:
Peter = 5
PeTer = 10
peter = 12
print(Peter)
print(peter)
print(PeTer)

5
12
10

To access the value in the variable, you just refer to the variable by its name. For example, if
you want to print the value that x stores, you say, print(x) and you will see 100 on the screen.
Be careful, print(x) will give different output. This latter will print a character x on the screen
instead of 100 because it will print exactly everything inside , remember?
Saying print(peter) and print(headmaster) will have similar effect. You will see 2.4345 and
John on the screen.

Changing Values:
Each variable can hold just one value, so if the same variable is reassigned with the new
value, it will just replace the old one. In the following example, variable x is initialised with
value 1 and later it is changed to 15 before it is changed again to 10. Its then printed. So we
will see 10 in our output at this point. x is later changed to 5 before it is printed again. So we
will have 5 too.
x = 1
x = 15
x = 10
print (x)
x = 5
print (x)

10
5

As previously mentioned, there are many types of variable. For example, a person's age is
stored as a numeric value and his name and address is stored as alphanumeric characters.
Python has various standard types that are used to define the operations possible on them
and the storage method for each of them. A few of them are just introduced here.
SIIT

2
! 6

ITS100 Programming is fun

Integer variable - a variable that keeps whole number


Floating point variable - a variable that keeps number with decimal point
String variable - a variable that keeps series of characters (or text)
Boolean variable - a variable that keeps True and False
Python is clever enough to change the type of the variable automatically. You can assign a
floating point to a variable that previously keeps integer value and Python will change the
type of that variable to floating point automatically. This is also true for other types of
variables. Look at this following example

x = 1
print (x)
x = 15.2
x = Peter pan
print (x)

Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For example:
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables. For
example:
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b, and one
string object with the value "john" is assigned to the variable c.

Mathematical Operations
You can use variables in the same way that you normally used the numbers in calculations.
For example:

SIIT

2
! 7

ITS100 Programming is fun

>>x = 2
>>y = x + 3
! 5

There are many mathematical operators that can be used in simple calculation like addition,
subtraction, multiplication and so on. The table here shows the programming symbols for
that calculations
Assume that a = 10 and b = 20, these are examples of the operations and results.

Error from data type dierence


However, mixing different types of variables in one calculation will cause a variety of
responses ranging from unexpected results to errors.

Try adding a number to a string and you will see the effect. In the following example, variable
x is an integer when a variable y is a string (notice the double quote). x + y will then spit an
error message. Just dont panic, read the error message and that can be easily identified.

SIIT

2
! 8

ITS100 Programming is fun

>>> x=5
>>> y = "5"
>>> x+y
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
x+y
TypeError: unsupported operand type(s) for +: 'int' and 'str'
!

Type cast
Python provides a clever way to change the type of variables by type-casting them with
special commands, int( ), float( ), str( ), and bool( ). The names of the commands clearly
explains themselves. See the following example.
>>> x = 1.532
>>> int(x)
1
>>> float(x)
1.532
>>> str(x)
'1.532'
>>> bool(x)
True

!
With the previous example, x is a floating point variable containing a value 1.532. Note that
when int(x) is called, the output from that function call is an integer, however the original x
still remains a floating point. But if you say something like, y = int(x), this case, x is still a
floating point, but y is an integer.

Input
Usually, we use variables at the place in the program where we do not know the value at the
time of programming. For example, we need users input for calculation. Thats where we
need another command to get input from user, in this case, from a keyboard.
x = input(Please input a number: )
!

The command for input is again very simple. Keyword input follows by (xxxx) with

SIIT

2
! 9

ITS100 Programming is fun

whatever text you want to display while waiting for users response. With the following
example, it just displays the text in double quotes and waits. After we input something, a
number or text, we then hit enter and that value will be kept in the variable x. In this particular
case x is 20.
>>> x = input(How old is Superman? :")
How old is Superman? :20
!

Important note! Variable that directly takes value from input is a string variable. So it cant
be used directly in mathematical operations. This following example is very common mistake.
x = input(How many dollars do you want to buy? )
y = input(Exchange rate (Baht per dollar) :")
payment = x * y
print(you have to pay ,payment, Baht)

Traceback (most recent call last):


File "/Users/apple/Documents/xx.py", line 3, in <module>
payment = x * y
TypeError: can't multiply sequence by non-int of type 'str'

The problem can be solves easily with the typecast functions. The correct program will look
like this:
x = int(input(How many dollars do you want to buy? ))
y = float(input(Exchange rate (Baht per dollar) :))
payment = x * y
print(you have to pay ,payment, Baht)

How many dollars do you want to buy? 20


Exchange rate (Baht per dollar) : 32.2
you have to pay 644 Baht

We enclosed the input commands in within typecast functions, int( ) and float( ) to change x
and y to integer and a floating point variable respectively.

Multiple inputs
OK, you have come this far in this chapter, so here is your bonus. After you use the input( )
command for sometimes you can notice that you can get only 1 variable per 1 input
command. And that can be annoying if we have to take many inputs in the program. With
that you have to use as many input commands. Can I get many inputs with one input
SIIT

3
! 0

ITS100 Programming is fun

command?, you may ask. Of course, you can. With a few click on the web you will see
input( ).split( ). That sounds like an alien language now. We will talk about that later but, for
now, this bonus command is to split, of course, the input into pieces and assign to multiple
variables with that one single command. Look at this following example:
>>> x, y = input("gimme two numbers: ").split()
gimme two numbers: 10 12
>>> x
'10'
>>> y
'12'

You can use it to split many values at once, but be very careful, the number of variables to
the left of = must be equal to the number of input provided by user, otherwise you will get the
error like this following example:
>>> a, b, c = input("Three numbers please: ").split()
Three numbers please: 2 12 35 24
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
a, b, c = input("Three numbers please: ").split()
ValueError: too many values to unpack (expected 3)
!

Formatted outputs
This is your second bonus. You can actually print out the values within the variables along
with normal text by separate them with , or + in the print command. In the following example,
we print a sentence My name is and follows by value in x which is Peter and then print a
space follows by a value in variable y, which is Pan
>>> x = Peter
>>> y = Pan
>>> print(My name is , x, , y)

SIIT

My name is Peter Pan

3
! 1

ITS100 Programming is fun

You can also format how a floating point number can be displayed using a %.f placeholder.
A number in front of f indicating number of decimal points to be printed.
commands

output

print(%.2f % 30.00123)

30

print (%.3f % 30.00163)

30.002

x = peter pan

My name is peter pan

print(My name is + x)

SIIT

3
! 2

ITS100 Programming is fun

Exercises
1. Write a program to get 3 inputs from user and print them in reversed order:
Enter the first number: 1
Enter the second number: 2
Enter the third number: 3
Reverse order of 1 2 3 --> 3 2 1
!

2. Write a program that takes two integer numbers and prints out the product
(multiplication) of the first and the second numbers. The program output should look like
this:
Enter the first integer number: 20
Enter the second integer number: 5
20*5 = 100
!

3. Write a program that converts a volume in milliliter to fluid ounce (1 milliliter = 0.034
ounces). The program output should look like this:
Enter a volume (in ml): 250

Volume in milliliter is 250.00


Volume in ounce is 8.50

4. Write a program that converts a temperature in Celsius (C) to Fahrenheit (F). The program
output should look like this:
Enter a temperature in C: 37
Temperature in C = 37.00
Temperature in F = 98.60
!
5. Write a program which receives three numbers a, b, c from user, and prints out the area
of triangle with edges a, b, c.

SIIT

Enter length of 3 sides of a triangle


Side A: 3
Side B: 4
Side C: 4
The area is : 6.0

3
! 3

ITS100 Programming is fun

6. Write a program to takes two integer numbers as input data and display their sum,
difference, product (multiplication). The program output should look like this:
Enter the first integer number: 8
Enter the second integer number: 22

The sum is 30
The difference is -14
The product is 176

7. Write a program that receives a three-digit integer from the user, then print out the sum of
all these three digits. Your program should response as follows:

x=123
Sum of digit = 6

8. Write a program to ask for a radius and colour of a circle and draw the circle at the
middle of the screen.

Enter the radius of circle: 100


Enter the color (red, blue, green): blue

9. Asks the positions (x,y) and radius of two circles from user. Draws these two circles and
draws a dot at the middle point between them. (Use Turtle Module)
Enter radius: 50
Enter the centre of 1st circle: -50 0
Enter the centre of 1st circle: 100 150
!

SIIT

3
! 4

ITS100 Programming is fun

Chapter 4

Predefined functions
You can already do lots of things with just three previous chapters. Lots of calculations. Lots
of drawings. You also may have noticed that, with help from some special functions
like .split() or int( ), you can do even a lot more. Those functions are called predefined
functions, the functions that has been included or built by someone and can be later
included into our program. There are myriad of those predefined functions out there. Too
many of them so that I am pretty sure that you cannot use or even cannot remember them
all. Turtle functions that you have seen and used in the first chapter are also predefined
functions. In this chapter, Ill introduce a set of mathematical functions. The rest will be up to
you to explore and use.
Maths functions are in Pythons standard library (https://docs.python.org/3/library/
index.html). This library is Pythons native built-in functions which actually means they are
always available and you dont have to download or config anything else for this commands.
You can just use them.
To start with, lets have a look at all mathematical functions listed herehttps://
docs.python.org/3/library/math.html.

ITS100 Programming is fun

Math
Similar to Turtle, to add mathematical functions to your program we need to start by
import math
With this one line of code, you add mathematical functionalities such as Power and
logarithmic functions or Trigonometric functions to your program.

Number-theoretic and representation functions


math.ceil(x) returns the ceiling of x, the smallest integer greater than or equal to x.
math.fabs(x) returns the absolute value of x.
math.factorial(x) returns x factorial. Raises ValueError if x is not integral or is negative.
math.floor(x) returns the floor of x, the largest integer less than or equal to x.
math.trunc(x) returns the Real value x truncated to an Integral (usually an integer).

Power and logarithmic functions


math.exp(x) return e**x.
math.log(x[, base])

With one argument, return the natural logarithm of x (to base e).

With two arguments, return the logarithm of x to the given base, calculated as log(x)

log(base).

math.log2(x) returns the base-2 logarithm of x. This is usually more accurate than log(x, 2).
math.log10(x) returns the base-10 logarithm of x. Usually more accurate than log(x, 10).
math.pow(x, y) returns x raised to the power y.
math.sqrt(x) returns the square root of x.

SIIT

3
! 6

ITS100 Programming is fun

Trigonometric functions
math.acos(x) returns the arc cosine of x, in radians.
math.asin(x) returns the arc sine of x, in radians.
math.atan(x) returns the arc tangent of x, in radians.
math.cos(x) returns the cosine of x radians.
math.sin(x) returns the sine of x radians.
math.tan(x) returns the tangent of x radians.

Angular conversion
math.degrees(x) converts angle x from radians to degrees.
math.radians(x) converts angle x from degrees to radians.

Constants

SIIT

math.pi

The mathematical constant = 3.141592..., to available precision.

math.e

The mathematical constant e = 2.718281..., to available precision.

3
! 7

ITS100 Programming is fun

Exercises
1. Many foreigners have difficulties in understanding the traditional Thai system to measure
the area of a piece of land. In the past, Thai people used terms such as Rai, Ngan, and
Tarangwa. Your task is to create a program that takes the inputs of the area of a piece of
land described using these three traditional Thai units to output the total area of this piece
of land in square meters. The conversion table and examples of the program interface is
as follow.

Conversion Table
1 Rai = 4 Ngan = 400 Tarang Wa = 1600 square meters
1 Ngan = 100 Tarang Wa = 400 square meters
1 Tarang Wa = 4 squared meters

Input the number of Rai: 2


Input the number of Ngan: 0
Input the number of Tarangwa: 40
The total area of the is is 3360 square meters
!

2. Write a program to find the distance, d, between points A and B where the positions of A
and B are specified by the Cartesian coordination of (x1, y1) and (x2, y2), respectively.
! d = (x1 x2 )2 + (y1 y2 )2
Enter the first point: 1 1
Enter the second point: 5 5
The distance between (1, 1) and (5, 5) is 5.66.
!

3. The period of one swing of a simple pendulum, T, is given by


! T = 2

where (in metric units) T= period (sec), l = length of pendulum (m), g= gravitational
acceleration = 9.81 m/sec2

Write a program capable of computing the period, T, for user inputting the length of a

SIIT

3
! 8

ITS100 Programming is fun

pendulum. The program output should look like this:


Enter the length of a pendulum in meter: 0.5
Period (T): 1.4
!

4. Write a program that gets 2 inputs from user, a deposit amount and interest rate in
percent, and then computes yearly interests earned for three years. Assume that the
earned interests are summed into the deposit amount every year. The program output
should look like this:
Input amount: 100
Yearly interest rate: 5

At the end of year 1 - Interest:


At the end of year 2 - Interest:
At the end of year 3 - Interest:

5.0 new balance: 105.0


5.25 new balance: 110.25
5.5125 new balance: 115.7625

5. Write a program that takes the three coefficients of a quadratic equation, a, b and c and
find its roots.

! root1 =

b + b 2 4ac
2a

! root 2 =

and

b b 2 4ac

2a

Note that: the program may give error if this term, ! b 2 4ac is less than 0, because the
root is imaginary and cannot be computed. Just dont worry about it for now. The
program output should look like this:
Enter a value for a: 1
Enter a value for b: -3
Enter a value for c: -4
!

SIIT

The roots are 4 and -1.

3
! 9

ITS100 Programming is fun

6. Write a program that computes duration of projectiles flight and its height above the
ground when it reaches the target.

Input an angle in radian: 0.5236


Input a distance to target: 100
Input a projectile velocity: 80
The flight will take 1.44 seconds.
!

7. Write a program that calculates the area of the trapezoid.

! area =

a+b
h
2

Enter a: 3
Enter b: 5
Enter h: 2.5
! The area of trapezoid is 10.00

SIIT

4
! 0

ITS100 Programming is fun

8. You are designing a new aquarium that contains a walkway for visitors to walk through
the aquarium to see different kinds of animals in the aquarium, and you want to know
how much water is needed to fill up your aquarium for animals to live. Assume that the
aquarium has a rectangular shape that contains a cylindrical walkway to allow people to
walkthrough the aquarium from one end to the other, your task is to create a program
which takes in the dimensions of the aquarium and the pathway in meters to calculate for
the volume of water needed to fill up the aquarium. (Note that the length of the aquarium
is the same as the length of the walk way because it connects with both ends of the
aquarium.) The formulae to calculate the volume of both shapes, the design of the
aquarium, and the example of the interface of the program are as follow.

Volume of Rectangular Shape = Width x Length x Height


Volume of Cylinder = x radius2 x Length

Input
Input
Input
Input

the
the
the
the

width of the aquarium: 22.5


length of the aquarium: 325.8
height of the aquarium: 7.6
radius of the walkway: 1.3

The amount of water needed is 53982.033 cubic meters


"

9. Write a program to draw a board of 2x2 cells by using turtle module. User must enter the
length of the board from keyboard and use this length to draw the board. Note that the
turtle can start and stop at any points.
!

SIIT

Length: 200

4
! 1

ITS100 Programming is fun

10. Find the biggest circle in the rectangle. Get the width and the height of rectangle from
user. Print out the radius and the area of circle and use python module draw this circle at
the middle of the rectangle. (Area of circle)
Enter the width of rectangle: 300
Enter the height of rectangle: 150
The radius of the biggest circle in this rectangle is 75.0
The area of the circle is 17671.46
!

"

SIIT

4
! 2

ITS100 Programming is fun

Chapter 5

Conditional Structures

if
One of the very common situations when you write program is that you need the program to
make decision for you. You may give it some conditions, and if the condition is true, you
want it to do one thing or otherwise if the condition is false then do another thing. Thats the
main topic for this chapter.
In Python we use a reserved word, if , for decision making. The usage pattern of this
command is very simple. Just if follows by a condition and a colon :
if condition:
statement to execute if the condition is true.
!
If the given condition is true then the following indented statement will be executed,
otherwise it will be skipped. See very simple example below:

ITS100 Programming is fun

x = 3
if x>2:
print("Superman!")
Superman!

!
In this example, the if will check whether x is actually more than 2. We saw the word
Superman! because the condition is actually true but if we changed the value of x to 2 than
nothing will be printed from this example because the condition is false.
You may want to print or execute more than one statement if the condition is true and you
can do so by providing all that statements in the same indentation with the first one. The
same indentation indicates that all of that statements are in the same block of code. With
this, if the condition is true, the whole block will be executed but if the condition is false the
whole block will also be skipped at once. So be very careful, indentation is very important
in Python programming. The indentation is how Python knows that a particular block of code
is separate from the code around it. The number of spaces used is important, and a Pythonoriented programming editor will always carefully help you maintain the proper indentation for
the code that is being written. The number of spaces is relevant, so it is important to use the
editor to determine your indentation and not change the number of spaces manually.
x = 3
if x>2:
print("Superman")
print("Supermom")
print("Supergirl")

x = 2
if x>2:
print("Superman")
print("Supermom")
print("Supergirl")

Superman
Supermom
Supergirl

if..else
The else statement is an optional statement and there could be, at most, only one else
statement following an if . An else statement can be combined with an if statement. An else
statement contains the block of code that executes if the conditional expression in the if
statement resolves to 0 or a false value.
Following is the general from of a typical decision making structure found in most of the
programming languages:
SIIT

4
! 4

ITS100 Programming is fun

x = 3
if x>0: print("Superman")
else: print("Supermom")

x = 2
if x>2:
print("Superman")
print("Supermom")
print("Superdad")
else:
print("Spiderman")
print("Spidermom")
print("Spiderdad")

Superman

Spiderman
Spidermom
Spiderdad

For the first example, the condition x>2 is true, so Superman was printed and Supermom
was skipped. On the other hand, the condition x>2 in the second example is false so the
whole block of print(Superman), print(Supermom") and
print(Superdad)was skipped, and the Spiderman, Spidermom and Spiderdad are
printed instead.
In case that there is just one statement following the if or the else, we can put that one
statement on the same line of code with if or else for convenient and shorter code.
However, if we want to have many statements following the if or else, then they have to be
in a block of code with same indentation and cannot be on the same line with if or else.

SIIT

4
! 5

ITS100 Programming is fun

age = 16
if age>10: print(Teenagers and above)
else: print(Kids)
Teenagers and above

if..elif..else
In case that you have many conditions or many cases to compare with, its very convenient
to use special if..elif..else statement. The elif here actually is the short form of else if.
Basically, we can use both of them in exchange.

buy=5500
if buy>10000: dis=10
else:
if buy>5000: dis=8
else:
if buy>1000: dis=7
else: discount=0
print(Get ,dis,% discount)

buy=5500
if buy>10000: dis=10
elif buy>5000: dis=8
elif buy>1000: dis=7
else: discount=0
print(Get ,dis,% discount)
Get 8% discount

Get 8% discount

Both examples are equivalent, but the first one looks a lot simpler thanks to the elif
statement. One thing that we have to be careful when using if..elif..else is that the whole
statement can be thought of as one big compound statement. It will start checking the first
condition, the second, the third and so on until it finds a condition that is true, then it will
process only the statements following that condition and skip the rest of the statement. It will
not check anything in that big statement again. The effect can be clearly seen from this
following examples (modified from previous example, just to show different style of
programming to solve the same problem)
x=5500
if x>10000:
print("Discount is 10%")
elif x>5000:
print("Discount is 8%")
elif x>1000:
print("Discount is 7%")
else:
print("No discount")

x=5500
if x>10000:
print("Discount is 10%")
if x>5000:
print("Discount is 8%")
if x>1000:
print("Discount is 7%")
else:
print("No discount")

Discount is 8%

Discount is 8%
Discount is 7%

!
SIIT

4
! 6

ITS100 Programming is fun

These two snippets look very similar, one with elif and one without. For the one on the left,
when the condition x>5000 is found true, it displays the 8% sentence and skip the rest of
the statement. For the one on the right, there are 3 ifs and they are 3 different, detached
statements. When the statement x>5000 is found true, it prints 8% sentence and finishes
that statement. It then went on to the next statement, which is to check whether x>1000,
and again this is true too, so Discount is 7% is also printed (unexpectedly, maybe). Just to
make it clear, Ill give you another similar example.

print ("This is a fortune teller program!")


print ("1. Jasmine")
print ("2. Rose")
print ("3. Orchid")
c = int(input("Choose one out of 3 flowers here:"))
if c==1: print ("You are nice and clean")
elif c==2: print ("You are hot and sexy")
elif c==3: print ("You are exotic and fun")
else: print ("You are silly! I told you to choose from 1 to 3!!")

print ("This is a fortune teller program!")


print ("1. Jasmine")
print ("2. Rose")
print ("3. Orchid")
c = int(input("Choose one out of 3 flowers here:"))
if c==1: print ("You are nice and clean")
if c==2: print ("You are hot and sexy")
if c==3: print ("You are exotic and fun")
else: print ("You are silly! I told you to choose from 1 to 3!!")

The only difference between these 2 snippets is the elif in the top one and the if in the
bottom one. The first program will display only one sentence but the second program will
always display 2 sentences no matter what number you choose. These two programs look
similar but in fact they will produce different output. The above one will give the result as you
expected but the 2nd example give you unexpected results.
Note: the input( ) function returns a string to the variable c, so c is a string variable. When
you want to make a comparison to a string variable, you have to compare with 1 (a string)
not 1 (a number). You can typecast it to integer with int( ) as shown in this program.

Comparison operators
Normally the expression that we use to test for the condition is the comparisons of
somethings. Here are the list of the comparison operators that are allowed in the Python

SIIT

4
! 7

ITS100 Programming is fun

!
Note that x=5 and x==5 are different! x=5 means we assign value 5 to x where x==5 means
a question (a comparison) whether x is equal to 5 or not, if it is equal to 5 then its true or it
will be false otherwise
Note Be careful about the datatype! 5 is not equal to 5 because the first is a number
where the second is a string. So they cannot be compared. If you want to compare them,
you have to typecast one of them to be in the same type with the other.
Note Also be reminded that the input from the user is a string, so when you make a
comparison, compare it with string, not a number. Or typecast it to a number first.

Logical Values
The result of comparison will be translated into just 2 values, True or False. For example
2==2 is equivalent to a True and 2>3 is equivalent to a False. Python has a special datatype
dedicated to keeping the logical values called Boolean. So, if a type of a variable is Boolean
that variable can either be True or False. You can assign this logical value directly to a
variable with these 2 keywords, True and False. (Note that, they are case sensitive)

>>> a = True
>>> b = False
>>> c = true
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
c = true
NameError: name 'true' is not defined

The previous example shows that a variable a is a boolean variable with logical value True
but there is an error assigning value true to c. The following example shows that we can
directly assign a logical value to a variable and we can just test the variable in the if

SIIT

4
! 8

ITS100 Programming is fun

statement. In this example, Superman is printed because the condition is true and Batman is
also printed because the print(Batman) statement is not part of the if, so it will be printed
anyway no matter condition is true or false.
a = True
if a:
print(Superman)
else:
print(Spiderman)
print(Batman)
Superman
Batman

!
Python programming language assumes any non-zero and non-null values as True which
means that any variable or value that a is not equal to zero can be used as True even though
they are not a boolean variables. Either zero or null then it is assumed as False value.
Anything that has a value, number of string, will be True too. In Python, integers and strings
can be conditions of if statement. 0 and empty string are equivalent to False
x = 5
y = 2
if y-x:
print("Superman")
else:
print("Spiderman")

x = 5
if x:
print("Superman")
else:
print("Spiderman")
Superman

Superman

The first example shows that a variable x can be used as a condition for the if statement, in
this case x is not zero and Superman will be printed. For the second example, the result of
y-x which is -3 is used for the condition for if and again, its not zero so Superman will again
be printed.

Logical Operations
Normal decision making involves not just only one condition but many conditions. The
conditions can get very complex and we need logical operations to determine the final
outcome of the complex decision-making conditions.

SIIT

4
! 9

ITS100 Programming is fun

Suppose that you have to check 2 conditions whether its cold or not and whether or not its
raining. If its really cold, but its not raining, so the sentence Its cold and its raining is then
not true. Three other possibilities are shown in the table. The sentence can only be true if
both Its cold and Its raining are true.
Its cold

Its raining

Its cold and its raining

And thats where we have to use truth table.

Logical conjunction (and)


Logical disjunction is an operation on two logical values, that produces a value of true if both
of its operands are true.
X

X and Y

Logical disjunction (or)


Logical disjunction is an operation on two logical values, that produces a value of true if at
least one of its operands is true.

SIIT

X or Y

5
! 0

ITS100 Programming is fun

There are following logical operators supported by Python language. Assume that X is True
and Y is False.
operators

example

result

and

X and Y

FALSE

or

X or Y

TRUE

not

not (X or Y)

FALSE

Take a look a few examples. The first one is pretty simple, the condition is (x>0) and (y>0)
and in this case, its true, so Superman and Supergirl will be printed along with Batman
which is not part of the if-else (itll be printed no matter the condition is true or false)
x=5
y=2
if (x>0) and (y>0):
print(Superman )
print(Supergirl)
else:
print(Spiderman)
print(Spidergirl)
print (Batman)

Superman
Supergirl
Batman

The second example is similar, but this time we use conjunction, or. So if either of the
condition (status ==student) or (age<20) is true or both are true then the whole condition is
true. In this case, the first one is true, so this student can not enter.
status= student
age = 20
if (status ==student)or (age<20):
print(No entry )
else:
print(Welcome)
print (Its cool!)

No entry
Its cool!

Last example is a bit more difficult. The condition is more complex. We will go to Japan
based on 2 conditions, if we have enough money, says 100,000 Baht or if we have less than

SIIT

5
! 1

ITS100 Programming is fun

40,000 Baht but Yen is not expensive, says 10 yens is less than 3 baht, then we will still be
going.
m=50000
tenyen=4
if (m>100000) or ((m<40000) and (tenyen < 3)):
print(We will go Japan )
else:
print(Eat ramen at home)
print (and watch Batman)

eat ramen at home


and watch Batman

Nested if
In real situation, the we may have many conditions with complex relationship between them.
We have to carefully translate them into programming language. And of course, there are
normally more than one way to do that. Lets have a look at this example where we want to
classify students into many conference rooms based on the following conditions:
1. The 1st year male students go to room 209
2. The 1st year female students go to room 210
3. For the higher years, MT or EM students go to room 301
4. For the higher years, IT or CPE students go to room 302
5. For the higher years, other departments go to room 305
Lets try to solve this problem in a straight forward manner. We have to ask each student
who comes to the registration what year he is, and what department he is. And of course,
we have to tell the program whether the student is a male or female. Three inputs are
needed, then. We then need to form a list of conditions in the if..else pattern as in the
following program.
This program works well and correct but you may notice that the conditions are complex and
prone to error.

SIIT

5
! 2

ITS100 Programming is fun

year = int(input("What year are you?: ))


sex = input("male or female?: )
dept = input("What department are you?:)
if year==1 and sex == male: room = 209
elif year==1 and sex == male: room = 210
elif year>1 and (dept==MT" or dept==EM): room = 301
elif year>1 and (dept==IT" or dept==CPE): room = 302
else: room = 305
print (Your room is:", room)

However, with many complex conditions, a small mistake in one of the conditions, such as
missing of ( ) on the 3rd or 4th condition, can lead to wrong result and that mistake, if
happened, will be difficult to detect. Such a mistake is what we called a logical error. There
is nothing wrong with the code, no grammatical error, so the editor or the parser cant detect
it. Just the logic that is wrong.
We can avoid such mistake by simplify the conditions with structured, nested if..else. The
following code will produce the same result as the previous one but conditions are simpler.
We first check if the student is a first year or not, if yes then we start a new block of code
that takes input of the sex and just classify student easily with simpler condition. On the
other hand, if he is not a first year, we start a new block of code. Within that block, we check
his department and classify them into rooms with simpler conditions too.
year = int(input("What year are you?: ))
if year==1:
sex = input("male or female? ")
if sex == male": room = 209
else: room = 210
else:
dept = input("What department are you?: )
if dept=="MT" or dept==EM": room = 301
elif dept=="IT" or dept==CPE: room = 302
else: room = 305

print (Your room is:", room)

These 2 different styles have different advantages and disadvantages. The first one is simpler
in terms of programming structure. It looks very linear and simple to write. However, the
second one is simpler in terms of conditions checking. The conditions are clear and easy to
understand, but the code may be more complex. So you have to choose the style for the
appropriate problem.

SIIT

5
! 3

ITS100 Programming is fun

The following example shows very complex flowchart of the problem. It may be more
appropriate to use nested if structure than the linear one.

Conclusions
We have done the condition checking in this chapter. The command is so simple just if or
if..else and if..elif..else and you have seen that we can use this simple command in a
variety of ways to solve many problems. No matter how complex the problem is, they can be
solved with these simple if..else structure. As I told you, programming is more of an art than
a science. One simple command and if you master it, you can use it to solve many complex
problem. Just like playing chess, we can learn to move each piece easily, but to be a good
chess player we need a lot of practice. The program can get more and more complex when
the conditions or logic get complex. So keep the basic right. if follows by a condition or
conditions, then a colon : There will be many more problems of if in the exercise sections.

SIIT

5
! 4

ITS100 Programming is fun

Exercises
1. Coee shop: Your friend owns a coffee shop. In his cafe, a normal price for a cup of
coffee is 40 Baht. However, if a customer wants stronger coffee, customer can request
as many extra shots as they like with the cost of 15 Baht per extra shot. In his shop, he
also has many healthy options for his customer, like offering soy milk and natural honey. If
the customer requests for soy milk, another 10 baht will be added. If customer wants to
have natural honey instead of normal syrup, customer will have to pay another 20 Baht
extra. Thats all options he has for a cup of coffee. OK, now, he would like us to write a
program to help his barista to calculate the price for each cup of coffee.
2. Sorting Hat: Its tradition when you come to Hogwarts School of Witchcraft and
Wizardry, you will be sorted by the Sorting Hat into 1 of the 4 Houses and they are
Gryffindor, Hufflepuff, Ravenclaw and Slytherin. Rumor has it that in fact the Sorting Hat is
actually not magical but simply a Python program written by Professor Albus Dumbledore
during his 1st year at SIIT. He revealed his secret in the 8th Harry Potter and The Turtle
Python that the sorting hat will just ask for the name of the person who is wearing it. If
the name of that person begins with H, B or N (like Harry Potter, Hermione Granger or
Neville Longbottom), it will put the person in Gryffindor. If the persons name begins with
E or C (like Elephant or Cedric Diggory), the person will be Hufflepuff. The person will be
added to Ravenclaw house only if the name begins with G or L (like Gilderoy Lockhart or
Luna Lovegood). The rest of the name will be in Slytherin. Problem is the Sorting Hat has
been stolen from Hogwarts, so Prof. Dumbledore ask you to write the new one for him.
3. Car payment: Suppose that your father is the Toyota car dealer and there are 3 different
types of Toyota in his showroom.
a. Toyota Camry costs 1,700,000 Baht
b. Toyota Altis costs 900,000 Baht
c. Toyota Vios costs 559,000 Baht
Every time when customers come and ask for the details of payment, a salesperson asks
customer what type of Toyota the customer wants, a, b, or c. He then asks for how
much the customer want to put for Down payment. Then how many months is customer
willing to pay? Then the salesperson has to calculate the amount of payment the
customer has to pay each month but the whole process is slow and has lots of mistakes.
Actually, it can easily be calculated by
each month payment = (Car price - Down payment) / number of months
Can you write a program for your father so everything will be faster and correct?

SIIT

5
! 5

ITS100 Programming is fun

4. Abstract body shape: Ask a user this question, How old are you? so that the program
can predict the future shape for the user. If the users age is in between 1 - 10 then use
the Turtle to draw 2 small rectangle. If the age is more than 10 but not more than 20, the
draw a big red triangle. If more than 20 but less than 30 then draw a snow man with 3
circles. If more than 30, the draw a big fat blue circle.
5. Write a program that takes three integer numbers and show the maximum number. Only
use if( ) for comparison. Additional functions are not allowed.
Enter three integer numbers: 5 16 11
The maximum number is 16.

6. Write a program that authenticates a user by asking for her passcode. If she input a word
Secret then grant her an access, otherwise deny her access.
Enter your passcode: John
Access Denied!

Enter your passcode: Secret


Access Granted!

7. Write a program that checks whether an input integer is negative or positive.


Enter an integer number: -1
The number you enter is negative.

Enter an integer number: 10


The number you enter is positive.

8. Write a program which reads two integer values. If the first number is less than the
second number then print the message Up!. If the second number is less than the first
number, print the message Down!. If the numbers are equal, print the message
Equal!.

SIIT

5
! 6

ITS100 Programming is fun

Enter two integer numbers: 10 5


Down!

Enter two integer numbers: 2 3


Up!

9. Write a program that translates the meaning of traffic light colors. Red light is represented
by character R and green by G. If the user inputs R, the program will print out Stop.
If the user inputs G, the program will display Go!.
Input traffic light color (R=Red,G=Green): R
Stop!

10. Write a program that gets five integer values and shows the maximum and minimum
values among them.
Input1#:0
Input2#:-7
Input3#:3
Input4#:11
Input5#:4

Maximum: 11
Minimum: -7

11. Write a program that takes 3 characters and then counts the number of consonants and
vowels as shown in the following example.
Input three characters:> z H a
The number of consonants is 2.
The number of vowels is 1.

!
12. The Lucky numbers for this month are 8, 12, 20, 55. Write a program to get 3 numbers
from user if at least 2 of the numbers match with the lucky numbers then print, "You
won!" otherwise say "You lose"

!
SIIT

Input 1: 20
Input 2: 22
Input 3: 18
You lose!

Input 1: 15
Input 2: 8
Input 3: 55
You won!

5
! 7

ITS100 Programming is fun

13. Write a program that gets a size of octagons side. If the size of side is less than 100
draw the orange octagon otherwise draw the black colour octagon. (Octagon can be
created of lines and turns - at the appropriate angle)
Enter the size of octagon: 50

14. Write a program that takes take a colour from user and draw a heart with that colour.
What is the colour of you heart?: red

What is the colour of you heart?: blue

15. Ask the user What day is today? Give her an angry face if she gives a wrong answer.

SIIT

5
! 8

ITS100 Programming is fun

Chapter 6

Repetition Structure

Repetition
The next useful concept for programming is a repetition structure.
When you write a bigger program or solve a more complex problem, it is very usual that you
need to repeatedly execute a block of code several times in the program. In general,
statements are executed sequentially: The first statement in is executed first, followed by the
second, and so on. Programming languages, such as Python, provide various control
structures that allow for more complicated execution paths. A loop statement allows us to
execute a statement or group of statements multiple times. In Python, two commands, for
and while, are very common and very useful in the repetition structure. For loops are
normally used when you have a block of code that you want to repeat n number of times
(normally, n is known). As an alternative, there is the while loop. while is normally used to
repeat a block of code until a certain condition is met, or if you want the block of code to
repeat forever, for example.

Lets begin with the for loop.

SIIT

5
! 9

ITS100 Programming is fun

For loop
A for loop is a Python statement which repeats a block of code a specified number of times.
It has the ability to iterate over the items of any sequence such as strings, arrays, lists,
tuples, dict and so on. (We will only talk about a list in this chapter, the rest will be discussed
in the following chapters.) The syntax of a for loop look is as follows:



for x in sequence:
statement
statement

A for follows by an iterating variable and a word in, then a sequence. So the pattern is
simply for .. in .. If a sequence contains an expression list, it is evaluated first. Then, the first
item in the sequence is assigned to the iterating variable x. Next, the statements block is
executed. Next item in the list will be assigned to x, and the statement block is executed
again and it keeps on doing this until the entire sequence is exhausted. The following
diagram shows the flow of the command.

!
OK, lets learn from two very simple examples here.

SIIT

for x in (1,2,3):
print("Superman")

for x in (1,1,1):
print("Superman")

Superman
Superman
Superman

Superman
Superman
Superman

6
! 0

ITS100 Programming is fun

In the left example, we let the variable x iterates over a list of (1,2,3). So in the first round of
the for command, x is assigned with the 1st element of the list, which is 1. It then prints a
Superman, which is the only command to be repeated. After the first round is finished, the
second number in the list is assigned to the variable x and this time x is 2. And again it prints
Superman. It keeps on doing this until the last item in the list is assigned and finished. The
example on the right will be just the same, it repeated 3 times, printing 3 Supermans. The
have the same results because there are 3 items in the list and variable x is not involved in
any calculation or printing. If x is a part of the print out, the results will look like this.



for x in (1,2,3):
print(x, Superman")

for x in (1,1,1):
print(x, Superman")

1 Superman
2 Superman
3 Superman

1 Superman
1 Superman
1 Superman



And you can notice that the value of x depends on the items in the list. Of course, we can
use that variable x (or other variable name) in any calculation we may want. Lets print a
multiplication table with 2 lines of code.
for n in (0,1,2,3,4,5,6):
print(n,"* 2 =",n*2)

0
1
2
3
4
5
6

*
*
*
*
*
*
*

2
2
2
2
2
2
2

=
=
=
=
=
=
=

0
2
4
6
8
10
12

With this example, n is the iterating variable and a list containing number 0 to 6. In the first
round, the first element of the list, 0, is assigned to variable n. We then print value of n follow
by * 2 = and the value of n multiplied by 2. So we have 0 * 2 = 0 for the first line. The first
iteration is finished. The second iteration is started. The second number in the list, 1, is then
assigned to n this time. So it will display 1 * 2 = 2. It will keep doing this until the last
element of the list, 6, is assigned and printed 6 * 2 = 12.
Same idea for a block of code is also applied here. If a block of code needs to be repeated,
we need to put them with the same indentation. In the following example, Superman and
Supergirl are printed twice because there are 2 items (10 and 20) in the list. When the first
item, 10, is assigned to a variable counter during the first round, it prints 10 in front of

SIIT

6
! 1

ITS100 Programming is fun

Superman and it print counter+1, 11, in front of Supergirl. Batman is not part of the loop
(notice the indent) so it is printed only once.
for counter in (10,20):
print(counter,"Superman")
print(counter+1,"Supergirl")
print("Batman")



10 Superman
11 Supergirl
20 Superman
21 Supergirl
Batman

The list can be not only the numbers, but also something else. The following example show
that we can put names in a list and then used it in for loop. Each member of the list will be
assigned to the variable. The command will just fetch each member and give the value to
intreating variable s and then start to process the statement (or statements) below. When all
the statements under the for command are all processed, thats the end of each iteration.
The new iteration starts by fetching the next value in the ranges list and give it to s, and
process the statement again with the new value s. And the program keeps doing this until all
the members in the range has been exhausted.
for s in ("Superman", "Supergirl", "Supermom"):
print(s,"is part of the Super family")
print("Batman is not")



Superman is part of the Super family


Supergirl is part of the Super family
Supermom is part of the Super family
Batman is not

Its convenient to list all the numbers in a sequence and provide it to the for command.
However, some times, we can not know all that numbers in advance. Or maybe the list is too
long, like 1 to 10000, so its cumbersome to list them all in this manner. There is another
command that helps with this problem.

Range
If you do need to iterate over a sequence of numbers, the built-in function range (start,
stop, step) comes in handy. It generates lists containing arithmetic progressions. Three
parameters, start, stop and step, are needed. It generates a list of numbers starting with
SIIT

6
! 2

ITS100 Programming is fun

start and ends just before stop value with increment step. The given end point is never part
of the generated list.
The first example, range(0,10,1) is to generate a list of numbers, starting from 0 and stop just
before 10 and increase by 1. The second example has the same start point and stop point
but the increment is 3 so the last number is 9. We can set the incremental step with a
negative number as shown in the last example, where starting point is -10 and end point tis
-100.
>>> range(0,11,1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 11, 3)
[0, 3, 6, 9]



>>> range(-10, -100, -30)


[-10, -40, -70]

If the conditions given to the range are not appropriate and the list couldnt be generated
then it will return an empty lists as shown in the following examples.
>>> range(0,-5,1)
[]
>>> range(-20, -11, -3)
[]



>>> range(-10, 10, -2)


[]

Range (omitting Step)


You can omit a few parameters for the range command. If step is omitted, it will be 1 by
default. So range (start, stop) means range (start, stop, 1)
range(start, stop) means range (start, stop, 1)

These 3 following examples show that when there are only 2 parameters provided to the
range command, that 2 parameters are considered to be start and stop and the value of
step will be set to 1 by default.

SIIT

6
! 3

ITS100 Programming is fun

>>> range(5, 10)


[5, 6, 7, 8, 9]
>>> range(10, 5)
[]
>>> range(-10, -5)
[-10, -9, -8, -7, -6]



Range (omitting Start and Step)


A start can also be omitted. When you provide just only 1 parameter to the range
command, it will be considered as Stop and set Start to 0 by default and again Step will be
set to 1 by default.
range(stop) means range (0, stop, 1)

the range will start from 0. So range (stop) means range (0, stop, 1)
>>> range(5)
>>> range(5)
[0, 1, 2, 3, 4]
>>> range(-10)
[]
>>> range(8)
[0, 1, 2, 3, 4, 5, 6, 7]

Note that range command doesnt accept floating point and string parameters.
>>> range(0.1, 0.5, 0.1)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
list(range(0.1, 0.5, 0.1))
TypeError: 'float' object cannot be interpreted as an integer



SIIT

>>> list(range("a","c",1))
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
list(range("a","c",1))
TypeError: 'str' object cannot be interpreted as an integer

6
! 4

ITS100 Programming is fun

For in Range
Now its more convenient that we combine the two functions, for and range. We can
generate a list with the range command and give each value to the iterating variable.



for x in range(a,b,c) :
statement
statement

Have a look at the following example. With only 2 lines of code, we can generate some
useful results. In this example, range(10) is translated into [0,1,2,3,4,5,6,7,8,9] before the for
command fetches each element from that list.
for x in range(10):
print(x,"squared equals,x*x)



0
1
2
3
4
5
6
7
8
9

squared
squared
squared
squared
squared
squared
squared
squared
squared
squared

equals
equals
equals
equals
equals
equals
equals
equals
equals
equals

0
1
4
9
16
25
36
49
64
81

If we want to calculate just only the square of even numbers, we can easily modified the
range command so that it generates only the even number. The rest of the program is
unchanged.
for x in range(0,10,2):
print(x,"squared equals,x*x)



SIIT

0
2
4
6
8

squared
squared
squared
squared
squared

equals
equals
equals
equals
equals

0
4
16
36
64

6
! 5

ITS100 Programming is fun

Nested-For
For complex calculation, we may need more than 1 iterating variable to solve it. The for
command can reside within another for. Thats is another useful concept and that always
cause confusion for beginners.
for x in range(2):
print(Superman)
for y in range(2):
print(Batman)

Superman
Batman
Batman
Superman
Batman
Batman

for every iteration of x, loop y will repeat 2 times too.


Consider this example:
for x in range(4):
for y in range(3):
print(x, y)



0
0
0
1
1
1
2
2
2
3
3
3

0
1
2
0
1
2
0
1
2
0
1
2

We have 2 loops here, one inside another. Lets call it loop x and loop y. Loop x will repeat
4 times and the value of x will be changing from 0, 1, 2 and 3. In each iteration of loop x, we
have another loop, loop y, inside it. Loop y repeats 3 times changing values from 0, 1 and
2. So for each iteration of loop x, the command in loop y will run 3 times. Thus, the result
12 lines, not 7 lines.

SIIT

6
! 6

ITS100 Programming is fun

for x in range(1,4):
print(Superman)
for y in range(x):
print(Batman)

Superman
Batman
Superman
Batman
Batman
Superman
Batman
Batman
Batman

The following example shows a table generated from a nested loop, one loop inside another.
For the loop y, we print x*y followed by a tab indicated by \t. Once loop y is done, we just
call a normal print() which automatically display a new line.
for x in range(1,6):
for y in range(10,60,10):
print(x*y,end="\t")
print()
10
20
30
40
50

20
40
60
80
100

30
60
90
120
150

40
80
120
160
200

50
100
150
200
250

While Loop
A while loop statement in Python programming language repeatedly executes target
statement as long as a given condition is true. The syntax of a while loop in Python
programming language is:
while condition:
statement

Here statement may be a single statement or a block of statements (Remember, in Python,


all the statements indented by the same number of character spaces are considered to be
part of a single block of code. Python uses indentation as its method of grouping
SIIT

6
! 7

ITS100 Programming is fun

statements). The condition may be any logical expression or logical value (non zero value is
considered to be true). The loop keep on iterating while the condition is true. When the
condition becomes false, program will skip the statement and go to the line immediately
following the loop. This means that if the condition is always true, the loop will run infinitely.
Diagram below show the flowchart of the while loop.

The following example shows simple structure of the while loop. The condition (5>4) is
always true, so the word Superman will be printed infinitely.
while 5>4:
print(superman)

In the next example, x is assigned to 5 at the beginning, so a condition x>0 is true and the
superman will be printed, then x is reduced by 1 for each iteration. Next round x is 4 and it
will still be true, Superman will be printed. It keeps going like this until x is 0, thats where the
condition is false. So Superman will be printed 5 times from

SIIT

6
! 8

ITS100 Programming is fun

x = 5
while x>0:
print(Superman)
x = x-1

Superman
Superman
Superman
Superman
Superman

Extra material: Random


We have seen 2 important modules so far, and they were Math module and Turtle module.
Random module is another useful one and is going to be introduced in this chapter. Same
as other modules, we can get all the functionalities in the module into our program by
importing it with import command.
import random
There are many useful commands in this module but one of the very useful that I would like
to introduce here is a function .randint(a,b) The function will return a random integer number
that are in between a and b, inclusively.
By calling x = random.randint(1, 100), x will be a random number between 1 - 100. Try to
run this piece of code several times and you will see that each time you get different
numbers.
import random as r
while x>10:
x = r.randint(1,100)
print (x)


Random number is very useful when you want your program to come up with unpredictable
results. The result that even the programmer doesnt know the outcome of the program. It
could be used in games or puzzles.

SIIT

6
! 9

ITS100 Programming is fun

Example of a guessing game


#guessing game
import random as r
answer = r.randint(1,100)
x=0
while x!=answer:
x = int(input("Guess: "))
if x>answer:
print("too big")
elif x<answer:
print("too small")
print("Congratulations! You win!")



Extra Material - if .. in range


Not only for command that can be used in combination with range, the if command has
that ability too. This following example shows that we can check whether the value of a
variable is a member of a given list or not.

x = input("Give me a character: ")


if x in ('a', 'e', 'i', 'o', 'u'):
print(x,"is a vowel")

Conclusions
We have discussed about the simple repetition structure using for loop and in combination
with range together to produce the important tool for Python programming.

SIIT

7
! 0

ITS100 Programming is fun

Exercises
1. Fill the corresponding pair of range commands and results.
range

all elements in range

range (0, 10, 1)


range (0, 10)
range (10)
range (1, 40, 5)
range (-2, 20,4)
range (12, 1, -2)
range (-10, 10, 3)
range (10, 3)
range (0, 10, -2)

2. Shell: Write a program that asks for a number of circles the user wants to draw, then
draw the circles similar to the one displayed below.

!
3. Square: (a) Write a program to calculate square of n numbers where n is the input from
user and (b) just display only the square of even numbers
4. Bank: A bank needs a program that help customers to calculate their accounts balance.
The program should ask customer for the amount the customer wants to deposit and
how many years they want to calculate. The program assumes that the interest rate is
5% per year and display the projected balance of each year for customer.

SIIT

7
! 1

ITS100 Programming is fun

5. Candy: Write a program to draw a candy (as displayed here). The candy picture here is
made of 100 circles. The size of the circle is reduced from 100 to 1. The colour of the
circle will be alternatively changed from red, pink, yellow, green and blue. (Hint: its
combination of if and for)

!
6. Get n from user and draw a flower with n petals.
Draw each petal with
turtle.circle(100,90)
turtle.left(90)
turtle.circle(100,90)
Also change the color of each petal too (hint: if within for and %(mod) operator
(n is 12 for this example)

!
7. ATM: Write a program to display an ATM menu that user can withdraw or deposit to the
account. Repeat the process until user choose exit from the menu.

SIIT

7
! 2

ITS100 Programming is fun

8. Write a program to generate bubbles on a canvas size of 1000x800 pixels at random


location, random sizes and random colour. Repeat the program until one bubble falls
below -350 (on the X axis)

Later change these bubbles into flowers with random sizes and colors too. (This
demonstrate the loop within the loop concept.)

SIIT

7
! 3

ITS100 Programming is fun

Python for Absolute Beginners


Introduction to Programming
(After Midterm)

Assoc. Prof. Dr. Bunyarit Uyyanonvara


Sirindhorn International Institute of Technology (SIIT)
Thammasat University

ITS100 Programming is fun

Chapter 8

User-defined function
Introduction
There are situations where we want to reuse some parts of our code again and again in our
program. Its not very convenient to copy and past the same code to many parts of the
program. The part of the code that needs to be reused should be defined as a function. A
function is a block of organised, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing. Python already gives you many built-in functions like print( ) or input( ), etc. but you
can also create your own functions. These functions are called user-defined functions.
Defining a function is easy because its the same way as we write a normal program but this
time we just give a name to that part of the program.

SIIT

7
! 5

ITS100 Programming is fun

Defining a function without parameter


The keyword def introduces a function definition. It must be followed by the function name
and an empty parenthesis. The statements that form the body of the function start at the
next line, indented by a tab stop. You can define functions to provide the required
functionality. Here are simple rules to define a function in Python.
Function blocks begin with the keyword def followed by the function name and
parentheses ( ).
The code block within every function starts with a colon (:) and is indented.

def functionname():
statements
statements

The following examples show how we define a function. In the first example, we define a
function called superfamily. This function requires no input as indicated by an empty
parenthesis after the function name. Within this function, there are 2 statements to print
Superman and Supermom.
def superfamily( ):
print(Superman)
print(Supermom)

!
To call the function we simply call it by the name, superfamily( ). Thats the same way we
called other functions already provided in Python. So when this function is called, there will
be 2 lines of the output.
We can put everything that we normally did when we normally write a program in a function.
The following example shows a more complex function with for and if.

SIIT

def batfamily( ):
for i in range(20):
print(Batman)
if i>10:
print(Batmom)
print(Batgirl)

7
! 6

ITS100 Programming is fun

Defining a function with parameters


Sometimes, not only we want to call a function, but also we want to pass some information
to the function as initial value. In order to do that we list parameters that we want in the
parenthesis next to the functions name. This is called the list of formal parameters.
There are 2 types of parameters. A required parameter and an optional parameter (or default
parameter)

Required parameters:
Required parameters are the parameters that are required, of course! Caller need to pass
values to the function in correct positional order. The number of parameters in the function
call must match exactly with the number of parameters listed in the function definition.
In the following example, a function called superwhat is defined with 1 required parameter.
To call this function, you need to pass a value in the parenthesis. You have to pass exactly 1
parameter, otherwise it would give a syntax error:
def superwhat( str ):
print(Super+str)
#this call will give error
super( )
#this call also will give error
super(man, girl)

#this one will be OK


super(man)

The next example shows that a function nsuperman is defined and this function needs 1
parameter, n. When a user calls this function, he has to provide a value to this parameter and
that value will be used in the function. The value will be passed to the corresponding
parameter or parameters in the list. In this case, if we look at the code, n will be used in a for
command to repeat n times. Superman will be printed n times.
def nsuperman(n):
for i in range(n):
print(Superman)

SIIT

7
! 7

ITS100 Programming is fun

In the next example, a function called nameXn is defined but this time it requires 2
parameters, name and n. s To call this function, again you need to pass 2 values in the
parenthesis and in the right order. The first value will be given to the first parameter and the
second value will be given to the second parameter and so on. In this case, if you call this
function with nameXn(Ron, 5) then Ron will be given to variable name in the function
and number 5 will be given to a variable n in the function.
def nameXn(name, n):
for i in range(n):
print(name)
#this call will give error
nameXn(Harry)
#this call also will give error. Number of parameters is correct but 2
will be given to name and Potter will be given to n and that causes
the error.
super(2, Potter)

#this one will be OK


super(Ron,5)

Default parameters:
A default parameter is an parameter that assumes a default value if a value is not provided in
the function call for that parameter. However, if the caller choose to pass a value to this
parameter, the parameter will take the value from the caller first. So, its a kind of optional
parameter. You can choose whether to give it a value or not to give the value and let it takes
the default value.
In order to assign the default value, you give an initial or default value to that parameter at
the function definition. The following example gives an idea of how to define a default
parameter. The function would print a default age if the parameter is passed from a caller.
Example
def student(name, age=18 ):
print(name, is , age)
#this call is OK. Result will be Doraemon is 22.
student(Doraemon, 22)
#this call is also OK. Result will be Nobita is 18.
student(Nobita)

SIIT

7
! 8

ITS100 Programming is fun

When student(Doraemon, 22) is called. Doraemon is passed to variable name and 22


is passed to variable age. So the function displays Doraemon is 22. But when
student(Nobita) is called, this time only Nobita is passed to variable name and the
variable age takes value from the default value which is 18. The function hence displays
Nobita is 18.
The next function is defined as nameXn with 1 required parameter and 2 default
parameters. If all parameters are given then everything will be fine, but if only 2 parameter is
given such as, nameXn(Potter, 10), the second value, number 10, will be given to the
second variable and the third parameter takes the default value.
def nameXn(name, n=5, intro=Welcome to SIIT):
print(intro)
for i in range(n):
print(name)
#this call is OK
nameXn(Harry, 5, Welcome to Hogswarts)
#this call is also OK
nameXn(Potter, 10)
#this one is also absolutely OK
nameXn(Ron)

!
The function will still take parameters from the caller to the function in the same order. If you
give the parameters in different order, it will generate unexpected results. Be careful, even
though you can define any parameter in your parameter list to be default ones, but if you
separate the default parameters like this
def alienvsmonster(alien= ET, n, monster=Godzilla, m):

Then when you call it with 2 parameters such as alienvsmonster(2, 3) , number 2 will be
assigned to variable alien and number 3 will be assigned to variable n. And the program will
not run because it thinks the required parameter m is missing. If only 2 parameters are given,
it will give to the first 2 parameters, it will not assume that you are assigning these 2 values to
the required parameters. So be careful about that.

SIIT

7
! 9

ITS100 Programming is fun

Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in
the function and structures the blocks of code. Once the basic structure of a function is
finalised, you can execute it by calling it from other part of the program, from another
function or directly from the Python prompt.
The function that is not called will not be executed. As in this example, we defined a
superfamily( ) function, but we never call it. So when we run this program, nothing is
printed!
#this is the function definition
def superfamily( ):
print(Superman)
print(Supermom)

In contrast, if we call the function 2 times as in the following example. The function will be
executed 2 times too and it will give Superman and Supermom twice as the output.
#this is the function definition
def superfamily( ):
print(Superman)
print(Supermom)

#this is the function calls


superfamily( )
superfamily( )

!
When the above code is executed, it produces the following result:

Superman
Supermom
Superman
Supermom
If the function requires parameter or parameters, then the caller will have to pass the
parameters to the function in the right order and the same number as listed. The first value
will be given to the first variable, the second value will be given to the second variable and so
on.

SIIT

8
! 0

ITS100 Programming is fun

We can pass the value to the function by providing the value that matches the number of
parameters required by the function. By default, parameters have a positional behaviour and
you need to inform them in the same order that they were defined.

When we finish the calculation within a function and want to return some result back from
the function to the caller or just simply want to get out of a function, we can use statement
return.

Return from a function without sending back value


Whenever return is called, it will immediately exits the function. In the following example, we
use statement return to indicate the end of the function. However, in this case, it the same as
not having the statement return.
def superfamily( ):
print(Superman)
print(Supermom)
return

!
The statement return doesnt have to be the last line in the function, you can put it
anywhere. As demonstrated in the next example. Whenever the statement return is
reached, it will exit the function.

def superman(x):
if x == 10:
return
else:
print("superman")

SIIT

8
! 1

ITS100 Programming is fun

Return from a function and send back some values


We can send some values into a function, we can also get values out of the function too. If
we want to pass back some value to the caller, we just simply line them up after the
statement return.
The following example shows a function adder(a, b) that takes 2 parameters, add them and
return the result back to the caller with statement return c.where c is a variable that keeps
the result.
def adder(a, b):
c = a + b
return c

!
Calling this function needs an extra care. Because the function returns the value back, so if
the caller want to receive the return, the caller has to provide a receiving variable. Calling the
function with returning result without receiving variable will not generate error.
def adder(a, b):
c = a + b
return c
#this call is OK, and x will be 42 after this function call
x = adder(20, 22)
y = x+2
print(y)
#this call is also OK, result from the function will be added with 2
before being displayed as 44
print(adder(20,22) + 2)

SIIT

8
! 2

ITS100 Programming is fun

Scope of variables:
All variables in a program may not be accessible at all locations in that program. This
depends on where you have first used that variable. Especially, when a variable is first used
(or declared) in a function, it will belong to that function only and cant be called or used
elsewhere. Thats called scope of a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python: Global variables and
Local variables

Global variables:
Global variables are variable that are created outside of any function. This kind of variables
can be used and accessed everywhere in the program body and can be accessed also by all
functions.The following example shows that variable a is declared outside of function
testGlobal, but the variable can also accessed by the function too.
The following function shows that a variable a is first created outside of any function, so this
variable can be used throughout the program.
a = 10
def testGlobal():
print(a,Spiderman)

Result
10 Superman
10 Spiderman
10 Superman

print(a,Superman)
testGlobal()
print(a,Superman)
!

Local variables:
Local variables are variables that are created within a function. Variables that are defined
inside a function body have a local scope which means that local variables can be accessed
only inside the function in which they are first created. When you call the function, the
variables declared inside that function are brought into scope and when the function is
finished that variables will disappear. So it cant be used anywhere else in the program.
This is good idea because it will prevent confusion between many functions. We may have
different variables that accidentally have the same name in many functions. Without the
scope of variable, it will be a mess of on function changing value of other functions variable.

SIIT

8
! 3

ITS100 Programming is fun

Imagine that when our program is bigger, there might be more people writing functions for
the same program not aware of what other people might be using for the variable name.
Scope of variable just solve that problem.
There are 2 possible ways to create (or declare) a new variable within a function.
A. assign a value to a new variable name for the first time in the function
In this example, a variable b is created by giving value 9 inside a function testLocal( ), thus
the variable is a local variable and has scope within the function only. When the
print(b,Supermans) is trying to access this variable, Python issues an error message
because the variable b is a local variable within the testLocal function only and can not be
accessed from somewhere else.
Result
9 Spiderman
Error message!

def testLocal():
b=9
print(b,Spiderman)

testLocal()
print(b,Superman)
!

B. Declare it in the parameters list


In this example, there are 2 variables in a parameter list next to the name of the function.
Same as case A., these 2 variables have local scope to the function and cannot be
accessed by the outside.
Example

Result
3 5 Spiderman
Error message!

def testLocal2(x, y=1):


print(x, y,Spiderman)
testLocal(3,5)
print(x,y,Superman)
!

So in conclusion, names defined inside a def can only be seen by the code within that def.
You cannot even refer to such names from outside the function.

SIIT

8
! 4

ITS100 Programming is fun

Scope of variables: Naming


Scope of variable is very important for programming because it is preventing us from a
variable-naming disaster. Imagine if 2 programmers are writing 2 different functions and these
2 functions are used in the same program. If we dont have the scope of variable as we
discussed earlier, 2 variables from the different functions might accidentally have the same
name (which is quite common if we use short variable-naming like in the example), then the
function from these programmers will not work as expected because the value of variables is
interfered by the other.
Names defined inside a def do not clash with variables outside the def, even if the same
names are used elsewhere. A name X assigned outside a given def (i.e., in a different def or
at the top level of a module file) is a completely different variable from a name X assigned
inside that def.

Notice the difference between a local and a global variable in the following example. In this
example, there are 2 different variables, created at different locations in the program but they
happen to have the same name, variable c. The first c is declared and created outside any
function, so it is a global variable when the second c is created within a function so this one
is a local variable. (Notice the difference from the previous exam, where variable b was just
used in the function, not created) Even though they have the same name here, but they are
created 2 times in different places so they are 2 different variables which we can see clearly
from the output result. (They are just like 2 men with the same name, Peter. One Peter might
be in UK, another Peter might be in USA. They have the same name, but definitely they are 2
different persons.)
Example
def testLocal():
c=9
print(c,Spiderman)

Result
5 Peterpan
9 Spiderman
5 Superman

c = 5
print(c,Peterpan)
testLocal()
print(c,Superman)

The first print(c,Peterpan) displays the value of global c (which is 5) along with a word
Peterpan. Then a function testLocal() is called and thats where another c is created. The

SIIT

8
! 5

ITS100 Programming is fun

new c is local and has value 9 and has nothing to do with the first c (similar to the way that
USAs Peter is born and has nothing to do with UKs Peter). When print(c,Spiderman) is
executed, 9 is then displayed together with a word Spiderman. After finishing with the
function call, program will then do print(c,Superman), and the value of c here is 5
because its the global c

Its clear that this is very useful and allows us to name variable freely if we wrap it in our
function. However, sometime we want to use the global variable within the function and we
want to also change its values. But if we just assign a new value to a variable in a function, it
will be a local variable. Global keyword can help with this.

Global assignment:
A keyword Global is needed if we want to specify some variables inside a function to have
global scope. The following example show that we can change the value of global variable
within a function if we specify it to be Global.
Example
def testScope():
global d
d = 9
print(d,Spiderman)

Result
5 Peterpan
9 Spiderman
9 Superman

d = 5
print(d,Peterpan)
testScope()
print(d,Superman)

Similar to previous example, the first d is global, and the result of print(d,Peterpan) is 5
Peterpan. Then the function testScope( ) is called. At this point, we specifically set the
variable d to be global which means it is the same d as the first one. The value of d is
changed to 9 and it displays 9 Spiderman. After the function is finished, the value of global d
has already been changed to 9. Thats why the last line of the output is 9 Superman.

SIIT

8
! 6

ITS100 Programming is fun

Example
def test1():
x = 10
print(x)

def test2():
global x
x = 5
print(x)

Result
2
10
2
5
5
5
5
15
25
25

def test3():
print(x)
def test4():
global x
x = x + 10
print(x)

SIIT

x=2
print(x)
test1()
print(x)
test2()
print(x)
test3()
print(x)
test4()
test4()
print(x)

8
! 7

ITS100 Programming is fun

def Arsenal():
x = 5
print(x)
def Chelsea():
y = x + 2
print(y+2)
def ManUTD():
global x
x = x + 4
print(x)
def Liverpool():
x = x + 2
print(x)
x=10
Arsenal()
Chelsea()
ManUTD()
print(x)

Conclusion
A function is a block of organised, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing. Four important steps for functions are:
Defining a function
def follows by name of function and a parenthesis, then a colon:
Calling a function
The function is called by its name
Passing value(s) to a function
List of arguments (or parameters) in the parenthesis next to functions name.
Required parameters
The all the values have to be passed to the function in the right order

Default parameters
Give an initial value to a variable in the arguments list to make it a default
Returning value(s) from a function
keyword return just returns the values back to the caller

SIIT

8
! 8

ITS100 Programming is fun

Review Questions:

Question 1 (level: C)
def Spiderman():
x = 10

this x is _____________ (global or local) and has value ________________

def Superman():
x = 20

this x is _____________ (global or local) and has value ________________

x=5
print(x)
Spiderman()
print(x)
Superman()
print(x)

this x is _____________ (global or local) and has value ________________


result ________________
this x is _____________ (global or local) and has value ________________
this x is _____________ (global or local) and has value ________________

Question 2 (level: C)
def Superman():
global x
x = 20

this x is _____________ (global or local)


and has value ________________

x=5
print(x)
Superman()
print(x)

this x is ____Global______ (global or local) and has value ___5_____________


this x is __G___________ (global or local) and has value ____5____________
this x is _ G____________ (global or local) and has value __20____________

Question 3 (level: B)
def First():
z=x+y
print z

x,y and z are ____L=10__, ____G=5______, __G=5_______ (global or local)

def Second():
x=5
y=3
z = x+y
print z

this x is __L___________ (global or local)


this y is __L___________ (global or local)
this x,y and z are ____L______, ____L______, _____L____ (global or local)

x=y=z=5
print(x,y, z)
First()
print(x,y, z)
Second()
print(x,y, z)

x,y and z are _____G_____, ____G______, ___G______ (global or local)


result: ____5______, ____5______, ____5_____
result: ___10_______
result: ____5______, _____5_____, ____5_____
result: ____8______
result: _____5_____, _____5_____, ____5_____

SIIT

8
! 9

ITS100 Programming is fun

Question 4 (level: B)
def test(c):
a=b+c
return a

this c is ____L_________ (global or local)


a,b and c are ___L=6_____, ____G=5______, ____L=1_____ (global or local)

b=5
x = test(1)

this b is ____G=5_________ (global or local)


x = ____6_________

Question 5 (level: A)

def test(a,b,c):
x = c+30
y = b+20
z = a+10
return x,y,z

x and c are ___L_______, _____L______ (global or local)


y and b are ___L_______, _____L______ (global or local)
z and a are ___L_______, _____L______ (global or local)
values of x,y,z ____________, ____________, ____________

a=1
b=2
c=3
print(a,b,c)
x,y,z = test(c,b,a)
print(x,y,z)
print(a,b,c)

this a is ___G__________ (global or local)


this b is ____G_________ (global or local)
this c is _____G________ (global or local)
values of a, b, c ___1______, ___2_________, __3_______

values of x, y, z ____31________, ____22______, ___13______


values of a, b, c _____1_______, ______2______, _____3_______

Question 6nw (level: A)

def Rooney():
global a
c = 5
a=b+c

def Messi(a, b, c):


c = a+b
b = a+c
a = b+c
return a,b,c

a=b=c=2
print(a,b,c)
Rooney()
print(a,b,c)
a,b,c = Messi(a,b,c)
print(a,b,c)
Rooney()
print(a,b,c)
a,b,c = Messi(a,b,c)
print(a,b,c)

a,b and c are __________, __________, _________ (global or local)

a,b and c are __________, __________, _________ (global or local)

values of a,b and c are ___2_______, ___2_______, ___2____


values of a,b and c are ___7_______, ___2_______, ___2______
values of a,b and c are ___25_______, ___16_______, _9_____
values of a,b and c are ____21______, ____16______, ___9______
values of a,b and c are __________, __________, _________

SIIT

9
! 0

ITS100 Programming is fun

Problem Solving:
A.Solve 2 exercise from the lab manual
B. Write a program that draws random-shape stars. This program will have 2 functions. The first
function is called LineAndTurn(angle) which required 1 parameter for a turning angle. Within the
first function, it just goes forward 100 pixels and then turn left with given angle. The second
function is Star( ) and this function will just call the first function for 50 times with random angles.
Then write a main program that call Star() for 10 times.

SIIT

9
! 1

ITS100 Programming is fun

Chapter 9

List & String

ITS100 Programming is fun

List Manipulation
Lets try to think how to write a program to solve this problem.
Write a program to get numbers from a user. User can keep inputing the numbers until he/
she inputs -1. Your program then rearranges all of those numbers and display them in an
increasing order
With this kind of problems, we cannot use normal variables to keep the those values from
users. First, because we dont know in advance how many numbers the user will input. And
second, we dont have an effective way to compare all of those different variables so that we
can rearrange or sort them. In fact, these similar situations are very common in programming
and thats why we have to have a special kind of variable to solve this problem. In most
programming languages, we call this kind of variable an array. We have similar structure in
Python and its called a list.
The list is a most versatile datatype available in Python which can be written as a list of
comma-separated values (items) between square brackets. The name of the list can be used
as if it is a single variable that can contain many items in it. So with that idea, we can add as
many items to one single variable.
Creating a list is as simple as putting different comma-separated values between square
brackets. For example:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

Please note that the good thing about the Pythons list is that items in a list need not all have
the same type and the main point that Pythons list is different from the other languages
array is that we dont have to specify the number of element in advance. So the list is
dynamics and very memory efficient.
There are certain things you can do with the list. These operations include indexing,
slicing, adding, multiplying, and checking for membership. In addition, Python has
many built-in functions to manipulate or to find specific information of the list such as finding
the length of a sequence or finding its largest and smallest elements. We will discuss those
actions and functions in this chapter.

SIIT

9
! 3

ITS100 Programming is fun

Accessing Values in Lists (Indexing)


OK, we can store many items in a single variable name. How can we access a specific
element in that list?
Easy. Each element of a list has an index which is a number indicating its position. The first
item in the list has an index 0, the second index is 1, the next one has index 2 and so forth.
When I said the first item, I actually meant the first item from the left because if you want to
access the first item from the right, the first index (from the right most) will be starting from -1
instead of 0. To access a value in a list, we use the name of the list following by the index of
the item of interest in square brackets.
Following is a simple examples.
A = ["Superman", "Batman", "Spiderman", Snoopy, Peterpan"]
print(A[0])
print(A[2])

Superman
Spiderman
A = ["Superman", "Batman", "Spiderman", Snoopy, Peterpan"]
print(A[-1])
print(A[-2])

Peterpan
Snoopy

Selecting many items from a list (or Slicing)


We can actually select more than one item at a time by provide 2 indices (separated by a
colon, : ) in the square brackets. If our list is called A, then A[start : stop] is a slice of a list A
starting from start index and finish just before stop index (the item at the stop index is not
included in the slice).
A = [10, 20, Spiderman", Bangkok, Tokyo, London, Paris]
print(A[1:4])

SIIT

[20,Spiderman,Bangkok]

9
! 4

ITS100 Programming is fun

This previous example shows that the list A is sliced from the index 1 to index 3 (stop just
before a stop point, 4) number 2 to just before the element number 4. The following example
shows similar thing but start from index 0 and stop just before index 1 (which means slice
from index 0 to index 0. Thats why is has one element in the result.)
B = [10, 20, Spiderman", Bangkok, Tokyo, London, Paris]
print(B[0:1])
[10]

We can also use the negative index in the slicing process too, as in the following example.
C = [10, 20, Spiderman", Bangkok, Tokyo, London, Paris]
print(C[-3:-1])
[Tokyo,London]

If you want to slice from the first element of the list, you can either specify the starting point
for the slice to be 0 or just leave it blank. Similarly you can leave the stop index blank in case
you want your slice to the last element of the list. This is very convenient because you dont
have to worry about the index of the last element, just leave it blank and you can get to the
last one.
Look at the following example:
C = [10, 20, Spiderman", Bangkok, Tokyo, London, Paris]
print(C[:3])
[10, 20, Spiderman]

C = [10, 20, Spiderman", Bangkok, Tokyo, London, Paris]


print(C[2:])
[Spiderman", Bangkok, Tokyo, London, Paris]

And of course, as you may have guessed, if you leave both start index and stop index blank
like this A[:], it means all the elements in list A will be included in the sliced.

SIIT

9
! 5

ITS100 Programming is fun

String manipulation
A string works in similar way to a list. In many situations we can consider a string as a list of
characters. Because lists are sequences, indexing and slicing work the same way for lists as
they do for strings. These two examples are equivalent and give the same results. The one
on the left, D is a string variable, to access the 4th element of the string we use D[3]. The
one on the right, variable E is a list, to access the 4th element of the list we use E[3].
D = Spider"
print(D[3])

E = [S,p,i,d,e,r]
print(E[3])

Similarly, the slicing also works for the string.


D = Spiderman"
print(D[1:5])

E = Superman"
print(D[:5])

pide

F = Doraemon"
print(D[5:])

Super

mon

Updating Lists:
You can update single or multiple elements of lists by giving the slice on the left-hand side of
the assignment operator with some value. Following is a simple example:
E = [10,20,30]
E[1] = 500
print(E)
[10,500,30]

Be careful, you can not change the items that dont exist. The following example will
produce an error, because you are accessing element which has index 3, and such element
doesnt exist.
E = [10,20,30]
E[3] = 200

And be careful, String object does not support item assignment as the list. Given A =
Superman and if you try A[3] = X, that will generate an error.

SIIT

9
! 6

ITS100 Programming is fun

Delete List Elements:


To remove a list element, you can use either the del statement if you know exactly which
element you are deleting or the remove( ) method to remove the item that has the matching
value. The method clear( ) will remove everything from the list. Following is a simple
example:
A = [10,20,30]
del A[1]
print(A)

A = [10,20,30]
A.remove(10)
print(A)

[10,30]

A = [10,20,30]
A.clear()
print(A)

[20,30]

[]

Note that these functions can not be applied to a string so you can not del or remove
character from a string.

Append New List Elements:


To add a list element, you can use the append( ) method. The new element will be added at
the end of the list. Following is a simple example:
A = [10,20,30]
A.append(500)
print(A)

A = [10,20,30]
A.append(Superman)
print(A)

[10,20,30,500]

[10,20,30,Superman]

The following example shows how to populate a list with for loop.
A = [10,20]
for i in range(5):
A.append(i)
print(A)

SIIT

[10,20,0,1,2,3,4]

9
! 7

ITS100 Programming is fun

Basic List Operations:


Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on strings in the prior
topic.

C = "Doraemon"
D = MK Sukiyaki
E = C[:4] + D[7:]
print (E)
Dorayaki

List Of Lists:
List can be nested, meaning that we can have many lists inside a list in the same way that
we have many elements in a list. The following example is a demonstration of 2 dimensional
list. A and B are list themselves and we enclose them into a new list C. So each element in
list C is now a list, not just a single element.
A = [10,20,30]
B = [Superman,Spiderman]
C = [A,B]
print(C)
[[10,20,30],[Superman,Spiderman]]

We index the multi-dimensional list in the same way as we index a normal 1-D list. As in the
previous example, C[0] does mean the first element of C which, in fact, is a list A. And then
C[0][0] will mean the first item in that list, which is a number 10 in this case.

SIIT

9
! 8

ITS100 Programming is fun

We can access the other element in similar fashion. C[1][0] means Superman. C[0][1] is 20
for example.
This looks like a 2-Dimensional list and it needed 2 indices to access each element. As you
may have guessed, we use the 2-D list to keep 2-D information such as a table or anything
in tabular format. And of course, you can have as many dimensions as you like by nesting
lists inside another list. The following show a 3D list which requires 3 indices to access each
element in the list.
A = [10,20]
B = [Cat,Bat]
C = [A,B]
D = [C, C]
print(D)
[[[10,20],[Cat,Bat]],[[10,20],[Cat,Bat]]]

SIIT

9
! 9

ITS100 Programming is fun

List Function and Method:


There are many useful functions that can be used to manipulate a list or item in the list. The
followings are some examples of those functions:
1. sum(listname) finds summation of all items in the list.
2. len(listname) gives the total length (or total number of elements) of the list
3. max(listname) returns the item that has maximum value in the list
4. min(listname) returns the item that has minimum value in the list
A = [10,20]
B = [Cat,Bat]
print(sum(A))
print(len(A))
print(max(A))

30
2
20

With the above functions,we have to provide a lists name as a parameter. However, the
following functions (rather called method) are built right into the list. And they can be called
by lists name followed by a dot (.) and the methods name.

SIIT

1
! 00

ITS100 Programming is fun

A = [10, 20, 3, 7]
A.sort()
print(A)
[3,7,10,20]

To use LIST with FOR, IF and RANDOM:


With the FOR
There are 2 ways to run through all the elements in the list with FOR loop. The first one, as
demonstrated in the following example, uses list in the same way as we used range in the
FOR loop earlier. The pattern is FOR followed by a name of iterating variable, then in and
then the lists name.
A = [10, 20, 3, 7]
for x in A:
print(x)

10
20
3
7

The second way is that we run through the list with the lists index. We slowly change the
index and use the index to specify each element as in the following example.
A = [Cat, Rat, Bat, Mat]
for i in range(4):
print(A[i])

Cat
Rat
Bat
Mat

The following example is similar, but it will display only the items with even indices.
A = [Cat, Rat, Bat, Mat]
for i in range(len(A)):
if i%2 == 0:
print(A[i])

!
SIIT

Cat
Bat

1
! 01

ITS100 Programming is fun

len(A) was used to find the number of elements automatically. i%2==0 can be true only
when i is an even number.

With the IF
You can check the membership of a list easily with the in command. These 2 programs are
doing exactly the same thing with different mechanisms.
x = input(Animal: )
if x==Cat or x==Rat or x==Bat:
print(Correct answer!)
else:
print(Try again)

A = [Cat, Rat, Bat]


x = input(Animal: )
if x in A:
print(Correct answer!)
else:
print(Try again)

!
The one on the left was using or in an if condition as we normally did previously. The one on
the right, however, takes advantages of the lists existence by put everything in a list and later
check for the membership of the list. The code is cleaner and easier to maintain.

With the RANDOM


RANDOM module has a specific function to random an element out of a list. That function is
random.choice(listname).
import random as r
import turtle as t
colours = [red, green, blue, pink]

while True:
x = r.choice(colours)
t.dot(100,x)

random.choice requires a list as a parameter. In this example, we put the colour names that
we want in a list and use random.choice to get a random colour and then use that colour in
the dot command.

SIIT

1
! 02

ITS100 Programming is fun

Problem Solving:
A. Write a program to get names from user (repeat until user input x) then display the
names in alphabetical order.
B. Write a program to get numbers from user (repeat until user inputs -1) then calculate the
average of those numbers. Then, display only the numbers that are more than the
average.
C. Use Turtle to draw a star pattern with random colours from a list of colours.
D. The Gardener
Write a program that will ask user to input m, n for the size of the garden. There are 3
types of seeds that user can choose from: garlic, banana and apple. The program will
repeatedly ask user to input type of seeds and number of seeds they wan to plant in
the garden. If user input -1 for type of seed or number of seeds, the program will stop
the input process. User is not allowed to input the same type of plant more than one time.
The program then displays a rectangle of size m x n and randomly plants the selected the
seeds within this area. Use these representation
Garlic - Green dot, size 20
Banana - Yellow dot, size 20
Apple - Red dot, size 10

Example
Size of the garden (m n): 300 200
seed and number of seed: garlic 10
seed and number of seed: apple 10
seed and number of seed: onion 5
seed unknown. try again.
seed and number of seed: banana 8
seed and number of seed: -1 -1

SIIT

1
! 03

ITS100 Programming is fun

4. What is the index value of the first

Review Exercise

element from the left?

1. Refer to the the code below:


5. What does a Two-Dimensional List

a_list = [10, 20, 30, 40].

do?

What is the value of a_list[-1]?

a. It forms a tabular, two


dimensional arrangement.

2. What does a list mean in Python?

b. It creates two lists at once.

a. A random integer

c. It creates a list with only two

b. A program that you can use to

elements

execute another program and

d. no correct answer

anlyze its run-time behavior


c. A sequence of values

6. How do you access a list element?

d. A system function

a. variable = name[i]
b. variable = i.name;

3. How do you access a list element?

c. variable = name.get(i);

a. By the name of the list followed

d. no correct answer

by the index value in brackets.

7. Which of the following will NOT

b. By the name of the list followed

produce an error?

by a dot and then the index


value

a. a = [1,2,3]
a.append[4]

c. By the index value followed by a


dot and then the name of the

b. a = "123"

list

a[3] = 4

d. By the name follow by the

c. a = [1,2,3]

elements name

a.append(4)

e. no correct answer

d. a=[1,2,3]
a[3] = 4

SIIT

1
! 04

ITS100 Programming is fun

Chapter 10

Simple Animation
Introduction
More than 10 lectures that we had in this semester, we have learned most of the simple
programming concepts of Python. Those concepts include variables, lists, if..else, for, while
and turtle. This week we will put everything that you know so far together to create some
animation and even games.
But first, there are a few more concept you need to know before starting something fun this
week.

Events Driven Programming

In computer programming, event-driven programming (EDP) or event-based


programming is a programming paradigm in which the flow of the programs determined by
eventse.g., user actions (like mouse clicks, key presses) or messages from other programs

ITS100 Programming is fun

or threads. Event driven systems are typically used when there is some asynchronous
external activity that needs to be handled by a program. For example, a user who presses a
button on his mouse. An event driven system typically runs anEvent loop, that keeps waiting
for such activities, e.g. input from devices or internal alarms. When one of these occur, it
collects data about the event andfiresit, i.e. it dispatches the event to theevent
handlersoftware that will deal with it.

Events

In computing, an event is an action or occurrence detected by the program that may be


handled by the program. Typically events are handled synchronously with the program flow,
that is, the program has one or more dedicated places where events are handled, frequently
an event loop.
Typical sources of events include the user (who presses a key on the keyboard, in other
words, through a keystroke). Another source is a hardware device such as a timer. Any
program can trigger its own custom set of events as well, e.g. to communicate the
completion of a task. A computer program that changes its behavior in response to events is
said to be event-driven, often with the goal of being interactive.

Event Handlers

In computer programming, an event handler is a callback subroutine that handles inputs


received in a program (called a listener in Python). Each event is a piece of application-level
information from the underlying framework, typically the GUI toolkit. GUI events include key
presses, mouse movement, action selections, and timers expiring. On a lower level, events
can represent availability of new data for reading a file or network stream. Event handlers are
a central concept in event-driven programming.
The events are created by the framework based on interpreting lower-level inputs, which may
be lower-level events themselves. For example, mouse movements and clicks are interpreted
as menu selections. The events initially originate from actions on the operating system level,
such as interrupts generated by hardware devices, software interrupt instructions, or state
changes in polling. On this level, interrupt handlers and signal handlers correspond to event
handlers.

SIIT

1
! 06

ITS100 Programming is fun

Simple Event Driven Programming with Python Turtle

Event-driven programming can also be defined as an application architecture technique in


which the application has a main loop which is clearly divided down to two sections:

the first is event selection (or event detection)

the second is event handling.

Just to make everything simple, we will handle events generated by user on the Turtle
screen. There are useful turtle functions for this task.
functions

description

turtle.listen( )

Set focus on TurtleScreen (in order to collect key-events). Dummy arguments are
provided in order to be able to pass listen() to the onclick method.

turtle.onscreenclick(funct)

Bind fun to mouse-click events on this turtle. If fun is None, existing bindings are

removed. Example for the anonymous turtle, i.e. the procedural way:
Parameters:
funct a function with two
arguments which will be
called with the coordinates
of the clicked point on the
canvas

example
def turn(x, y):
...

turtle.goto(x,y)
turtle.dot(20,red)

turtle.onscreenclick(turn)

turtle.onkey(funct, key)

Bind fun to key-release event of key. If fun is None, event bindings are removed.

Remark: in order to be able to register key-events, TurtleScreen must have the

Parameters:
funct a function with no
arguments

focus. (See method listen().)

key a string: key (e.g.


a) or key-symbol (e.g.
space)

SIIT

1
! 07

ITS100 Programming is fun

There are also some useful turtle functions that can help generate a smooth animation
15
turtle.clear( )

Delete the turtles drawings from the screen. Do not move turtle. State and
position of the turtle as well as drawings of other turtles are not affected.

turtle.hideturtle( )

Make the turtle invisible. Its a good idea to do this while youre in the middle of
doing some complex drawing, because hiding the turtle speeds up the drawing
observably.

turtle.update( )

Perform a TurtleScreen update. To be used when tracer is turned off.

turtle.tracer(0)

Set tracing on/off (according to whether flag is true or not). Tracing means line are
drawn more slowly, with an animation of an arrow along the line.

turtle.pensize(10)

change the size of the pen

turtle.setheading(deg)

Set the turtle direction

Simple example: Response to Mouse click


Lets write a simple program that responses to users mouse click. Just display a big red dot
at the location that user click the left button on her mouse. The code and example output are
displayed.
import turtle as t

def newball(clickx,clicky):
t.pen(pensize=10)
t.goto(clickx,clicky)
t.dot(100,"red")

t.tracer(0)
t.listen()
t.onscreenclick(newball)

The t.tracer(0) is to set tracer off to make sure that turtle will draw faster. Then t.listen( )
starts listening and waiting for events. We response to one event, the left click on the screen
with t.onscreenclick(newball) and with this command we also pass a name of event
handler or the function that handle this event, newball. This function needs to have 2
parameters because the event will pass coordinate x,y to those two parameters. We then

SIIT

1
! 08

ITS100 Programming is fun

draw red dots on the point that user just clicks.

Simple example: Response to key press


In this example, we will response to a key press. We will set the listener to listen to 4 events,
the press of key left, right, up and down.
import turtle as t
def goleft():
t.setheading(180)
t.fd(20)
def goright():
t.setheading(0)
t.fd(20)
def goup():
t.setheading(90)
t.fd(20)
def godown():
t.setheading(270)
t.fd(20)
t.listen()
t.pensize(10)
t.pencolor("blue")
t.onkey(goleft,"Left")
t.onkey(goright,"Right")
t.onkey(goup,"Up")
t.onkey(godown,"Down")

The t.listen( ) starts listening and waiting for events. We set a pensize and pencolor to 10
and blue respectively. Then wait for 4 keys, left, right, up and down. If the left key is pressed,
function goleft will be call to handle the event. In similar fashion, goright, goup and godown
will handle the rest 3 events. In the handler functions, its just very simple, we set the turtle
heading in the appropriate direction and just draw a line of 20px.

SIIT

1
! 09

ITS100 Programming is fun

Problem Solving:
Write a program to let user click on a turtle screen. When the user clicks, add a new
animated bouncing ball of size 100px with a random color to the screen (In the lab, you
will have to do the reversed. There are many bouncing balls at the beginning and if the user
import turtle as t
import random as r
x=[]
y=[]
mx=[]
my=[]
c=[]
n=0
colour = ["red",
"green","blue","yellow","pink","black"]
def putball(cx, cy):
global n
x.append(cx)
y.append(cy)
mx.append(r.randint(-2,2))
my.append(r.randint(-2,2))
c.append(r.choice(colour))
n += 1
def updateball():
for i in range(n):
x[i] += mx[i]
y[i] += my[i]
if (x[i]<-200) or (x[i]>200): mx[i] *= -1
if (y[i]<-200) or (y[i]>200): my[i] *= -1
t.goto(x[i],y[i])
t.dot(50,c[i])
t.setup(500,500,0,0)
t.tracer(0)
t.hideturtle()
t.pu()
t.listen()
t.onscreenclick(putball)
while (3>2):
t.clear()
updateball()
t.update()

click on the ball, it will pop out of the screen)


SIIT

1
! 10

ITS100 Programming is fun

Write a single-player Pingpong game with Pythons turtle. A animate bouncing pingpong is
initialized randomly on the screen. At the lower part of the screen, there is a paddle that user
import turtle as t
x = 20
y = 10
xmove = 1
ymove = 1
paddlex = 0
t.pensize(10)
t.tracer(0)
t.pu()
t.listen()
def drawpaddle():
t.goto(paddlex,0)
t.setheading(0)
t.pd()
t.fd(50)
t.pu()
def goleft():
global paddlex
paddlex = paddlex-10
def goright():
global paddlex
paddlex = paddlex+10
def updatepingpong():
global x,y,xmove,ymove
x = x + xmove
y = y + ymove
if (x>200) or (x<-200): xmove = -1 * xmove
if (y>200) or (y<-10): ymove = -1 * ymove
if (y<=10) and (x>paddlex) and (x < paddlex+50): ymove = -1 * ymove
def drawpingpong():
t.goto(x,y)
if (y < 0):
print("Failed!")
t.dot(10,"red")
else:
t.dot(20,"black")
while (3>2):
t.clear()
drawpingpong()
updatepingpong()
drawpaddle()
t.onkey(goleft,"Left")
t.onkey(goright,"Right")
t.update()

can control with keyboards left or right keys. The pingpong ball can bounce off the walls
and pingpong paddle. If the user miss the ball and the ball can get below the paddle, the
user loses. (In the lab, modify this program to have more pingpong at the same time)

SIIT

1
! 11

ITS100 Programming is fun

Self Practice
1. Write a Python program to display this shape

2.

SIIT

1
! 12

You might also like