Chapter 01 Intro to Programming & Python
Chapter 01 Intro to Programming & Python
Introduction to Computers,
Programs, and Python
1
Objectives
❑To demonstrate a basic understanding of computer
hardware, programs, and operating systems (§§1.2–1.4).
❑To describe the history of Python (§1.5).
❑To explain the basic syntax of a Python program (§1.6).
❑To write and run a simple Python program (§1.6).
❑To explain the importance of, and provide examples of,
proper programming style and documentation (§1.7).
❑To explain the differences between syntax errors, runtime
errors, and logic errors (§1.8).
❑To create a basic graphics program using Turtle (§1.9).
2
What is a Computer?
▪ A computer consists of a CPU, memory, hard disk, flash disk,
memory cards, monitor, printer, and communication devices.
▪ Performs computations and makes logical decisions
▪ Millions / billions times faster than human beings
▪ Computer programs, Hardware, Software, memory.
Bus
3
Computer organization
▪ Six logical units of computer system
1. Input unit:
• E.g. Mouse, keyboard
2. Output unit:
• E.g. Printer, monitor, audio speakers
3. Memory unit:
• E.g. RAM, ROM
4. Arithmetic and logic unit (ALU):
• Performs calculations
5. Central processing unit (CPU):
• Supervises operation of other devices
6. Secondary storage unit:
• E.g. Hard drives, flash drives
4
CPU
▪ The central processing unit (CPU) is the brain of a computer.
▪ It retrieves instructions from memory and executes them.
▪ The CPU speed is measured in megahertz (MHz), with 1 megahertz
equaling 1 million pulses per second.
▪ The speed of the CPU has been improved continuously.
▪ If you buy a PC now, you can get an Intel Pentium Core i9 Processor at
28 gigahertz (1 gigahertz is 1000 megahertz).
Bus
5
Bits and Bytes
• Computers store information using binary digits (bits) i.e., 0’s and 1’s.
• The minimum storage unit in a computer is a byte. A byte is composed
of eight bits.
• A small number such as 3 can be stored as a single byte. To store a
number that cannot fit into a single byte, the computer uses several
bytes.
• A kilobyte (KB) is about 1,000 bytes or 1024 bytes.
• A megabyte (MB) is about 1 million bytes or 1024 KB.
• A gigabyte (GB) is about 1 billion bytes or 1024 MB.
• A terabyte (TB) is about 1 trillion bytes or 1024 GB.
6
Memory
▪ Memory is to store data and program instructions for CPU to execute.
▪ A memory unit is an ordered sequence of bytes, each holds eight bits.
▪ A program and its data must be brought to memory before they can be
executed.
▪ A memory byte is never empty, but its initial content may be
meaningless to your program.
▪ The current content of a memory byte is lost whenever new information
is placed in it.
Bus
7
How Data is Stored?
• Data of various kinds, such as numbers, characters,
and strings, are encoded as a series of bits (zeros Memory address Memory content
and ones).
• Computers use zeros and ones because digital
devices have two stable states, which are referred . .
to as zero and one by convention. . .
• The programmers need not to be concerned about . .
the encoding and decoding of data, which is
performed automatically by the system based on 2000 01001010 Encoding for character ‘J’
the encoding scheme. 2001 01100001 Encoding for character ‘a’
• The encoding scheme varies. For example, 2002 01110110
character ‘J’ is represented by 01001010 in one Encoding for character ‘v’
byte. 2003 01100001 Encoding for character ‘a’
• A small number such as three can be stored in a 2004 00000011 Encoding for number 3
single byte.
• If computer needs to store a large number that
cannot fit into a single byte, it uses a number of
adjacent bytes.
• No two data can share or split a same byte. A byte
is the minimum storage unit.
8
Storage Devices
▪ Memory is volatile, because information is lost when the power is off.
▪ Programs and data are permanently stored on storage devices and are
moved to memory when the computer actually uses them.
▪ There are three main types of storage devices: Disk drives (hard disks
and USB flash disks), CD drives (CD-R and CD-RW), and Tape
drives.
Bus
9
Input/Output Devices: Monitor
Bus
10
Monitor Resolution and Dot Pitch
resolution The screen resolution specifies the number of pixels in
horizontal and vertical dimensions of the display device.
Pixels (short for “picture elements”) are tiny dots that
form an image on the screen. A common resolution for a
17-inch screen, for example, is 1,024 pixels wide and
768 pixels high. The resolution can be set manually. The
higher the resolution, the sharper and clearer the image
is.
dot pitch The dot pitch is the amount of space between pixels,
measured in millimeters. The smaller the dot pitch, the
sharper the display.
11
Communication Devices
❑ A regular modem uses a phone line and can transfer data in a speed up to 56,000 bps
(bits per second).
❑ A DSL (digital subscriber line) also uses a phone line and can transfer data in a speed
20 times faster than a regular modem.
❑ A cable modem uses the TV cable line maintained by the cable company. A cable
modem is as fast as a DSL.
❑ Network interface card (NIC) is a device to connect a computer to a local area
network (LAN). The LAN is commonly used in business, universities, and
government organizations. A typical type of NIC, called 10BaseT, can transfer data
at 10 mbps (million bits per second). Wireless networking is now popular.
Bus
13
Evolution of Operating Systems
▪ Batch processing
• One job (task) at a time
• Operating systems developed
➢Programs to make computers more convenient to use
➢Switch jobs easier
▪ Multiprogramming
• “Simultaneous” jobs
• Timesharing operating systems
14
Major tasks of OS
• The major tasks of an operating system are:
1. Controlling and monitoring system activities:
• Operating systems perform basic tasks, such as recognizing input from
the keyboard, sending output to the monitor, keeping track of files and
folders on storage devices, and controlling peripheral devices, such as
disk drives and printers.
2. Allocating and assigning system resources:
• The operating system is responsible for determining what computer
resources a program needs (such as CPU time, memory space, disks,
input and output devices) and for allocating and assigning them to run
the program.
3. Scheduling operations:
• The OS is responsible for scheduling programs’ activities to make
efficient use of system resources.
15
What is programming/program?
▪ Programming a computer simply means telling it what to do;
▪ A program is a precise sequence of steps to solve a particular
problem;
▪ It is a sequence of instructions that specifies how to perform
a computation.;
▪ The computation might be: -
• mathematical, like solving a system of equations or finding the roots
of a polynomial,
• a symbolic computation, like searching and replacing text in a
document or (strangely enough) compiling a program.
• The instructions (or commands, or statements) look different in
different programming languages, but there are a few basic
functions that appear in just about every language:
• input: Get data from the keyboard, or a file, or some other
device.
• output: Display data on the screen or send data to a file or
other device.
• math: Perform basic mathematical operations like addition and
multiplication.
• testing: Check for certain conditions and execute the
appropriate sequence of statements.
• repetition: Perform some action repeatedly, usually with some
variation.
17
Why Programming is important
• Learning to program is important because it develops analytical and
problem solving abilities.
• It is a creative activity and provides us a means to express abstract
ideas.
• By designing programs, we learn many skills that are important for
all professions. These skills can be summarized as:
• Critical reading
• Analytical thinking
• Creative synthesis
18
What skills are needed
• Paying attention to detail
• A good programmer always analyzes the problem statement very carefully
and in detail.
• Think about the reusability.
• Whenever you are writing a program, always keep in mind that it could be
reused at some other time.
• Think about user interface
• Never assume that the user of your program is computer literate. Always
provide an easy to understand and easy to use interface that is self
explanatory.
• Understand the fact the computers are stupid
• They do exactly what you tell them to do: no more, no less-- unlike human
beings. Computers can't think by themselves.
• Comment the code liberally
• Always comment the code liberally.
19
Program design recipe
• Just like soccer players, architects, composers, or writers, programmers
must practice the basic skills of their trade for a long time before they
can be truly creative.
• Design recipes are the equivalent of soccer ball handling techniques,
writing techniques, arrangements, and drawing skills.
• To design a program properly, we must:
• Analyze a problem statement, typically expressed as a word problem;
• Express its essence, abstractly and with examples;
• Formulate statements and comments in a precise language;
• Evaluate and revise the activities in light of checks and tests and
• Pay attention to detail.
20
Example … a Simple Recipe
21
Programming methodologies
▪ Object-oriented programming
• is an approach that provides a way of modularizing programs i.e.
dividing programs into smaller parts (objects, classes, etc.)
▪ Structured programming
• Is a paradigm aimed on improving clarity, quality, & development
time of a computer program by making use of subroutines &
structures.
▪ Functional programming
• This uses functions as fundamental building blocks of the program.
A function is a collection of statements that perform a particular
task.
Programs
▪ Computer programs, known as software, are instructions to the
computer.
▪ You tell a computer what to do through programs.
▪ Without programs, a computer is an empty machine. Computers do
not understand human languages, so you need to use computer
languages to communicate with them.
▪ Programs are written using programming languages.
23
Programming Languages
Machine Language Assembly Language High-Level Language
1101101010011010
24
Programming Languages
Machine Language Assembly Language High-Level Language
25
Programming Languages
Machine Language Assembly Language High-Level Language
The high-level languages are English-like and easy to learn and program.
For example, the following is a high-level language statement that
computes the area of a circle with radius 5:
area = 5 * 5 * 3.1415;
26
Popular High-Level Languages
Language Description
Ada Named for Ada Lovelace, who worked on mechanical general-purpose computers. The Ada
language was developed for the Department of Defense and is used mainly in defense projects.
BASIC Beginner’s All-purpose Symbolic Instruction Code. It was designed to be learned and used easily
by beginners.
C Developed at Bell Laboratories. C combines the power of an assembly language with the ease of
use and portability of a high-level language.
C++ C++ is an object-oriented language, based on C.
C# Pronounced “C Sharp.” It is a hybrid of Java and C++ and was developed by Microsoft.
COBOL COmmon Business Oriented Language. Used for business applications.
FORTRAN FORmula TRANslation. Popular for scientific and mathematical applications.
Java Developed by Sun Microsystems, now part of Oracle. It is widely used for developing platform-
independent Internet applications.
Pascal Named for Blaise Pascal, who pioneered calculating machines in the seventeenth century. It is a
simple, structured, general-purpose language primarily for teaching programming.
Python A simple general-purpose scripting language good for writing short programs.
Visual Visual Basic was developed by Microsoft and it enables the programmers to rapidly develop
Basic graphical user interfaces.
27
Tools of the trade
▪ Editors
• First of all we need a tool for writing the code of a program. E.g.
NotePad, NetBeans, Eclipse, Borland C++, PyCharm, & other text
editors are used.
▪ Compiler and Interpreter
• An interpreter is a program that reads a high-level program and
does what it says. In effect, it translates the program line-by-line,
alternately reading lines and carrying out commands.
• Drawbacks of the interpreter include:
➢the program executes slowly;
➢as interpreters are reading the program line by line, they cannot get the
overall picture of the program hence cannot optimize the program making
it inefficient.
Tools cont’d …
• A compiler is a program that reads a high-level program and
translates it all at once, before executing any of the commands.
➢Often you compile the program as a separate step, and then execute the
compiled code later.
➢In this case, the high-level program is called the source code, and the
translated program is called the object code (bytecode - Java) or the
executable.
• A compiler will stop translating if it finds an error and there will be
no executable code generated whereas Interpreter will execute all
the lines before error and will stop at the line which contains the
error.
• So Compiler needs syntactically correct program to produce an
executable code.
Tools cont’d ...
▪ Debugger
• Debugger is used to debug the program i.e. to correct the logical
errors.
• Using debugger we can control our program while it is running. We
can stop the execution of our program at some point and can check
the values in different variables, can change these values etc.
• In this way we can trace the logical errors in our program and can
see whether our program is producing the correct results.
• This tool is very powerful, so it is complex too.
Tools cont’d …
▪ Linker
• Most of the time our program is using different routines and
functions that are located in different files, hence it needs the
executable code of those routines/functions.
• Linker is a tool which performs this job, it checks our program and
includes all those routines or functions which we are using in our
program to make a standalone executable code and this process is
called Linking.
Tools …
▪ Loader
• After a executable program is linked and saved on the disk and it is
ready for execution.
• We need another processor which loads the program into memory
and then instruct the processor to start the execution of the
program from the first instruction (the starting point of every C
program is from the main function, and every java program is the
main method).
• This processor is known as loader.
What is debugging?
• Programming is a complex process, and since it is done by
human beings, it often leads to errors.
• For whimsical reasons, programming errors are called bugs
and the process of tracking them down and correcting them
is called debugging.
33
Kinds of errors
• Compile-time errors/Syntax errors
• The compiler can only translate a program if the program is syntactically
correct; otherwise, the compilation fails and you will not be able to run your
program. Syntax refers to the structure of your program and the rules about
that structure.
• For example, in English, a sentence must begin with a capital letter and end
with a period. this sentence contains a syntax error. So does this one
• There are more syntax rules in programming languages than there are in
English, and the error messages you get from the compiler are often not very
helpful.
34
• Run-time errors
• Runtime errors are errors that cause a program to terminate
abnormally. They occur while a program is running if the Python
interpreter detects an operation that is impossible to carry out.
• Typically caused by input mistakes, when the user enters a value
that the program cannot handle e.g. string instead of number.
• The second type of error is a run-time error, so-called because the
error does not appear until you run the program.
• Another example and common source is division by zero.
35
• Logic errors and semantics
• If there is a logical error in your program, it will compile and run
successfully, in the sense that the computer will not generate any
error messages, but it will not do the right thing. It will do
something else. Specifically, it will do what you told it to do.
• The problem is that the program you wrote is not the program you
wanted to write.
• The meaning of the program (its semantics) is wrong.
• Identifying logical errors can be tricky, since it requires you to work
backwards by looking at the output of the program and trying to
figure out what it is doing.
1 # Convert Fahrenheit to Celsius
2 print("Fahrenheit 35 is Celsius degree ")
3 print(5 / 9 * 35 - 32)
36
Interpreting/Compiling Source Code
37
Interpreting Source Code
▪ An interpreter reads one statement from the source code,
translates it to the machine code or virtual machine code, and
then executes it right away, as shown in the following figure.
▪ Note that a statement from the source code may be translated
into several machine instructions.
38
Compiling Source Code
▪ A program written in a high-level language is called a source
program.
▪ Since a computer cannot understand a source program, a
program called a compiler translates the entire source code
into a machine-code file (object program)
▪ The machine-code file is then executed, as shown in the
following figure.
39
Compiling Source Code ….
• The object program is often then linked with other supporting
library code before the object can be executed on the
machine.
Library Code
40
Why Python?
▪ Python is a general-purpose programming language. That means you can use
Python to write code for any programming task.
▪ Python is now used in the Google search engine, in mission-critical projects at
NASA, and in transaction processing at the New York Stock Exchange, etc.
▪ Python is interpreted, which means that Python code is translated and executed
by an interpreter, one statement at a time. In a compiled language, the entire
source code is compiled and then executed altogether.
▪ Python is an object-oriented programming (OOP) language. Data in Python are
objects created from classes.
▪ A class is essentially a type or category that defines objects of the same kind
with properties and methods for manipulating objects.
▪ Object-oriented programming is a powerful tool for developing reusable
software (to be handled later). 41
Python’s History
▪ Python was created by Guido van Rossum in the Netherlands
in 1990 and was named after the popular British comedy
troupe Monty Python’s Flying Circus.
▪ Van Rossum developed Python as a hobby, and Python has
become a popular programming language widely used in
industry and academia due to its simple, concise, and
intuitive syntax and extensive library.
▪ Python is now being developed and maintained by a large
team of volunteers and is available for free from the Python
Software Foundation (Open source).
42
History …
• Two versions of Python are currently coexistent: Python 2
and Python 3.
• The programs written in Python 3 will not run in Python 2.
• Python 3 is a newer version, but it is not backward-
compatible with Python 2. This means that if you write a
program using the Python 2 syntax, it may not work with a
Python 3 interpreter.
• Python provides a tool that automatically converts code
written in Python 2 into syntax Python 3 can use. Python 2
will eventually be replaced by Python 3.
43
Popular Python Integrated development
environments/IDEs
▪ PyCharm
▪ Python (Command Line)
▪ IDLE (GUI)
▪ Programmer’s NotePad
▪ Sun NetBeans
▪ IBM Eclipse
▪ Microwerk’s CodeWarrior
44
Thinking About Objects: Introduction to Object
Technology: Python is an OOP language
▪ Objects
• Reusable software components that model real-world items
• Look all around you
➢People, animals, plants, cars, etc.
• Attributes (properties or characteristics)
➢Size, shape, color, weight, etc.
• Behaviors (tasks performed by or on the objects)
➢Babies cry, crawl, sleep, etc.
45
Objects …
▪ Object-oriented design (OOD)
• Models real-world objects
• Models communication among objects
• Encapsulates data (attributes) and functions (behaviors)
➢Information hiding
➢Communication through well-defined interfaces
▪ Object-oriented language
• This type of programming is called object-oriented programming
(OOP)
• OOP is implemented using object-oriented languages such as
Python, Java, C++, C#, etc.
46
Installing Python & IDE
• Download the latest version of Python 3
• https://www.python.org/downloads/
• https://www.python.org/downloads/windows/
• https://www.python.org/downloads/release/python-3114/
• Download the PyCharm IDE
• https://www.jetbrains.com/pycharm/download/
• https://www.jetbrains.com/pycharm/download/?section=windo
ws
• https://www.jetbrains.com/pycharm/download/?section=linux
47
Launching Python
• Assume you have Python installed on the Windows OS. You can
start Python in a command window by typing python at the
command prompt, or by using IDLE.
• IDLE (Interactive DeveLopment Environment) is an integrated
development environment (IDE) for Python.
• You can create, open, save, edit, and run Python programs in
IDLE.
• Both the command-line Python interpreter and IDLE are available
after Python is installed on your machine.
• After Python starts, you will see the symbol >>>. This is the
Python statement prompt, and it is where you can enter a Python
statement.
48
A Simple Python Program
49
Creating Python Source Code Files
• Entering Python statements at the statement prompt >>> is
convenient, but the statements are not saved.
• To save statements for later use, you can create a text file to
store the statements and use the following command to
execute the statements in the file:
python filename.py
• The text file can be created using a text editor such as
Notepad. The text file, filename, is called a Python source
file or script file, or module.
• By convention, Python files are named with the extension
.py. 50
Running a Python Program
• Running a Python program from a script file is known as
running Python in script mode.
• Typing a statement at the statement prompt >>> and
executing it is called running Python in interactive mode.
51
LISTING 1.1 Welcome.py
• 1 # Display two messages
• 2 print("Welcome to Python")
• 3 print("Python is fun")
52
Example …
• In the above text, line numbers are displayed for reference
purposes; they are not part of the program. So, don’t type
line numbers in your program.
• Suppose the statements are saved in a file named
Welcome.py.
• To run the program, enter python Welcome.py at the
command prompt.
53
Comments
• Line 1 is a comment that documents what the program is
and how it is constructed.
• Comments help programmers communicate and understand
a program.
• They are not programming statements and thus are ignored
by the interpreter.
• In Python, comments are preceded by a pound sign (#) on a
line, called a line comment, or enclosed between three
consecutive single quotation marks (' ' ') on one or several
lines, called a paragraph comment.
54
Comments …
• When the Python interpreter sees #, it ignores all text after #
on the same line. When it sees ' ' ', it scans for the next ' ' '
and ignores any text between the triple quotation marks.
• Here are examples of comments:
# This program displays Welcome to Python
' ' ' This program displays Welcome to Python and
Python is fun
'''
55
Indentation matters in Python.
• Note that the statements are entered from the first
column in the new line.
• The Python interpreter will report an error if the
program is typed as follows:
# Display two messages
print("Welcome to Python")
print("Python is fun")
56
Others …
• Don’t put any punctuation at the end of a statement.
• For example, the Python interpreter will report errors
for the following code:
# Display two messages
print("Welcome to Python").
print("Python is fun"),
57
Python is case sensitive
• Python programs are case sensitive.
• It would be wrong, for example, to replace print in the
program with Print.
58
Special Characters
59
LISTING 1.2 WelcomeWithThreeMessages.py
60
Using Python To Perform Mathematical
Computations
• Python programs can perform all sorts of mathematical
computations and display the result.
• To display the addition, subtraction, multiplication, and
division of two numbers, x and y, use the following code:
print(x + y) >>>2 + 3 or >>>print(2 + 3)
print(x – y) 5
>>>8 – 7
print(x * y) 1
print(x / y) >>>5 * 8
40
print(x % y) >>>8 / 4
2.0
>>>5 % 2
61
1
Example:
• Listing 1.3 shows an example of a program that evaluates
62
Exercise
• Show the output of the following code:
>>>print("3.5 * 4 / 2 - 2.5 is")
>>>print(3.5 * 4 / 2 - 2.5)
63
Programming Style and Documentation
• Programming style deals with what programs look like.
• When you create programs with a professional programming
style, they not only execute properly but are easy for people
to read and understand.
• Documentation is the body of explanatory remarks and
comments pertaining to a program.
• These remarks and comments explain various parts of the
program and help others understand its structure and
function.
64
1. Appropriate Comments and Comment
Styles
• Include a summary comment at the beginning of the
program to explain what the program does, its key features,
and any unique techniques it uses.
• In a long program, you should also include comments that
introduce each major step and explain anything that is
difficult to read.
• It is important to make comments concise so that they do
not crowd the program or make it difficult to read.
65
2. Proper Spacing
• A consistent spacing style makes programs clear and easy to
read, debug (find and fix errors), and maintain.
• A single space should be added on both sides of an operator,
as shown in the following statement:
66
Getting Started with Graphics Programming
• Turtle is Python’s built-in graphics module for drawing lines,
circles, and other shapes, including text.
• It is easy to learn and simple to use.
• There are many ways to write graphics programs in Python.
• A simple way to start graphics programming is to use
Python’s built-in turtle module.
• Later, we will introduce Tkinter for developing
comprehensive graphical user interface applications.
67
Drawing and Adding Color to a Figure
• The following procedure will give you a basic introduction to
using the turtle module. Subsequent chapters introduce
more features.
• 1. Launch Python by choosing Python (command line) from the
Windows Start button or by typing python at the command
prompt.
• 2. At the Python statement prompt >>>, type the following
command to import the turtle module. This command imports all
functions defined in the turtle module and makes them available
for you to use.
• >>> import turtle # Import turtle module
68
Drawing …
• 3. Type the following command to show the current location
and direction of the turtle.
• >>> turtle.showturtle()
• 4. Type the following command to draw a text string:
• >>> turtle.write("Welcome to Python")
• 5. Type the following command to move the arrowhead 100
pixels forward to draw a line in the direction the arrow is
pointing:
• >>> turtle.forward(100)
69
Complete the drawing …
• 6. Type the following commands to turn the arrowhead right
90 degrees, change the turtle’s color to red, and move the
arrowhead 50 pixels forward to draw a line:
• >>> turtle.right(90)
• >>> turtle.color("red")
• >>> turtle.forward(50)
70
Another one …
• >>> turtle.color("green")
• 7. Now, type the following commands to turn the arrowhead
right 90 degrees, set the color to green, and move the
arrowhead 100 pixels forward to draw a line:
• >>> turtle.right(90)
• >>> turtle.forward(100)
71
Finally …
• 8. Finally, type the following commands to turn the
arrowhead right 45 degrees and move it 80 pixels forward to
draw a line:
• >>> turtle.right(45)
• >>> turtle.forward(80)
• 9. You can now close the Turtle Graphics window and exit
Python.
72
Moving the Pen to Any Location
• When the Turtle program starts, the arrowhead is at the
center of the Python Turtle Graphics window at the
coordinates (0, 0).
• You can also use the goto(x, y) command to move the turtle
to any specified point (x, y).
• Restart Python and type the following command to move the
pen from (0, 0) to (0, 50)
• >>> import turtle
• >>> turtle.goto(0, 50)
73
Pen …
• You can also lift the pen up or put it down to control whether
to draw a line when the pen is moved by using the penup()
and pendown() commands.
• For example, the following commands move the pen to (50, -
50).
• >>> turtle.penup()
• >>> turtle.goto(50, -50)
• >>> turtle.pendown()
74
Draw a Circle
• You can draw a circle using the circle command.
• For example, the following commands set color red and
draw a circle with radius 50.
• >>> turtle.color("red")
• >>> turtle.circle(50) # Draw a circle with radius 50
75
Example:
Drawing the Olympic Rings Logo
76
Example: Drawing the Olympic Rings Logo
#LISTING 1.5 OlympicSymbol.py • 10 turtle.penup()
1 import turtle • 11 turtle.goto(0, -25)
2 • 12 turtle.pendown()
3 turtle.color("blue") • 13 turtle.circle(45)
4 turtle.penup() • 14
5 turtle.goto(-110, -25) • 15 turtle.color("red")
6 turtle.pendown() • 16 turtle.penup()
7 turtle.circle(45) • 17 turtle.goto(110, -25)
8 • 18 turtle.pendown()
9 turtle.color("black") • 19 turtle.circle(45)
77
Olympic Rings …
• 20 • 26
• 21 turtle.color("yellow") • 27 turtle.color("green")
• 22 turtle.penup() • 28 turtle.penup()
• 29 turtle.goto(55, -75)
• 23 turtle.goto(-55, -75)
• 30 turtle.pendown()
• 24 turtle.pendown() • 31 turtle.circle(45)
• 25 turtle.circle(45) • 32
• 33 turtle.done()
78
• The program imports the turtle module to use the Turtle
Graphics window (line 1).
• It moves the pen to (-110, -25) (line 5) and draws a blue
circle with radius 45 (line 7).
• Similarly, it draws a black circle (lines 9–13), a red circle (lines
15–19), a yellow circle (lines 21–25), and a green circle (lines
27–31).
• Line 33 invokes turtle’s done() command, which causes the
program to pause until the user closes the Python Turtle
Graphics window. The purpose of this is to give the user time
to view the graphics. Without this line, the graphics window
would be closed right after the program is finished.
79
Questions??????
80