Python Programming

advertisement
Computer Science for Everyone
An Introduction to Programming – Python
Version 1.1.8
Computer Science for Everyone
An Introduction to Programming – Python
Version 1.1.8
Scott Durkin
Fort Collins, Colorado
http://poudre.us/cs
Copyright © 2011 Scott Durkin
Permission is granted to copy, distribute, and/or modify this document under the terms of the GNU Free
Documentation License, Version 1.1, or an later version published by the Free Software Foundation.
The GNU Free Documentation License is available from http://www.gnu.org
Preface
As a short "curriculum module" regarding an introduction to computer programming for children
who are around eleven or twelve years old (and for some teachers who may have never
programmed before), this document has been fashioned to provide the reader (teacher and
perhaps some motivated students of various ages) an elementary introduction to the topic of
computer science. For the instructor who has programmed before and is not yet familiar with the
Python language, she or he will find it easy to glean an appropriately-paced series of lesson plans
from this document either by following the outline provided, or devising one's own. Regardless
of your experience with programming as a teacher, it is hoped that you will find this and/or other
beginning tutorials/textbooks on this subject helpful in tailoring lessons for your situation.
This resource contains text, graphics, videos, code, documentation, and links to other resources,
but it may not be worthwhile unless the learner, student and teacher alike, becomes physically
and mentally involved by entering code and writing scripts in Python; and in the process,
actively thinking about computer science and beginning on the path of becoming a programmer.
Learning how to program may significantly enhance a person's ability to read, think and solve
problems in many areas of life and study; and perhaps in the case of some of the students who
read this or learn from a teacher who has, even learn a little more about some of the concepts
related to grade-level mathematics standards at the same time.
This pedagogical view is driven by the current K-12 models for computer science instruction
from CSTA of ACM and other entities, along with such landmark works as Being Fluent in
Information Technology from the National Academy of Sciences.
Of course, Python could be used with younger students, and as mentioned, multiple K-12
computer science curriculum models exist at many organizational levels in this and other nations.
For instance, a kindergarten teacher in the spring could encourage an able student to double-click
on the icon of the Python snake and type, print "Marissa " * 50, for example, to
witness her name instantly appear fifty times on the computer monitor as a stated or unstated
example of repeated addition or multiplication. What could be the educational ramifications if as
a matter of simple practice and no-cost benefit every student in this or any school district knew
how to program in one or more professional open source and/or proprietary computer languages
at a measurable level commensurate to or beyond many of the concepts associated with her or his
grade-level mathematics standards?
Scott Durkin
Contents
PYTHON PROGRAMMING.................................................................................................................... 1
TEACHING OUTLINE ............................................................................................................................. 2
GETTING STARTED ............................................................................................................................... 3
Installing Python 2.2.3......................................................................................................................... 3
Something to Keep in Mind ................................................................................................................ 3
Python IDLE and the Hello, World! Test........................................................................................ 4
The Hello, World! Program................................................................................................................ 5
Keywords and Color-coded Text ...................................................................................................... 6
Documentation/Adding Comments ................................................................................................ 6
Errors ........................................................................................................................................................ 7
Opening Existing Scripts in Python ................................................................................................. 7
Python Help ............................................................................................................................................. 8
Glossary ................................................................................................................................................................ 8
THE BASICS .............................................................................................................................................. 9
Data Types and Variables ................................................................................................................... 9
Built-in Functions.................................................................................................................................. 9
Variables and Data Types – An Overview ................................................................................... 10
Using the IDLE Shell to Learn About Variables and Data Types ......................................... 11
How Python Handles Basic Math ................................................................................................... 12
Computer Science and 6th Grade Mathematics Standards .................................................... 13
Glossary ............................................................................................................................................................. 14
SIMPLE APPLICATIONS...................................................................................................................... 15
The Halt! Who Goes There? Program (halt.py) ........................................................................ 15
The raw_input Function.............................................................................................................................. 15
Type Coercion ................................................................................................................................................. 15
Conditional Statements and Indentation (White-space) ............................................................... 16
Code for the halt.py Program .................................................................................................................... 17
Glossary ............................................................................................................................................................. 19
Area and Perimeter Program (rectangle.py) ............................................................................ 21
The High/Low Guessing Game (guess.py) .................................................................................. 22
The while Loop ............................................................................................................................................... 22
Creating the High/Low Guessing Game ................................................................................................ 23
Developing the Initial Program ................................................................................................................ 23
The Initial Script ............................................................................................................................................ 24
Generating a Random Number ................................................................................................................ 25
Adding a Counter ........................................................................................................................................... 26
Adding Feedback ........................................................................................................................................... 27
Putting the Game in a Loop ....................................................................................................................... 28
How Fair is the Random Number Generator? ........................................................................... 29
The for Loop .................................................................................................................................................... 29
Computer Simulation ................................................................................................................................... 30
Glossary ............................................................................................................................................................. 32
The Least Common Multiple (LCM) Finder (lcm.py) ............................................................... 33
The input Function ....................................................................................................................................... 33
The Factors Finder Program (factorsFinder.py)...................................................................... 35
The Change Maker (changeMaker1.py/changeMaker2.py)................................................. 36
Creating changeMaker1.py ........................................................................................................................ 37
Creating changeMaker2.py ........................................................................................................................ 38
The Greatest Common Denominator (GCD) Finder (gcd.py) ............................................... 39
Lists..................................................................................................................................................................... 39
Creating and Using Your Own Functions ............................................................................................. 41
Creating the Program .................................................................................................................................. 43
Glossary ............................................................................................................................................................. 44
Other Simple Applications ............................................................................................................... 46
Careers in Computing ........................................................................................................................ 47
Python Programming
As most are already aware, a computer basically does four things with information: input, output, storage and
processing. In the early 1800s, the term "computer" referred to a human being who did calculations for a living.
Later, this same term applied to the machinery that could do the same four things with information. Due in part to
the pioneering work in computer software development by Ada Lovelace, Rear Admiral Grace Hopper and many
others, computer programming languages have evolved along with computing machinery.
The ever-increasing ubiquitous nature of personal computing that has erupted over just the past few decades may be
viewed by some as its own argument of the need for all citizens to possess a basic understanding of what a computer
is and how it does what is does, even if only at the most fundamental levels. Learning how to program a computer
may also improve some students' level of understanding of certain concepts associated with mathematics. Common
sense may dictate that if a fourth-grader learns how to create a computer program that is able to identify all the
factors of any positive integer, then she or he may enhance his or her understanding of the concept of a factor. In
fact, this is very easy to do in Python. The program could be as short as four or five lines of code; however, the
process of composing and understanding what this code means could have a significant impact on student
achievement.
integer = int(raw_input("Enter any positive integer to view all the factors of that number: "))
for divisor in range(1,integer+1):
if integer % divisor == 0:
factor = divisor
print factor
You may not currently understand all the code above designed to identify all the factors of any positive integer, but
you may soon see that Python is a pretty easy language to learn.
Python is an open source language invented in the early 1990s by Guido van Rossum. It is currently used by
hundreds of thousands of programmers around the world and the number of users tends to double every year.
Though this powerful object-oriented language is used by those at NASA, Google and many other organizations and
universities, it is also an effective introductory language to computer science for most anyone ten years older and up.
"As a first programming language, Python provides a lucid, interactive environment in which to explore procedural,
functional and object oriented approaches to problem solving. Its high level data structures and clear syntax keep the
forest in view through the trees." - Python in Education
This document is designed for any user new to programming, a teacher or able student in fourth grade or above. The
version of Python used is 2.2; however, it could easily be adjusted to work with 3.x.
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
1
Teaching Outline
As with anything like this to impart, the timing and pace of this "curriculum module" may vary from instructor to
instructor, as progress may be a function of the students involved, the experience and comfort level the instructor
has with the material, and other issues.
This document was designed mostly for teachers new to teaching programming. Obviously, an initial step for such a
teacher is to learn how to program, and this document should help guide an instructor through that process. Later, it
is then simply a matter of the instructor mapping out what she or he would like to accomplish each session with
students.
The content of this document is presented in several voices. Sometimes the content is directed to the instructor and
other times it is directed to the student/learner.
Below is one general outline of a possible five-session sequence of the initial portion of the content provided in this
document. The *.py programs below are detailed in this document.
Session 1 – IDLE, Hello, World Test, Variables and Data Types, Math
Session 2 – Hello, World Program, halt.py, rectangle.py
Session3 – guess.py
Session 4 – lcm.py, factorsFinder.py
Session 5 – changeMaker.py
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
2
Getting Started
The Python programming language software is free. It may be downloaded at http://python.org. Many platforms
and versions are available. This document uses a Microsoft Windows operating system for examples, but Python
works with Macintosh and Linux systems as well. For the purpose of student learning in the Poudre School District,
Windows version 2.2.3 is stable in the PSD network. Teachers should see her or his Building Technology
Coordinator for installation of Python on PSD computers, but, if willing, the instructor should also install Python on
one or more home computers to get started.
Windows versions 2.3 to 2.6 may be used on the teacher workstation as the font size may be adjusted larger for
projection; however, there are PSD network stability issues associated with the use of these versions. Versions 3.x
of Python have also been available since 2008. There are subtle yet significant changes in syntax and other aspects
from versions 2.x. Due to fact that Python 3.x is relatively new, does not yet have a vast amount of resources
developed for it (unlike 2.x), and also has stability issues in the PSD network, this document will address the use of
Python 2.2.3 within the Microsoft operating system.
Although 2.2.3 is used in this document, an effort has been made to introduce programming concepts in light of how
things are done in Python 3.x, as that is the future of this language. Later, at some more propitious time, an
experienced user of 2.2.3 will have no trouble migrating to 3.x. As an example, computers in N205 at Preston have
the following versions of Python installed: 2.2, 2.3, 2.5 and 3.1. This is due to various work in Computer
Applications 2 (#1756) with Python using add-on modules specific to certain versions.
Installing Python 2.2.3
If you are student sitting in a PSD classroom, it is likely that one or more versions of Python are already installed on
your workstation. Regardless, anyone reading this document should also take the small amount of time to have
Python 2.2.3 installed on her or his home computer(s). If nothing else, Python is a great and handy calculator.
Please view the video below to learn how to download Python for your computer. Python is completely free and no
registration or other requirement is needed.
How to Download and Install Python 2.2.3 and Open the Python Shell - 3:11 (download_shell.swf)
http://staffweb.psdschools.org/sdurkin/pythonflicks/download_shell.swf
Something to Keep in Mind
If one would like to learn how to program, it is highly advised that as one progresses through this document to
physically perform the examples using Python on a computer. It may also be helpful to print, in color, all or
portions of this document.
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
3
Python IDLE and the Hello, World! Test
Many programming languages have what is known as an integrated development environment (IDE), a user
interface which allows a programmer to create programs. The IDE that comes with Python is called IDLE
(Integrated Development Learning Environment). This name reflects how Python may be used as an effective
teaching language, and also plays on the last name of one of the performers in the Monty Python group, Eric Idle.
The Python IDLE includes an interactive mode – meaning it can provide immediate feedback to input, and may
serve as a helpful way to learn about some programming concepts prior to applying them in programs. Though this
document references use of the IDLE included in the Python installation, there are also commercial IDE's available
for Python, such as WingIDE.
It is a good idea to read this document on or in front of a computer so you can try out the examples as you go.
To get to the Python IDLE, go to the Start menu and select Programs | Python 2.2 | IDLE (Python GUI). GUI stands
for graphical user interface. Once IDLE opens, the user should see the interactive Python shell prompt, three
greater than symbols >>>, or chevron.
Python shell prompt
In the IDLE, the user may conduct the "Hello, World!" test. The "Hello, World!" test is typically the first thing a
programmer does in a new language to learn how difficult or easy it is to get the text, "Hello, World!" to display on
the screen.
At the >>> prompt, type: print "Hello, World!" and press the Enter key. Here, the word "print" actually means
display information to the screen.
>>> print "Hello, World!"
Hello, World!
>>>
As you can see, The Hello, World! Test doesn't get much easier than with Python.
For the sake of comparison, here is the same program in Java:
class Hello {
public static void main (String[] args) {
System.out.println ("Hello, world.");
}
}
Here it is in C++:
#include <iostream.h>
void main ()
{
cout << "Hello, world." << endl;
return 0
}
Please view the video below to learn more about how to access the Python IDLE and perform the Hello, World!
Test. This video also addresses making a Hello, World! Program, described next.
Python IDLE and the Hello, World! Test - 4:56 (hello.swf)
http://staffweb.psdschools.org/sdurkin/pythonflicks/hello.swf
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
4
The Hello, World! Program
When commands are entered in the Python shell the results are immediately displayed to the user, which again is
advantageous when testing something out. Alternatively, a disadvantage is that the code is not preserved for future
use. Most programmers usually like to save an actual program to a file, sometimes referred to as a script.
To save the "Hello, World!" test into a script, first highlight and copy the single line of code from the shell: print
"Hello, World!". That way, you do not have to type it in again as you already know this code works.
From within the shell window, go to File – New Window. This will open a blank window in Python. This is a text
editor window – not much unlike Notepad, for example. However, once you save it with a proper name (described
in the next paragraphs), Python will display helpful information as you enter code along with color-coding text
based on context.
Go to File – Save As and save the file into your school folder for this class with the name hello.py. All Python
program files should always end in .py. Some general file name conventions include: use mostly lower case
letters, do not begin a file name with a numeral, do not use spaces and it must end in .py. If at any time color-coding
is not present in an IDLE script file, then it probably has an invalid file name.
Valid file names:
halt.py
guessingGame.py
Invalid file names: hello world.py
2variables.py
hello
hello.txt
factors.py
helloWorld.py
(contains a space)
(starts with a numeral)
(doesn't end in .py)
(same as above)
Paste the code content into the file.
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
5
Keywords and Color-coded Text
The word "print" is a keyword in Python. Keywords are words already reserved by a computer language for special
purposes. Below is a list of reserved words, or keywords, in Python. Keywords may vary slightly among the
various versions of Python that are available. There is no need to be overly concerned about all the items on this list
at this time. It is just provided here so you know that such words exist and what they are.
and
as
assert
break
class
continue
def
del
elif
else
except
exec
finally
for
from
global
if
import
in
is
lambda
not
or
pass
print
raise
return
try
while
with
yield
Formally, the command you typed in the Hello, World Test is known as a print statement. The keyword "print" is
used to display text to the computer monitor/screen. In order for the text to appear, it must be encased in quotation
marks (or apostrophes, just be consistent). As you may have noticed, such text is colored green. Python IDLE
uses color-coded text to help the programmer read code. For instance in Python 2.2, the keyword "print" is colored
orange and strings are colored green. Colors and when they are used may vary slightly among Python versions.
Documentation/Adding Comments
Take a few moments to document this and any program you write. This is done by adding comments in English to
your computer program. When scripts are run by Python, anything on any line that appears after a hash '#'
character is ignored by the interpreter. Below is the same file documented. Comments appear in red text.
Once the code and documentation are entered, save the changes to the file. Run the file by pressing the F5 key.
Upon running, the shell window should display and the output of the program should appear in the shell.
If the program ran successfully, simply close the shell window.
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
6
Errors
To error is human, to parse 1 2 divine. Parsing is going through your code line-by-line and part by part, to find
problems. As an example, Python is case sensitive – meaning "Print" is not the same as "print".
Say a user entered this for the Hello, World! Test: Print "Hello, World!"
The shell would yield this:
IDLE 0.8 -- press F1 for help
>>> Print "Hello, World!"
SyntaxError: invalid syntax
>>>
In a script file, the IDLE shell would return:
Traceback (most recent call last):
File "<string>", line 1, in ?
File "C:\Python22\howdy.py", line 1
Print "Hello, World!"
^
SyntaxError: invalid syntax
In either case, Python attempts to share with the programmer feedback regarding the error. In neither case however,
does Python provide one with exactly what the problem is other than to highlight or point to the line that has the
problem (great, there is just one line in the program!) and to report that there is a SyntaxError.
A beginner to programming may not readily notice her or his own errors – hence, the errors occurring in the first
place. Also, as you can see, the built-in Python debugger can be less than completely helpful. Students! Parsing
is a great group activity. Please help each other and encourage everyone to seek assistance in the classroom as you
and others encounter errors! Helping others by sharing information, explaining problems and providing possible
solutions with one other is a tremendously effective way to increase one's own understanding of computer science.
Over time this allows everyone in the room to progress at a faster rate as the teacher isn't the only one who can help
students in the room. Under such conditions, more teaching and learning tends to occur during any given amount of
time as academic engaged time is increased due to the timely cooperation which may occur simultaneously
throughout the computer laboratory setting. Taken to the extreme, say if a teacher was challenged to get an entire
roomful of non-programming elementary students (each and every student) to understand and perform the Hello,
World test and program in only four minutes, she or he would be clever to ask for another roomful-worth of
elementary programming students to help each non-programmer on a one-to-one basis as the instructor directs the
class during initial and other pivotal portions of the four minutes.
Tip for teachers: whenever you explore a new feature, consider experimenting with common mistakes you think
some students may make. For example, in the "Hello, World!" program, what happens if you leave out one of the
quotation marks, or both? What if you misspell the word "print" or capitalize it? This approach may increase your
understanding of code and debugging ability when with students, as over time you become more familiar with error
messages and what they mean.
Opening Existing Scripts in Python
To open an existing Python script, it is best to launch Python IDLE and then use File – Open to navigate to the file
you want to open. If one simply double-clicks on a Python script icon, it will likely attempt to run in a DOS
command window and not display the content of the script itself.
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
7
Python Help
Python has a built-in help section accessible from the prompt by typing: help()
Glossary
bug: An error in the program.
debugging: The process of finding and removing any of the three kinds of programming errors.
comment: Information in a program that is meant for other programmers (or anyone reading the
source code) and has no effect on the execution of the program. (Same as documentation.)
documentation: Information in a program that is meant for other programmers (or anyone reading the
source code) and has no effect on the execution of the program. (Same as comment.)
exception: An error that is detected while the program is running.
graphical user interface (GUI): A user interface based on graphics instead of text; uses a mouse as well as a
keyboard as an input device.
hash character: The "#" character, which is used to begin any line of comment/documentation.
integrated development environment (IDE): A user interface which allows a programmer to create programs.
integrated development learning environment (IDLE): The user interface that comes with Python which allows
a programmer to create programs.
interactive mode: A way of using the Python interpreter by typing commands and expressions at
the prompt.
interpret: To execute a program in a high-level computer language, such as Python, by translating it one line at a
time.
keyword: A reserved word that is used by the compiler to parse a program; you cannot use keywords
like if, def, and while as variable names.
parse: To examine a program and analyze the syntax and structure, often to identify possible errors.
print statement: An instruction that causes the Python interpreter to display a value on the screen.
program: A set of instructions that specifies a computation.
prompt: Characters displayed by the interpreter to indicate that it is ready to take input from the
user. The Python shell prompt is three greater than symbols >>>, or chevron.
script: A program stored in a file.
script mode: A way of using the Python interpreter to read and execute statements in a script.
statement: A section of code that represents a command or action.
syntax: The structure of a program.
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
8
The Basics
This brief section describes three common data types: string, integer, and float. Also included is information
regarding variables, assignment statement, assignment operator (=), and built-in functions. In addition to the text in
these sections, be sure to read and understand the code and comments in the IDLE examples.
Data Types and Variables
Computers reference information such as a person's name, e-mail address and age in terms of variables. Variables
are unique single characters or group of characters (often a word) identified by the programmer to store and refer to
such possibly changing values. The value assigned to a variable needs to be associated with a particular data type,
which is based on what kind of information is being stored and how it may be used in the future.
String data type is often used for normal text, such as a person's name, e-mail address, or city of residence. Integer
data type is used for whole numbers. Float data type is used for decimal numbers. There are other data types in
Python, but just these three can get a novice programmer started.
Three common data types in Python
Data type
String <str>
Integer <int>
Float <float>
Use
Text
Whole numbers
Decimal numbers
Variables hold values. For instance, say the word "price" is to be used as a variable to hold the value 19.99. To
make this happen, one uses an assignment statement, which assigns a certain value to a variable. Below is an
example of an assignment statement in the Python shell.
>>> price = 19.99
The "=" symbol in the line above is known as an assignment operator. It can be said that the variable "price" is
assigned the value of 19.99. (Since the symbol "=" is reserved as the assignment operator, similar to some other
languages, Python uses "==" to represent equality.)
In a following section, the IDLE shell is employed to show how characters may be specified as variables to store
values by using assignment statements. Also see the flyer, Variables and Data Types, which appears after the next
section.
Built-in Functions
In programming, a function is a named sequence of statements that performs a computation and returns a result,
often referred to as a return value. Python has many built-in functions, ones that are available whenever Python is
run. You have already used a built-in function in Python, the print function. The print function is designed to
receive content to be displayed to the screen. This content, such as the string "Hello, World!", follows the function
name. In functions, what follows the function name is referred to as the argument. Stated another way, it is said
that the string "Hello, World" is the argument passed to the function print.
Unlike the print function, other Python function calls (anytime a function is used in program) tend to follow the
format below, one where the function name is followed by the argument encased in parentheses.*
Typical format of a function call
functionName(argument)
As you will see in the next section, the built-in type function may be used to learn of three basic kinds of data
types: string, integer and float. The argument passed to the type function is an object, such as a variable. Later,
you will learn how to import other functions and even create your own.
* In Python 3.x, the print function also uses parentheses to encase the argument: print("Hello, World!").
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
9
Variables and Data Types – An Overview
A variable is a single letter (a character) or groups of characters (such as a
word) specified by the programmer. This is a way to easily refer to a certain
piece of information. For instance, it is easier and more meaningful for a
programmer to refer to the cost of something with the variable price rather than
the ever-changing actual value of 19.99, 22.99, 23.99, etc.
Variables hold values. The variable price could be used to hold the
value 19.99. Another variable could be name used to hold the value of the
string of alphabetical characters that make up a person’s first name, such
as "Biff". Values vary by data type. Three common data types in
Python are: string, integer and float.
The information that
needs to be stored
A person’s name
A person’s age
The price of something
The variable
name specified
The value assigned
to the variable
The data type of that
value
name
age
price
"Bob"
10
19.99
String (text)
Integer (whole numbers)
Float (decimal numbers)
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
10
Using the IDLE Shell to Learn About Variables and Data Types
If one would like to learn how to program, it is highly advised to print this document (if possible, in color) or have it
open side-by-side the Python IDLE and actually perform the examples in Python on a computer as one progresses
through this document. It makes a significant difference in understanding, and is what is asked of the student in the
computer laboratory.
Type the following in the IDLE to see how variables may be created, referenced and have its data type identified.
IDLE 1.1.1
>>> name = "Biff"
>>> print name
Biff
>>> type(name)
<type 'str'>
>>> age = 11
>>> type(age)
<type 'int'>
>>> price = 19.99
>>> type(price)
<type 'float'>
Here is the same information with comments.
IDLE 1.1.1
>>> name = "Biff"
>>> print name
Biff
>>> type(name)
<type 'str'>
>>> age = 11
>>> type(age)
<type 'int'>
#
#
#
#
'name' is a VARIABLE created by
The '=' symbol is an ASSIGNMENT
It is said, the VARIABLE "name"
This single line of code may be
the programmer.
OPERATOR.
is ASSIGNED the VALUE of "Biff".
referred to as an ASSIGNMENT STATEMENT.
# Here the variable is referenced, and the VALUE is RETURNED.
#
#
#
#
This is a FUNCTION CALL.
'type' is a built-in FUNCTION, the ARGUMENT passed to it is an OBJECT.
In this case, the object is the variable name.
The type function returns the data type of the variable--in this case, STRING.
# The variable 'age' is assigned the value of 11.
# The data type INTEGER is returned, which is for whole numbers.
>>> price = 19.99
>>> type(price)
<type 'float'>
# The data type FLOAT is for decimal numbers.
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
11
How Python Handles Basic Math
Math operators in Python include the symbols below.
+
**
Addition
Subtraction
Exponentiation
*
/
%
Multiplication
Division (integer or float)
Modulo division (remainder)
Again use the IDLE to see examples of mathematics in Python. Particular attention should be paid to how Python
handles different types of division problems.
>>>
4
>>>
-6
>>>
10
>>>
7
>>>
7.5
>>>
1
>>>
0
>>>
2
>>>
25
>>>
8
2 + 2
Integer, modulo (or modulus) and regular division in Python 2.x
3-9
Integer division:
5 * 2
15 / 2
15.0 / 2
15 / 2
returns 7
Modulo division:
15 % 2
returns 1
Float division:
15.0 / 2
returns 7.5
15 % 2
quotient
14 % 2
divisor
17 % 5
remainder
dividend
5**2
2**3
Here is that same code with clarifying comments.
>>>
4
>>>
-6
>>>
10
>>>
7
2 + 2
# Enter this math problem and it will return the answer.
3-9
# Spaces are optional.
5 * 2
# The multiplication symbol is the asterisk.
15 / 2
# When both the DIVIDEND and DIVISOR are INTEGERS
# then what is returned the WHOLE NUMBER QUOTIENT
# WITHOUT the REMAINDER.
>>> 15.0 / 2
7.5
# If the dividend is of float data type, then
# the answer returned is the exact float answer.
# Note: simply adding the '.0' to the '15' makes it a float.
>>>
1
>>>
0
>>>
2
>>>
25
>>>
8
# To find the REMAINDER of an integer division problem,
# use the MODULO (%) OPERATOR.
15 % 2
14 % 2
17 % 5
5**2
# The representation for EXPONENTIATION is two asterisks.
2**3
Comparison operators in Python include the symbols below.
==
>
>=
Equal to
Greater than
Greater than or equal to
!= Not equal to
< Less than
<= Less than or equal to
Python will respond to comparison statements by returning the integer 1 (one) as true and 0 (zero) as false.
>>> 15 == 3 * 5
1
>>> 15 == 3 * 4
0
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
12
Please view the video below for more information regarding Python and basic mathematics.
How Python Handles Basic Math - 3:07 (simpleMath.swf)
http://staffweb.psdschools.org/sdurkin/pythonflicks/simpleMath.swf
As you can see, the Python IDLE could serve as a handy calculator for homework, and unlike a typical hand-held
calculator the shell session will allow you scroll back to view earlier calculations. Try typing in 2**10000, which is
210000. Can your average hand-held calculator do that? 
Computer Science and 6th Grade Mathematics Standards
Many aspects of introductory computer science may be explored in the context of K-12 mathematics standards.
Colorado Math Standards http://www.cde.state.co.us/cdeassess/UAS/AdoptedAcademicStandards/Math_Standards_2010.pdf
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
13
Glossary
argument: A value provided to a function when the function is called.
assignment: A statement that assigns a value to a variable.
assignment operator: The "=" symbol, which allows a value to be assigned to a variable.
built-in function: Functions which come ready to use with Python, such as print and raw_input.
comparison operators: The symbols used in Python for mathematical comparison. These equals (==), not equals
(!=), less than (<), greater than (>), less than or equal (<=), and greater than or equal (>=).
data type (or just type): A category of values. The types addressed so far are integers (type int), floating-poing
numbers (type float) and strings (type str).
dividend: In the expression a/b = c, a is the dividend.
divisor: In the expression a/b = c, b is the divisor.
expression: A combination of variables, operators and values that represents a single result value.
float: A data type that represents numbers with fractional parts.
function: A named sequence of statements that performs a computation.
function call: A statement that executes a function. It consists of a function name followed by an argument list
inside parentheses.
integer: A data type that represents whole numbers.
modulo operator: An operator, denoted with a percent sign (%), which works on integers and yields the remainder
when one number is divided by another.
operand: One of the values on which an operator operates.
operator: A special symbol that represents a simple computation such as addition or multiplication. Operators in
Python include -,+,/,* and %.
quotient: In the expression a/b = c, c is the quotient.
remainder:
return value: The result of a function.
statement: A section of code that represents a command or action.
string: A data type that represents sequences of characters.
user-defined: Something created by the programmer, such as a variable name used in a program.
value: One of the basic units of data, such as a number or string, that a program manipulates.
variable: A user-defined name that refers to a value.
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
14
Simple Applications
The Halt! Who Goes There? Program (halt.py)
The first simple program, halt.py, will have the user enter her or his name and age, and the computer program will
provide responses based on that input. For fans of Monty Python, think of the bridge keeper scene in Holy Grail.
Some of the concepts in this program include: sending prompts to the user and receiving keyboard input using the
built-in raw_input function, type coercion, concatenate operator (+), conditional statements: if statement and if-else
statement, indentation, blocks of code, modulo division, equality and inequality.
The concepts listed above are described in the documentation of the code for this program provided a few sections
later in this document. However, the following sections involve a few concepts to consider prior to tackling the
program.
The raw_input Function
The built-in raw_input function is a way Python can accept input from the keyboard during a program. The object
passed to this function is a string that serves as the prompt to the user for the input. For instance, to store a user's
last name into a variable, the code below could be used in the Python shell.
>>> lastName = raw_input("Please enter your last name: ")
Please enter your last name: Biff
>>> print lastName
Biff
>>>
Below is the basic format of a raw_input function used to store keyboard input into a variable.
variableName = raw_input(prompt)
Type Coercion
All information received by a raw_input statement is defaulted to string data type. This is fine when you are
taking in a person's name. However, if you ever need to take in someone's age, for example, the data should be
converted from a string to an integer. A person's age is an integer, and this is probably how you would want that
value stored in the variable. This would be particularly important if you ever planned on conducting mathematical
calculations with this variable.
This can be done with a procedure known as type coercion, where as or after the data is received from the user it is
converted from one data type to another. Type coercion is also known as type casting.
Try the following in the shell, but do not enter the comments.
>>> age = raw_input("How old are you? ")
# raw_input defaults to string type
How old are you? 11
>>> print age
11
>>> type(age)
<type 'str'>
# The type string is confirmed.
>>> age * 2
# The value in the variable age behaves as a string.
'1111'
>>> age = int(age) # TYPE COERCION: age is re-assigned to integer type using the int function.
>>> type(age)
<type 'int'>
# The type integer is confirmed.
>>> age * 2
# Now, the value in the variable age behaves as an integer.
22
You will see an example of type coercion in the upcoming halt.py program.
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
15
Conditional Statements and Indentation (White-space)
It is possible to have a single line of code or a block of code (a group or set of lines of code) execute only under
certain circumstances. This is done with a conditional statement. Conditional statements are able to direct the
flow of execution in a program based on whether or not they are true or false at any given time.
True and False are special data types in Python called boolean. True is represented with the integer 1 (one) and
False is represented by 0 (zero).
Below a comparison operator is used in the shell to display True and False expressions.
>> 5 == 4 + 1
1
>>> 7 == 4 + 2
0
In Python, if a conditional statement is true, then the code below it (indented four spaces) will execute. If the
conditional statement is false, then the indented code below it will not execute.
For instance, say one wanted a banking program to ask a user to open a savings account when the checking account
balance goes over $1,000 dollars. (This is assuming the user does not already have a savings account.) The
conditional statement could look like the code below.
if checkingBalance > 1000:
openSavings = raw_input("Would you like to open a savings account? ")
The first line of code above is a conditional statement, specifically an if statement. Notice that A CONDITIONAL
STATEMENT ENDS IN A COLON (:)! This is important because after the programmer types in the Enter
key after the colon, the Python IDLE will automatically indent the code below it four spaces.
The indented code will only execute if the conditional statement is true. If the conditional statement is false, then
the indented code is skipped and the Python interpreter looks below the indented code for the next line of code that
is not indented. This indentation is extremely important in Python as it controls the flow of execution. This is
sometimes known in programming as white-space, and in Python this white space takes the place of "{}" used in so
many other languages, such as Java, C++, and others.
Try typing the three lines of code below in the shell.
>>> students = 40
>>> if students > 38:
print "We need another teacher!"
To see the output, press the Enter key twice after completing the print statement.
We need another teacher!
>>>
Be very careful with indentations in Python, being off just by one space may cause an error in the program. Try
to ALWAYS remember the colon at the end of any conditional statement. If you do remember the colon, you
will be fine as Python will then take care of the indentation for you. Just so you know, Python indents four white
spaces per level of indentation. The tab key in Python also indents four spaces.
Indentation is a concept some students can struggle with in the beginning so be on the lookout for this when helping
others parse code.
The following is from the Help section in IDLE. Automatic indentation: After a block-opening statement,
the next line is indented by 4 spaces (in the Python Shell window by one tab). After certain
keywords (break, return etc.) the next line is dedented. In leading indentation, Backspace
deletes up to 4 spaces, if they are there. Tab inserts 1-4 spaces (in the Python Shell window
one tab). See also the indent/dedent region commands in the edit menu.
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
16
Code for the halt.py Program
Below is the code for the halt.py program. This initial program is important in that addresses many basic concepts of computer programming. Open a new
script window in Python. Save the file as halt.py.
The code below is heavily documented. A teacher who may be a novice programmer may find this a little confusing at first, but just know that the red text is just
comments. Below there are only four lines of code, and that is all the students need to see and enter. It is not necessary for you to type in the comments, but do
read them here! At the end of this program, the code appears again undocumented, in just 15 lines. You may elect to view that code first to see how it all goes
together, and then come back here and see each line explained via comments.
# halt.py
# Biff B.
# 02.12.2008
Python 2.2
# Concepts in this program include: input, output, assignment operator, variables,
#
conditional statements: if and if-else, modulo division, and concatenate operator
# taking input and producing output
name = raw_input("Halt!
# Encase strings in either quotation marks or apostrophes, just be consistent.
# The built-in raw_input function accepts keyboard input and this information
# is stored in the VARIABLE, which in this case is the word "name".
# The argument passed in this function is a prompt in the form of a string.
# The COMMA allows the print output to continue on the same line.
# If the comma was not there, the program would return an error.
Who goes there? ")
print "You may pass", name
# Save the above and run.
# The program should ask for a name, accept it, and return it.
##############################################################
## Although, there is a punctuation problem with the output.
print "You may pass,", name, "."
# Here is the fix.
print "You may pass,", name + "."
No period.
One could add a period the following way:
# However, there is still an output problem when the program is run.
# The period has a space in front of it as a comma imposes a space before and after itself.
# When the '+' sign is used with two strings it "adds" (concatenates) the two strings.
# Therefore, in such cases, the '+' sign is said to be a CONCATENATE operator.
# Save the above and run until working properly.
The program continues in the next section.
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
17
##############################################################
# Practice taking input and producing output
# Now have the "bridge keeper" ask the user her or his age, and say back to the user, "It must be nice to
# be xx years old." - the xx being 11 or whatever the user types in
# Students should know/learn that a variable is needed to store the input, and that a raw_input function could be used
# to take in the information. A logical variable name would be "age".
# Students should have an opportunity to attempt a solution without being first shown.
age = raw_input("What is your age, " + name + "? ")
# Note how the name is incorporated into the prompt.
age = int(age)
# Coerce the variable "age" to integer (int) data type.
print "It must be nice to be",age,"years old,",name+"."
# Note how superfluous spaces may be removed.
# Save the above and run until working properly.
##############################################################
# Conditional statements:
#
#
#
#
#
if
if-else
Now ask the students to report to the user if her or his age is an even or odd integer.
Ask the students how one would normally determine this - express it in mathematical terms using English.
An even number (integer) is one that divides evenly by two (with no remainder).
Therefore, modulo division by two of the age should reveal if the number is even or odd. If there is no remainder,
then it is even.
# Show the students:
#
#
#
#
#
#
#
else:
#
print "Your age is an odd number,", name + "."
if age % 2 == 0:
print name + ", your age is an even number."
The double equals signs (==) in Python represents "EQUALS TO".
This is a CONDITIONAL STATEMENT. ALL CONDITIONAL STATEMENTS END WITH A COLON :
INDENTATION will automatically occur due to the colon above.
The indentation is how Python keeps track of what to do in conditional statements.
As long as the conditional statement is TRUE, the INDENTED BLOCK OF CODE below
the conditional statement will be EXECUTED. If not, the entire indented block is
merely skipped.
An ELSE statement may be added to the IF statement to express odd numbers.
# Note how ELSE is lined up with IF, ends in a colon and has indented code below.
# Save and test with both odd and even numbers.
##############################################################
# Optional twists:
if age == 11:
print "Your age is the same as the author of this program when it was created."
if age > 50:
print "Gee, there weren't even fifty stars on the U.S. flag when you were born."
if age != 11:
# The symbols != represent INEQUALITY.
print "You are not the same age as the author when this program was created."
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
18
Below is the same halt.py program with less comments.
# halt.py
# Biff B.
# 02.12.2008
Python 2.2
name = raw_input("Halt! Who goes there? ")
print "You may pass,", name + "."
age = raw_input("What is your age " + name + "? ")
age = int(age)
print "It must be nice to be", age, "years old,", name + "."
if age % 2 == 0:
print name + ", your age is an even number."
else:
print "Your age is an odd number,", name + "."
if age == 11:
print "Your age is the same as the author of this program when it was created."
if age > 50:
print "Gee, there weren't even fifty stars on the U.S. flag when you were born."
if age != 11:
print "You are not the same age as the author when this program was created."
Glossary
raw_input: A built-in function which allows a program to receive keyboard input.
type casting/coercion: The act of changing data from one type to another.
indentation: The process of arranging code in levels of indenting to control the flow of execution.
indent: To go in one level of indentation, or four spaces towards the right margin.
dedent: To go out one level of indentation, or four spaces towards the left margin.
body: The sequence of statements within a compound statement.
Boolean expression: An expression whose value is either True or False.
branch: One of the alternative sequences of statements in a conditional statement.
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
19
concatenate: To join two string operands end-to-end.
condition: The Boolean expression in a conditional statement that determines which branch is executed.
conditional statement: A statement that controls the flow of execution depending on some condition.
comparison operator: One of the operators that compares its operands: ==, !=, >, <, >=, and <=.
compound statement: A statement that consists of a header and a body. The header ends with a
colon (:). The body is indented relative to the header.
flow of execution: The order in which statements are executed during a program run.
if statement: A conditional statement that only executes if the Boolean expression is True. If it is False, the body of the code is not executed.
logical operator: One of the operators that combines boolean expressions: and, or, and not.
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
20
Area and Perimeter Program (rectangle.py)
Say a fence and turf company often needs to know the area and perimeter of a rectangular field. Applying what you now know how to do in Python, create a program
called rectangle.py, which can take in the length and width of any rectangle and return the area and perimeter of that shape. Below is the code for such a program.
However, you may decide to challenge yourself by first attempting the program on your own.
#
#
#
#
#
#
#
#
#
#
#
#
rectangle.py
02.02.2009
Biff B.
Python 2.2.3
SPECIFICATIONS:
input:
output:
processing:
storage:
The program takes in length and width of any rectangle and returns the area and perimeter of that shape.
length and width of any rectangle
the area and perimeter of that shape
formula for area: length * width
with answer expressed in units SQUARED
formula(s) for perimeter: length * 2 + width * 2
with answer expressed in units
(length * 2) + (width * 2) parentheses clarify, but not needed (PEMDAS)
length+length+width+width
alternative formula
none, just display results to screen
# welcome/instructions
print """
********************************************************
Welcome to the Area and Perimeter Finder for Rectangles
********************************************************
# Three quotation marks may be used to encase multiple lines of output.
Enter the length and width of any rectangle and you will
be returned the area and perimeter.
********************************************************
"""
# Three quotation marks denote the end of the multi-line output.
# input
length = raw_input("Enter the length of rectangle: ")
width = raw_input("Enter the width of rectangle: ")
# assign a data type (float may used to handle both integers and decimals)
length = float(length)
width = float(width)
# processing
area = length * width
perimeter = length+length+width+width
# output
print "A rectangle", length, "by", str(width)+":"
print "\nArea:", area, "units squared"
print "Perimeter:", perimeter, "units"
Computer Science for Everyone – Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
21
The High/Low Guessing Game (guess.py)
In this program, a random number from 1 to 100 will be generated. The player of the game will continually try to
guess what that "secret number" is until it is identified. The program will respond by informing the user if each
guess is too low, too high or correct. At the end of the game, the user is also to be informed of how many guesses it
took to identify the number.
The while Loop
In order to make it easier for a computer program to repeatedly do something, such as ask the user what the secret
number is and provide feedback each time, a programmer long ago invented what is commonly referred to as a loop.
A loop in computer science is a structure that allows for something to repeat. Attaching a loop to a condition is a
very useful programming concept. For the guessing game, it would be helpful to create a loop that repeats as long as
any of the user's guesses do not equal the secret number. In Python, a while loop may be used to achieve this effect.
Before creating the guessing game, open the Python shell in the IDLE and type the following in to see how typical
while loops behave. Do not enter the comments to the right of each line. They are just there to contribute to the
reader's ongoing education in computer science. After the last line of x = x + 1 press the Enter key twice to see the
output.
>>> x = 1
>>> while x < 10:
print x,
x = x + 1
#
#
#
#
#
#
#
#
#
#
#
Assign the variable x the integer value of one.
As long as x is less than 10, execute the indented block of code.
The comma at the end keeps all output on one line.
Each time through the loop x will be INCREMENTED by one.
This last line of the indented code above is very important.
The variable x is increased by one each ITERATION.
Iteration is a word used in computer science, meaning each
time through a loop.
Leave this last line of code out and you would have an INFINITE LOOP.
See the video for an example of an infinite loop.
The output of the code appears below.
1 2 3 4 5 6 7 8 9
Try this loop in the Python shell.
>>> x = 10
>>> while x > 0:
print x
x = x - 1
#
#
#
#
INITIALIZE the variable x to the integer value of ten.
This loop will TERMINATE whenever x becomes zero or less.
Without the comma, the output of each iteration appears on a new line.
Instead of incrementing the variable, here it is DECREMENTED by one.
10
9
8
7
6
5
4
3
2
1
>>>
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
22
Creating the High/Low Guessing Game
"There is more than one way to do it" (TIMTOWTDI) is a common phrase in programming. The code below is just
one approach of many that could generate this type of guessing game. Other approaches could be far more elegant,
such as ones which contain fewer lines of code and/or offer a more efficient approach. The program development of
the guessing game is arranged in phases.
Developing the Initial Program
As stated before, a while loop may be used to compare the player's guesses to the secret number. As long as a guess
is not the secret number, the game continues. However, when the user guesses correctly the while loop should
terminate.
A program development technique called pseudocode involves writing out in English what you want a program to
do before you actually begin to code it. Once the pseudocode is written, then it is only a matter of translating it to
the Python language. This approach allows the programmer to first focus on the programming concepts and flow of
the program, and then later focus on the actual code involved.
Below is an example of pseudocode for the basic parts of guessing game.
Generate a secret random number between 1 and 100
Start the program by purposely setting the value for the user's guess to be incorrect
This way, the loop below will execute the first time
While the player's guess does not equal secret number
Ask the user for a guess, assign the data type to integer
If the guess is greater than the secret number,
inform the player the guess is too high
If the guess is less than the secret number,
inform the player the guess is too low
The above while loop will terminate when the guess is correct
At that point, the player should be informed that the secret number has been identified
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
23
The Initial Script
Save a new script file as guess.py. It is not necessary to show or have the students write the comments, but do
explain to them the concepts associated with each line of code.
#
#
#
#
guess.py
02.02.2009
Biff B.
Python 2.2.3
# High/Low Guessing Game
# The player tries to guess a secret number between 1 and 100.
# Every guess the player makes receives feedback of either too high, too low or correct.
secret = 76
# Initially, have the students supply the secret
# number. Programmer's do this so they *know*
# the answer while testing the program during development.
guess = -99
# This sets the guess to be wrong so the while
# loop will initially execute. Why –99? Why not? It works! :)
while guess != secret:
# != means NOT equal
guess = raw_input("What is the secret number?")
guess = int(guess)
# Set the data type to integer.
if guess > secret:
print "The number", guess, "is too high."
if guess < secret:
print "The number", guess, "is too low."
print "Yes, the secret number was:", secret
# Note that this line is DEDENTED back to the left
# and will execute only when the while loop above it
# terminates. Pressing the Backspace key at blocked code will dedent the cursor four spaces,
# or a single indent.
Students should test and validate the program by putting in a number they know is too low, then too high, and then
just right.
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
24
Generating a Random Number
Now that the program is working have Python generate the "secret" random number. This may be done by
importing the random module and using the randrange function inside it to create a random number between 1 and
100. Once this is done, even the programmer will be able to play the game without already knowing what the
random number is. (Of course, a programmer could insert a print statement after the secret number is generated in
order to see what that number is as she or he continues to test the game.)
Also please note how the line of code containing the raw_input function has been altered so as to make the line
below it no longer necessary.*
# guess.py
import random
# This statement imports a module called random. This and other modules were
# installed with Python, and more may also be added by the programmer.
# MODULES often contain groups of code, called FUNCTIONS, which are designed to perform
# commonly-needed actions. For instance, the random module contains a RANDRANGE function,
# which generates a random number between a specified range of numbers.
# Before a program may make use of any function inside a module, the module must
# first be imported, as it is here in the single line of code above.
############################################################################################
## secret = 67 This "old" code is commented out/or replace "67" with the function call below.
secret = random.randrange(1,101)
# This generates a random number between 1 and 100 inclusive.
# randrange is a function inside the random module.
# The function randrange takes two arguments, which are separated by a comma.
# Note how the second argument must actually be one higher than the range needed.
# If the argument passed was (1,100), only numbers between 1 and 99 would be created.
guess = -99
while guess != secret:
guess = int(raw_input("What is the secret number?")) # * Note how this line has been altered
##guess = int(guess)
<-- so that this line is no longer needed.
if guess > secret:
print "The number", guess, "is too high."
if guess < secret:
print "The number", guess, "is too low."
print "Yes, the secret number was:", secret
Save and test the program, a game that you now as a programmer can play yourself.
* This style is more in line with how things are done in Python 3.x. For those interested, there is more information below.
The only difference is Python 3.x uses the word input instead of raw_input. The keyboard input in each case defaults to
string data type. Python 3.x only uses the input function, which makes for the kind of format seen in this line of code – one
where the entire keyboard input function exists within a type coercion function, in this case, int.
Python 2.x happens to use two keyboard input functions: input and raw_input. However, opposite to Python 3.x, Python
2.x uses the term input to take in integer and float data types. As you have seen, the Python 2.x raw_input function
defaults data to string type.
To reduce confusion (and mimic how things are done in Python 3.x), only raw_input has been used so far in this document
since it is that function that serves the same purpose as the input function in Python 3.x. However, the input function in 2.x
may be used in other 2.x programs referenced later in this document.
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
25
Adding a Counter
Now add a counter, a variable to keep track of how many times something happens, to the program so that it will
report how many tries the player needed to identify the secret number. This involves creating a variable to keep
track of the number of attempts and incrementing it by one every time the user guesses. After the while loop
terminates, the variable may then be used to report how many tries it took the player to guess the secret word.
Observe the new code along with the comments below to alter your existing program so as to inform the player how
many attempts were needed to identify the secret number.
# guess.py
import random
secret = random.randrange(1,101)
guess = -99
attempts = 0
#1. The variable is initialized with the value zero.
#
Of course, any appropriate variable name would do: count,tries,guesses,etc.
while guess != secret:
guess = int(raw_input("What is the secret number?"))
attempts += 1
#2. The variable is incremented by one each iteration.
#### Notice the shorthand code compared to the longer: attempts = attempts + 1
if guess > secret:
print "The number", guess, "is too high."
if guess < secret:
print "The number", guess, "is too low."
print "Yes, the secret number was:", secret
print "It took you this many tries:", attempts
#3. The counter variable is used to report out.
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
26
Adding Feedback
Add feedback to the player during and/or after the game. See the comments to the right that is along side the added
code.
# guess.py
import random
secret = random.randrange(1,101)
guess = -99
attempts = 0
while guess != secret:
if attempts == 8:
print "Eight tries so far. Keep trying!"
if attempts == 9:
hint = raw_input("Do you want a hint? y/n ")
if hint == "y":
if secret > 1:
print "The secret number is less than:", secret + 1
else:
print "The secret number is less than: 2"
guess = int(raw_input("What is the secret number?"))
attempts += 1
if guess > secret:
print "The number", guess, "is too high."
if guess < secret:
print "The number", guess, "is too low."
print "Yes, the secret number was:", secret
print "It took you this many tries:", attempts
if attempts < 6:
print "Five or less tries reflect some skill and/or luck!"
# Help out the player
# when it may be needed.
#
#
#
#
#
#
#
# Provide a compliment
# when appropriate.
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
27
Putting the Game in a Loop
Now that the game works, the code may be indented and placed in a while loop.
Below are the documentation and code for placing the game in a loop so a user may play the game as many times as
desired.
import random
#1. Highlight all the code except for the first line (above) that imports the random module,
#
and then press the Tab key. This will indent the highlighted code one level to the right,
#
as it now appears in this code here.
while 1: #2. All the way to the left, add this while loop ABOVE the indented block of code.
#
The '1' means TRUE. Therefore, the loop executes forever, unless it is broken (#5).
#3. Add a prompt to see if the user would like to play the game.
play = raw_input("Would you like to play the High/Low Guessing Game? y/n ")
if play == "n":
#4. This condition allows the user to exit the program.
print "Goodbye!"
break
#5. The keyword 'break' terminates the outer 'while 1' loop.
#
The Python interpreter then skips down to the next line
#
of code at the same level (#6) of the terminated 'while 1' loop.
secret = random.randrange(1,101)
guess = -99
attempts = 0
while guess != secret:
if attempts == 8:
print "Eight tries so far. Keep trying!"
if attempts == 9:
hint = raw_input("Do you want a hint? y/n ")
if hint == "y":
if secret > 1:
print "The secret number is less than:", secret + 1
else:
print "The secret number is less than: 2"
guess = int(raw_input("What is the secret number?"))
attempts += 1
if guess > secret:
print "The number", guess, "is too high."
if guess < secret:
print "The number", guess, "is too low."
print "Yes, the secret number was:", secret
print "It took you this many tries:", attempts
if attempts < 6:
print "Five or less tries reflect some skill and/or luck!"
print "End of program."
#6. Here is where the program skips to once the outer loop is broken.
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
28
How Fair is the Random Number Generator?
The for Loop
Another loop available in Python is the for loop. You will use it to generate a very large amount of random
numbers, and analyze how often certain ranges of numbers appear. This may provide some insight as to how
equitable the distribution of random numbers is across the range.
First, enter the code examples below (without the comments) in the shell to see how a for loop operates.
>>> for x in range(1,10):
print x,
#
#
#
#
The first argument in the built-in range function is the
beginning of the range, and the second argument is the end
of the range, but note what the output goes to – nine!
Press Enter twice after the comma to see the output below in blue.
1 2 3 4 5 6 7 8 9
As you may have noticed, as soon as you type in the opening bracket for a function call a small box will pop up
below the current line giving you a "tip" with regards to the arguments that are expected. The tip continues to
display until the closing bracket is entered.
Now press the Alt-p keys. This will repeat the previous code. Edit the second argument to be 11. Since the value
of the second argument is exclusive, this will get the loop to count to ten. Place the cursor back to just after the
comma and press the Enter key twice to see the output of this adjusted code.
>>> for x in range(1,11):
print x,
# To count to ten, the second argument must be one more.
1 2 3 4 5 6 7 8 9 10
Again, press Alt-p and remove the first argument. As you observe, when left out it is assumed to be 0, which does
yield 11 iterations.
>>> for x in range(11):
print x,
0 1 2 3 4 5 6 7 8 9 10
Lastly, use a for loop to generate 25 random numbers between 1 and 100.
>>> import random
>>> for x in range(11):
print random.randrange(1,101),
76 13 62 42 46 79 28 15 91 47 58 18 44 46 33 29 13 43 24 53 26 64 18 64 67 30
Of course, for loops can do other things, but what we have seen is enough to get started using a for loop to help
with the analysis of the fairness of the randrange function in the random module.
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
29
Computer Simulation
How could one assess the randomness of the randrange function? Say you had Python create a million random
numbers and each one was printed onto a paper 3"x5" note card. You were then asked to take each card and place it
into one of four large bins: the first bin is to be used for numbers 1 to 25, the second is for numbers 26 through 50,
the third bin for 51 to 75 and the fourth bin for 76 to 100. If the random number generator was fair, after every card
was processed would not each bin contain roughly an equal amount of random numbers, around a quarter of a
million? Obviously, it would be impractical to physically perform such an analysis as at a pace of one second per
card it would take a person over ten days non-stop, but with a computer it is very quick and easy to simulate.
Use Python to create a million random numbers, and as each number is created increment one of four counters, each
designed to represent one-fourth of the range of possible numbers.
Before going on in this document, please consider trying to write some or all of the pseudocode for this program and
even parts of the program itself. You may surprise yourself, and will enhance your ability to think like a computer
scientist.
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
30
Open a new script in Python and save the file as randomAnalysis.py.
Below is some pseudocode.
Import the random function
Create four counters, or buckets, if you will: one each for 1-25, 26-50, 51-75, and 76-100
Ask how many numbers should be generated
Use a for loop to generate random numbers
During each iteration, increment the appropriate bucket
At the end, report the amount of each bucket
# randomAnalysis.py
import random
bucket1
bucket2
bucket3
bucket4
=
=
=
=
0
0
0
0
#
#
#
#
for numbers 1-25
26-50
51-75
76-100
times = int(raw_input("How many random numbers should be generated?"))
for x in range(1,times+1):
x = random.randrange(1,101) # The variable x is used to represent the random number.
if x <= 25:
bucket1 += 1
elif 26 <= x <= 50:
bucket2 += 1
elif 50 < x < 76:
bucket3 += 1
else:
bucket4 += 1
print
print
print
print
"Bucket
"Bucket
"Bucket
"Bucket
1:",
2:",
3:",
4:",
#
#
#
#
#
These are elif (else-if) statements, which allows multiple conditions
to be considered.
<-- Also notice how x is represented to be within a range.
Here, x is both greater than 50 AND less than 76 (or 51-75).
An else statement is required as the final condition.
bucket1
bucket2
bucket3
bucket4
print "\nTotal:", bucket1+bucket2+bucket3+bucket4
# Just in case something fishy is going on. :)
Save the script and run the program.
Below is sample output based on a generation of one million random numbers. As you can see, each bucket is
roughly the same. So one could assume the random number generator is fair enough for friendly games. The kind
of random numbers generated by Python are referred to as pseudorandom numbers.
Bucket
Bucket
Bucket
Bucket
1:
2:
3:
4:
249794
249860
250597
249749
Total: 1000000
The students should see that generally the buckets come out even.
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
31
Glossary
loop: To repeat something over and over.
while loop: A loop that repeats as long as a certain condition is true.
increment: To increase.
iteration: Each time through a loop.
decrement: To decrease.
terminate: To end or break out of a loop.
initialize: To create a variable and set it's value.
pseudocode: A description of how a program works using English, or a combination of code and English.
module: A file that contains functions that may be used when imported in a program.
counter: A variable used to keep track of how many times something happens.
for loop: A loop that runs for a specific number of times.
exclusive: This means "not included" when talking about a range of numbers. When someone says, "1 through 10
exclusive," that person means the numbers 2, 3, 4, 5, 6, 7, 8 and 9, but not 1 or 10.
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
32
The Least Common Multiple (LCM) Finder (lcm.py)
The input Function
For the first time in this document, the input function in Python 2.x will be used. The input function in Python 2.x
takes in float and integer data. Python 3.x does not have an input function, but only a raw_input function. The input
function also allows multiple variable assignments in one statement. Please read all the comments below as you
create this program.
Students are to make a program that can take in any two integers and output the least common multiple.
#
#
#
#
lcm.py
02.02.2009
input is two integers
output is the least common multiple
# Review with the students what the lcm of two integers is and the brute force algorithm of
# simply increasing the smaller integer by its multiple and repeating that process
# until the two are equal.
#
#
#
#
#
#
Walk through the algorithm with the students. Find the LCM of 6 and 8.
x = 6
y = 8
6
8 Which one is smaller? x Then increment it by its original multiple (6 becomes 12).
12
16 Which one is smaller now (12 or 8)? y Then increment it by its original multiple.
18
24 Which one is smaller now? x Then increment it by its original multiple.
24 <-- ^^ -- The lcm is identified when x and y are equal.
# This algorithm will work with any two positive integers, and very quickly with a computer.
#
#
#
#
#
#
#
#
Pseudocode:
Take in two integers, x and y.
Create two more variables, multx and multy, which will be used as the original multiple values.
Use a while loop to compare x and y.
Each iteration should increment the smaller variable by its original multiple.
The loop terminates when x and y are equal, identifying the lcm.
x,y = input("Enter two integers separated by a comma (for ex. 6,8): ")
##NOTE: The line of code above is the first in this document to use the INPUT function in Python
2.x. The input function may be used to take in float and integer data. Also, notice how in the
statement above multiple variables may be assigned when a comma separates the keyboard input.
multx = x
multy = y
# These two variables are created to preserve the original multiple values.
# Some students may need extra time and help in understanding when and how to create
# variables in order to solve problems.
print "x\ty"
# The escape character (\) followed by the letter "t" inserts a tab.
while x != y:
# Once x and y are equal the lcm is identified, and the loop terminates.
print x, "\t", y
# This will help one see the effects of the loop.
# This is an example of SCAFFOLDING, which is code that may be removed
# after the programmer uses it to confirm the program is working as
# desired and/or to help with the debugging process.
if x < y:
x += multx
# Increase the smaller integer by its multiple.
else:
y += multy
lcm = x
# y could have also been used as both are equal at this point.
print x, "\t", y
print "The LCM of", multx, "and", multy, "is", str(lcm) + "."
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
33
Below is the same code with less documentation.
#
#
#
#
lcm.py
02.02.2009
input is two integers
output is the least common multiple
x,y = input("Enter two integers separated by a comma (for ex. 6,8): ")
multx = x
multy = y
print "x\ty"
while x != y:
print x, "\t", y
if x < y:
x += multx
else:
y += multy
lcm = x
print x, "\t", y
print "The LCM of", multx, "and", multy, "is", str(lcm) + "."
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
34
The Factors Finder Program (factorsFinder.py)
Create a Factor Finder program that can take in any integer and return all the factors of that number. Include a
counter so you may answer questions such as, how many factors are there in a million?
Pseudocode:
Take in any integer
Use a loop to divide that integer by every number from one to the integer itself
During each iteration, check to see if there is a remainder to the integer division
If there is no remainder, then that divisor is a factor of the integer
Print/display the factor, increment a counter
Use the counter to report how many factors were found
# factorsFinder.py
fcount = 0
integer = int(raw_input("Enter any integer and be returned the factors of that number: "))
print "The factors of", integer, "are:",
for divisor in range(1,integer+1): # Test every divisor from 1 to the integer itself.
if integer % divisor == 0:
# Modulo division: if there is no remainder, then that
factor = divisor
# divisor is a factor of the integer.
print factor
fcount += 1
print "\nThe integer", integer, "has", fcount, "factors." # '\n' creates a new line of output
# The '\' backslash is known as an escape character.
# An escape character indicates that the character after it has special
# meaning. In this case, the 'n' stands for 'new line.'
Save the script and test it out. How many factors does the integer one million have? (When you enter a single
number in Python, do NOT use comma separators. For instance, to enter a million type "1000000" instead of
"1,000,000".) Can you add code to this program that would tell the user if the integer entered was prime or not?
Can you get this program to run continually until the user enters zero?
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
35
The Change Maker (changeMaker1.py/changeMaker2.py)
You are to make a program that can process information passed within a self-service retail register. The input will
be how much the total bill is and how much money the customer has inserted into the register. Your program is to
return the exact change that is needed, and indicate how many, if any, fifty-dollar bills, twenty-dollar bills, ten dollar
bills, five dollar bills, one dollar bills, quarters, dimes, nickels and pennies should be dispensed to the customer.
(The register accepts one hundred dollar bills, but does not dispense them.) The program should run continuously
until 0 is entered for the bill.
When creating a larger program sometimes it is helpful to start out small. Think about a machine that could only
handle coins, like the ones used inside Wendy's Restaurants in Fort Collins. What if the program only had to deal
with the input of the amount of change needed from 0.00 to 0.99? The program would just have to return the
appropriate coinage. Start with this smaller program in mind. Once this is accomplished, it shouldn't be much of a
leap to add the rest.
Yes, yes, the code follows, but if you haven't already, do you not think it is about time to start thinking on your
own? Thinking about problems in computer science is an inherently beneficial activity, learning to program over
time may increase one's ability to read, think and solve problems. The sense of accomplishment is great, and it is a
way of thinking that may positively influence one's overall performance in whatever fields are pursued in the future.
As you learn a programming language, you can probably handle more complex ideas over time. Of course, some
solutions do not have to be that complex. There are more elegant solutions to be sure, but as you will see the
solution shared here just uses a simple idea, over and over again.
As long as the change needed to dispense is over 0.25, wouldn't you look at counting one or more quarters out until
that is no longer the case, and then look at the next largest denomination? Think about it, and try to come up with
some pseudocode.
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
36
Creating changeMaker1.py
#changeMaker1.py
# A simple change maker for coins
# input: The amount of change needed, ranges from 0.00 to 0.99
# output: The number of quarters, dimes, nickels and pennies to be dispensed
# initialize counters for all types of coins
quarters = 0
dimes = 0
nickels = 0
pennies = 0
change = float(raw_input("How much change is needed? ")) # Coerce the input to be of float type.
print "Change to be dispensed:", change
while round(change,2)
quarters += 1
change -= 0.25
while round(change,2)
dimes += 1
change -= 0.1
while round(change,2)
nickels += 1
change -= 0.05
while round(change,2)
pennies += 1
change -= 0.01
>= 0.25: #
#
#
>= 0.1: #
#It is helpful to display the change that was requested.
The built-in round function sets change to 2 decimals places.
Increment the counter by one.
Change gets DECREMENTED 0.25 each ITERATION.
Look at other coinage in descending denomination ...
>= 0.05:
>= 0.01:
# Once the above while loops terminate, use the counters to report the dispensation of coinage.
print "Quarters:", quarters
print "Dimes:", dimes
print "Nickels:", nickels
print "Pennies:", pennies
The next section involves adding features to handle the amount of the bill, the amount of money inserted, the change
needed, and the ability to deal with currency. The video below shows the development of the entire program.
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
37
Creating changeMaker2.py
Below is an expanded version of changeMaker1.py, which includes input for the bill and money entered along with
the ability to break the change needed from 99.99 to 0.00 into fifties, twenties, tens, fives, ones, quarters, dimes,
nickels and pennies. The program also loops until the input for the bill is zero.
# changeMaker2.py
# The entire program loops until zero is entered for the amount of bill.
while 1:
# Indent all the code below and place it within a while loop.
bill = input("What is the amount of the bill? ")
if bill == 0:
break
# If the bill is entered as zero, the program should terminate.
else:
inserted = input("How much money was inserted by customer? ")
change = inserted - bill
### The above line assumes that the customer has inserted more than enough money.
print "Change needed: ", change
fifties = 0
# Additional counters for currency are added in descending order.
twenties = 0
tens = 0
fives = 0
ones = 0
quarters = 0
dimes = 0
nickels = 0
pennies = 0
while change >= 50.00:
# Again, the idea is to deal with denominations in descending order.
fifties = fifties + 1
change = change - 50.00
while change >= 20.00:
twenties = twenties + 1
change = change - 20.00
while change >= 10.00:
tens = tens + 1
change = change - 10.00
while change >= 5.00:
fives = fives + 1
change = change - 5.00
while change >= 1.00:
ones = ones + 1
change = change - 1.00
while change >= 0.25:
quarters = quarters + 1
change = round(change,2) - 0.25
while change >= 0.10:
dimes = dimes + 1
change = round(change,2) - 0.10
while change >= 0.05:
nickels = nickels + 1
change = round(change,2) - 0.05
while change >= 0.01:
pennies = pennies + 1
change = round(change,2) - 0.01
print
print
print
print
print
print
print
print
print
"Fifties:", fifties
"Twenties:", twenties
"Tens:", tens
"Fives:", fives
"Ones:", ones
"Quarters:", quarters
"Dimes:", dimes
"Nickels:", nickels
"Pennies:", pennies
print "Goodbye!"
# This message appears once the while loop is terminated.
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
38
The Greatest Common Denominator (GCD) Finder (gcd.py)
This next section involves creating a program that can return the greatest common denominator of any two
positive integers.
As far as a working algorithm goes, one way could be to find the factors of each positive integer and then compare
the contents of those two lists of factors to identify the greatest common denominator. The students have already
constructed a factors finder program and may just need a way to easily refer to that code since it will be needed
more than once in this program, but they also now need a way to compare the contents of the two lists of factors.
The next section describes how to make use of the list data type in Python, and the section after that addresses how
to wrap up the code from the Factors Finder program into a programmer-created function.
Lists
Python has a list data type that can help with the construction of the GCD program. A list is a sequence of values
(of any data type). Students will need to learn about lists in order to create the Greatest Common Denominator
program. More times than not and especially when I work with younger students, I tend to just have them jump on
the shell and have at it. However, for those who want to learn more formally about lists, please check out the 13
pages of Chapter 10 – Lists in Think Python - An Introduction to Software Design, an excellent open source
textbook by Allen Downey designed for high school students.
As usual, the comments below are not to be entered in the shell, but here to provide context for what is being done.
As you see in the video, as I teach and have the students enter the code, I would basically state and expound upon
the comments listed here.
IDLE 1.2
>>> beatles = []
>>> beatles
[]
>>> type(beatles)
<type 'list'>
#
#
#
#
#
#
#
#
#
#
Initialize a list by using square brackets "[]", a variable and
an assignment operator.
Return the value of this list.
It is an empty list, but a list!
Return the data type of the variable.
Python provides METHODS, which operate on lists.
For example, the APPEND method below adds a new ELEMENT to the end of a list.
Each "thing" in a list is called an ELEMENT (ITEM is also another commonly-used term).
Though in the examples below only strings are used, each element of a list may be of any
data type. In the GCD project, the elements in the lists will be integers.
>>> beatles.append("John") # Add an ELEMENT to the list using the APPEND method.
>>> beatles
['John']
>>> beatles.append("Paul")
# The default is that new ITEMS are added to the end of the list.
>>> beatles
['John', 'Paul']
>>> beatles = beatles + ["George"]
# Here is another way to add an item to a list.
>>> beatles
['John', 'Paul', 'George']
>>> beatles += ["Ringo"]
# Of course, here is the shortcut for the previous way.
>>> beatles
['John', 'Paul', 'George', 'Ringo'] #########################################################
>>> beatles[0]
## Lists have elements/items which are accessible via an INDEX!
'John'
## However, the indexing begins at ZERO! <<<<<<<<<<<<<<<<<<<<<<<
>>> beatles[1]
###################################^^^^#########################
'Paul'
##
>>> beatles[2]
##
'George'
#######################################################
>>> beatles[3]
## Therefore, even though Ringo is the fourth member, #
'Ringo'
## the index is 3 as indexing begins with 0.
#
>>> beatles[4]
#######################################################
Traceback (most recent call last):
## The index of 4 returns an "out of range"
File "<pyshell#16>", line 1, in ?
## error message similar to what appears here.
beatles[4]
###############################################
IndexError: list index out of range
(On paper, this shell session on lists continues on the next page.)
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
39
>>> len(beatles)
# Here, the built-in len function returns the LENGTH of the list,
4
# which is the number of elements in the list.
>>> beatles[-1]
# Note how the last item in the list may be accessed with the index –1.
'Ringo'
>>> length = len(beatles) # Here is another way to determine the last item.
>>> beatles[length-1]
'Ringo'
>>> for member in beatles:
print member
# A FOR loop may be used to TRAVERSE the elements of the list.
'John'
'Paul'
'George'
'Ringo'
>>> x = len(beatles) - 1
>>> while x >= 0:
beatles[x]
x -= 1
# Here, WHILE loop is constructed to traverse a list
# in reverse order.
'Ringo'
'George'
'Paul'
'John'
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
40
Creating and Using Your Own Functions
Recall the factorsFinder.py program you made. In the GCD program, you will need to find the factors of two
positive integers. Often, when the same operation needs to be repeated it is best to wrap the process, or algorithm,
into a block of code that can be called upon whenever it is needed. Python allows a programmer to do this with
what is known as a function. You have used many built-in functions already, such as type, int, print, raw_input
and others. In the GCD program, you will wrap code from the factorsFinder program into a function that you can
"call" upon when you need to find the factors of the two positive integers.
Functions written by the programmer are to always be placed above the regular or main code of the program. A
function definition is used by the programmer to specify the name of the new function and the sequence of
statements that execute when the function is called.
For instance, say you were writing a computer game and there is a need to print out the same lyrics to a song at
various instances throughout the program. Here is a way you could define that function and call upon it when it is
needed.
def printLyrics(): # The keyword def stands for definition and printLyrics is the function name.
print "I'm a lumberjack, and I'm okay."
# Note the function HEADER above ends in a colon,
print "I sleep all night, and I work all day." # and the BODY of the function is indented.
To call the function later during the program, the programmer would then use this function call.
printLyrics()
# Notice there is no argument in this particular function call,
# but the parentheses are needed.
Below is the same example in the shell.
>>> def printLyrics():
print "I'm a lumberjack, and I'm okay."
print "I sleep all night, and I work all day."
>>> printLyrics()
I'm a lumberjack, and I'm okay.
I sleep all night, and I work all day.
>>>
Below is an example of a user-defined function call that contains an argument, which is a variable passed to the
function. As you see, the function is defined to accept the argument by assigning it to a variable called a
parameter, in this case called "bob". A parameter is just a variable name used in the function definition, and is
designed to handle whatever argument was passed to it at the call. This way, the function may be used with
different arguments throughout a program.
>>> def printThrice(bob):
print bob * 3
# This is a FUNCTION DEFINITION.
The PARAMETER is "bob".
>>> printThrice("Spam! ")
Spam! Spam! Spam!
>>> printThrice("Hoy! ")
Hoy! Hoy! Hoy!
# This is a FUNCTION CALL. The ARGUMENT is "Spam! ".
# The return value of the function appears.
# This is another FUNCTION CALL. The ARGUMENT is "Hoy! ".
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
41
It may not be readily evident why it is worth the trouble to divide a program into functions. There are several
reasons:
• Creating a new function gives you an opportunity to name a group of statements, which makes your program
easier to read and debug.
• Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only
have to make it in one place.
• Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into
a working whole.
• Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
42
Creating the Program
Biff is often asked by his math teacher to identify the greatest common denominator of two positive integers so he
decides to write a program called gcd.py that will help him check his work on such problems.
Biff wants the program to be able to take in two positive integers, place the factors of each integer into a list, and
identify the greatest common denominator by comparing the contents of the two lists.
A sample of the program running would look like this:
Enter two integers separated by a comma to receive the GCD: 45,36
The factors of 45 are: [45, 15, 9, 5, 3, 1]
The factors of 36 are: [36, 18, 12, 9, 6, 4, 3, 2, 1]
The GCD of 45 and 36 is: 9
Done!
Biff writes some psuedocode.
Function(s)
Wrap code from factorsFinder.py into a function named factorsFinder, this function should be able to receive
any integer and return a list containing all the factors of that number
The list of factors returned should be in order from largest (the integer itself) to smallest (1)
Actual program
Receive the input of two integers: x and y
Call the factorsFinder function in two separate assignment statements, one with the argument of x and
the other of y, so variables may be used to reference each list of factors returned by the function calls
Traverse one list and identify the first element that is also present in the other list
This first "match" will be the GCD of the two integers, x and y, display the GCD to the computer monitor
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
43
#
#
#
#
#
gcd.py
input: Two positive integers
output: The GREATEST COMMON DENOMINATOR (GCD) of those two integers.
process: Populate two lists with the factors of each integer, largest to smallest.
Compare the contents of one list to another. The first match is the GCD.
# function definition section – in this case, just one
# factorsFinder is the function name, and positiveInteger
# is the PARAMETER, the variable assigned to the ARGUMENT
def factorsFinder(positiveInteger):
# (the integer) passed to it from the FUNCTION CALL.
factors = []
# An empty list is initialized.
divisor = positiveInteger
# divisor to test for factors
while divisor >= 1:
# The loop is set to terminate after the divisor of 1 is tested.
if positiveInteger % divisor == 0: # If there is no remainder, then it is a factor.
factors.append(x)
# Populate the list with all the factors.
divisor -= 1
# DECREMENT the variable, divisor, by one each iteration.
return factors
# This RETURN statement allows the variable assigned in the
# function call to be given the value of the list of factors.
# main <--The function definition area is above this line and the actual program is below.
x,y = input("Enter two integers separated by a comma to view GCD: ")
xfactors = factorsFinder(x)
yfactors = factorsFinder(y)
# These two FUNCTION CALLS are assigned to variables.
print "The factors of", x, "are:", xfactors
print "The factors of", y, "are:", yfactors
# Use print statements to verify
# the program is properly working.
for item in xfactors:
# Traverse in order the content of one list to see which element
if item in yfactors:
# first also appears in the other list. That will be the GCD.
print "The GCD of", x, "and", y, "is", str(item)+"."
# Display GCD.
break
# Terminate the loop as the GCD has been identified.
print "\nDone!"
Once working, submit the script in the body of an e-mail message with the subject "GCD" ALONG with the GCD
of 576 and 384. Therefore, your subject should read:
GCD### (except the '#'s need to be replaced with the GCD of 576 and 384) You may copy this input: 576,384
Below is the same program undocumented.
# gcd.py
def factorsFinder(positiveInteger):
factors = []
divisor = positiveInteger
while divisor >= 1:
if positiveInteger % divisor == 0:
factors.append(x)
divisor -= 1
return factors
# main
x,y = input("Enter two integers separated by a comma to view GCD: ")
xfactors = factorsFinder(x)
yfactors = factorsFinder(y)
print "The factors of", x, "are:", xfactors
print "The factors of", y, "are:", yfactors
for item in xfactors:
if item in yfactors:
print "The GCD of", x, "and", y, "is", str(item)+"."
break
print "\nDone!"
Glossary
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
44
list: A data type in Python which can contain items arranged in a sequence. The items may be of various type.
element: One "thing" or entity in a list.
item: One "thing" or entity in a list.
traverse: To "go across" the items of a list in sequence. A for loop is often used to traverse the items of a list.
append: To add an item to the end of an existing list.
index: Items in a list are identifiable by numbers, which makes up the index. The first item is in the zero-th place.
The second in the one-th place, and so on. It can be a little confusing at first, but just know that numbering begins at
zero and the index of the last item is "one less" than the length of the list, which is the number of items in the list.
length function: The length (len) function returns the number of items in a list, or the number of characters in a
string.
function: A function is a predictable set of statements which, whenever called, acts upon one or more variables and
returns a result.
function definition: A set of statements which, whenever called, acts upon one or more variables and returns a
result. A function definition has the following format: a header, which contains the keyword def followed by the
function name and then the parameter(s), in any, in parentheses. Below the header is the body, an indented set of
code designed to return a desired result. Unless stored in a module, user-created function definitions must be placed
at the top of the script file, above the actual program code.
function call: To evoke/use a function during a program. The format is the function name followed by the variable
passed to it inside a set of parentheses. This variable is called the argument. The function called may be one that is
built-in Python, imported from others elsewhere, or personally created by the programmer.
body: The indented code below the first line of a compound statement.
header: The first line of a compound statement. The code below it is indented.
argument: A value provided to a function when the function is called. This value is assigned to the corresponding
parameter in the function.
parameter: A variable name used inside a function to refer to the value that was passed as an argument at the
function call.
return statement: The expression of the return value of a function.
return value: The result returned to the point of the function call.
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
45
Other Simple Applications
Fibonnaci Sequence and the Golden Ratio – display the numbers in the sequence: a=0 b=1 and c = a + b, as well as
how the golden ratio is present in the sequence by dividing each number found in the sequence by the previous
number
Fractions – program can multiply and divide given pairs of fractions
Mean, Median, Mode – program can identify these values from a given data set
Finding the Distance Between Two Given Points on a Linear Plane – using the Pythorean Theorem
Penny Doubler – ask the user for how many days to double a penny and display findings
Using a Computer to Simulate the Results of a Chance Device – roll two dice a million times and analyze the sum of
each roll
Math Facts Game – single-digit multiplication "flash card" game
Wrap all previous programs into a single program that has a menu interface
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
46
Careers in Computing
The Careers section of the Computer Science Teachers Association is a great resource for career posters, brochures
and links.
Computer Science for Everyone –Sixth Grade (Non-programmers) http://poudre.us/cs February 6, 2016
47
Download