0% found this document useful (0 votes)
50 views

Course Ebook - Student Edition

This document provides an introduction and guide to programming in Python 3. It discusses that Python is an open-source, object-oriented, and high-level programming language. It is intended to introduce new programmers to coding and software development by selecting and organizing parts of the Python language and libraries to build practical programs. The guide covers basic Python concepts like variables, strings, functions, conditionals, and lists over its sections and chapters.

Uploaded by

Nanoton
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Course Ebook - Student Edition

This document provides an introduction and guide to programming in Python 3. It discusses that Python is an open-source, object-oriented, and high-level programming language. It is intended to introduce new programmers to coding and software development by selecting and organizing parts of the Python language and libraries to build practical programs. The guide covers basic Python concepts like variables, strings, functions, conditionals, and lists over its sections and chapters.

Uploaded by

Nanoton
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 102

GUIDE

to Programming in Python 3.3.2 | Written by Victor E. Rodriguez


1
2
About Python

Python is an open-source, object-oriented and high-level programming language. As this book is written for the
new programmer, let's take a few moments to explain what these terms mean. Open-source is both a type of
license and a philosophy. When software is open-source, users are given a free license to use, modify and
redistribute its source code. You'll usually find a very large, vibrant and innovative community for almost any
open-source project or software.

The definitions of high-level programming language and object-oriented programming (OOP) are better
understood after knowing a little more about how programming works. As we work through this book, and as
programming concepts become clearer, we'll finally introduce what high-level and object-orient programming
(OOP) really mean. For now, know that Python is loved for its ease, elegance, simplicity and ability to do a lot
with a small amount of code. Because of it's natural language elements, it is an excellent language for new
programmers.

About the Guide

This guide is not intended to be a resource for the deepest parts of the Python language or its many libraries. It
has been written to introduce the new programmer to the world of code and to experience the art of software
development. Specific modules and parts of the language have been selected and organized throughout the text
to lead the student into practical program development, serving as a foundation for a greater career in
computing. All terms are in boldface and defined to ensure that no key programming concept slips by.

About the Author

Victor is a computer science instructor, advocate and author with over 11 years in software and education,
including K-12 and vocational CS program and curriculum development. He has taught at Google, developed
course content for John Hopkins CTY, spearheaded the CS department at two international school groups (+6
schools) and has worked in the tech and education field in Italy, Germany, the Middle East, NYC and the heart
of Silicon Valley in Cupertino, California. He currently runs EngageCS.org, a CS advocacy K-12 and vocational
curriculum portal

License & Cover Design

Python Logo © 1990-2013, Python Software Foundation.


This work, including the Growth Flower © 2016, EngageCS

3
TABLE OF CONTENTS
Sec Topic Pg

A.1 Introduction: Installing Python …........…........…........…........…........…........…........…........…........…........…........…................. 6


A.2 IDLE & Shell (Interactive Interpreter …........…........…........…........…........…........…........…........................................................ 6
A.3 Python 3.3.2. Mac OS X …........…........…........…........…........…........…........….......…........…............…........…....................... 6
A.4 Python 2.7.5 for Windows …........…........…........…........…........…........…........…....…........…............…........…....................... 6
A.5 Resources …........…........…........…........…........…........…........….......…........…............…........…............…........….................. 6
1.1 Numeric Types …........…........…........…........…........…........….........…........…............…........…............…........…..............…... 7
1.2 Arithmetic Operators …........…........…........…........…........…...........…........…............…........….............................…........…... 7
2.1 Order of Evaluation …........…........…........…........…........…............…........…............…........…..............................…........…... 8
3.1 Variables …........…........…........…........…........…........…........…........…........…........…........…........…........…........…........…... 9
4.1 Strings …........…........…........…........…........…........…........…...….................…........…........…........…........…........…........…... 10
4.2 Referencing Characters in a String …........…........…........…........…................…........…................................…........…........…... 10
4.3 Finding an Index in a String …........…........…........…........….........…........…............…........…......................….......…........…... 11
4.4 Concatenating Strings ....…........…............…........…............…........…............…........…..............…....................…........…........ 11
4.5 Repeating Strings ....…........…............…........…............…........…............…........….................…........…............…........…........ 11
4.6 Splitting Strings ....…........…............…........…............…........…............…........…....................…........…............…........…........ 11
4.7 Escaping ....…........…............…........…............…........…............…........…............…..........................…............…........…........ 11
5.1 Functions & Arguments ...…........…............…........…............…........….............…...................…...................…......................... 12
5.2 Built-In Functions ...…........…............…........…............…........…...................…...................…..................................…............ 12
6.1 Using Comments ...…........…............…........…............…........…...............…........…............…........…............…........…......... 13
7.1 Booleans ...…........…............…........…............…........…...............…........…............…........…............…........….....….............. 14
7.2 Comparison Operators ...…........…............…........…............…........…..............…........…............…........….......…...…...…....... 14
8.1 Containment ...…........…............…........…............…........…...............…........…............…........…............…........…................. 15
8.2 Membership Operators ...…........…............…........…............…........…..........…........…............…........…..............…...….......... 15
9.1 Getting User Input ...…........…............…........…............…........…...............…........…............…........…............…........…......... 16
10.1 Converting Strings & Integers ...…........…............…........…............…........…....…........…............…........…...............…............ 17
P.1 Apply & Practice: Are We There Yet? ...…........…............…........…............….....…........…............…........…...............…............ 18
11.1 Indenting ...…........…............…........…............…........…...............…........…............…........…............…........…...…...….......... 19
12.1 The If Statement ...…........…............…........…............…........…............…........…............…........…............…...........…............ 20
P.2 Apply & Practice: Shorter Message Service ...…........…............…........….......…........….................…........…............…...…....... 21
13.1 The Else Statement ...…........…............…........…............…........…...............…........…............…........…............…........…......... 22
14.1 The Elif Statement ...…........…............…........…............…........…..............…........…............…........…............…........….......... 23
P.3 Apply & Practice: To Drive or Not to Drive ...…........…............…........…....…........…....................…........…......…...…............. 24
15.1 Lists ...…........…............…........…............…........…...............…........…............…........…............…........…..…...…...…............. 25
15.2 Referencing Items in a List ...…........…............…........…............…...........…........…............…........….........…...........…...….... 25
15.3 Appending Lists ...…........…............…........…............…........…...............…........…............…........…............…............…......... 25
15.4 Extending Lists ...…........…............…........…............…........…..............…........…............…........…............…........…............... 25
15.5 Sorting Lists (Ascending) ...…........…............…........…............…...........…........…............…........….........….........…...…......... 26
15.6 Sorting Lists (Descending) ...…........…............…........…............…...........…........…............…........….........…........….....…....... 26
15.7 Reversing ...…........…............…........…............…........…..............…........…............…........…............…........…...…....….......... 26
15.8 Counting ...…........…............…........…............…........…..............…........…............…........…............…........…...…...….......... 26
15.9 Removing ...…........…............…........…............…........…............…........…............…........…............…..........…...….…............ 26
15.10 Popping ...…........…............…........…............…........…...............…........…............…........…............…..........…...…...…......... 27
16.1 Tuples ...…........…............…........…............…........…...............…........…............…........…............…........…..….......….......... 28
16.2 Dictionaries ...…........…............…........…............…........…............…........…............…........…............…..........…...…............ 28
16.3 Deleting Items in a Dictionary ...…........…............…........…...........…........…............…........….............…..........…..…............ 28
16.4 Adding Items to a Dictionary ...…........…............…........…..............…........…............…........…..........…..........….....…............ 29
16.5 Combining Dictionaries ...…........…............…........…............…........…........…............…........…............…......…...….............. 29
17.1 For Loop ...…........…............…........…............…........…..............…........…............…........…............…..........…...….….......... 30
P.4 Apply & Practice: This Programmer is No Dodo ...…........…...............…........….........…........…............….................…............ 31
18.1 Counters ...…........…............…........…............…........…...............…........…............…........…............…......................…......... 32
19.1 While Loop ...…........…............…........…............…........…...............…........…............…........…............….................…......... 33
P.5 Apply & Practice: Four, No More ...…........…............…........…............….....…........…............…........…...................…............ 34
20.1 Exception Handling ...…........…............…........…............…........…...........…........…............…........…..................................... 35
21.1 User-Defined Functions ...…........…............…........…............…........…......…........…............…........….................................... 36
P.6 Apply & Practice: Now We're Cooking! ...…........…............…........….......…........….................…........…................................ 38
22.1 Modules ...…........…............…........…............…........…...............…........…............…........…............…........…....................... 39
23.1 Classes & Objects ...…........…............…........…............…........….......…........…............…........…............…........…................. 40
24.1 Creating a Directory ...…........…............…........…............…........…....…........…............…........…............................................ 41
24.2 Removing a Directory .........…............…........…....…........…............…........…..................…........…...........….......................… 41
25.1 Reading Files …........…............…........…....…........…............…........…..................…........…...........…........…...........…........… 42

4
Sec Topic Pg

26.1 Writing to Files …........…........…........…........…........…........…........…........…........…........…........…...........….......…............... 43


27.1 Renaming Files …........…........…........…........…........…........…........…..........................................................….......…............... 44
27.2 Removing Files …........…........…........…........…........…........…........….......…........…............…........….................…............... 44
27.3 Getting File Info …........…........…........…........…........…........…........…....…........…............…........…......................…............. 44
P.7 Apply & Practice: Logging the Login …..........…........…........….......…........…............…........…............…........…..................... 45
28.1 Working with CSV Files …....…........…........…........…........….........…........…............…........…............…........…..............…... 46
29.1 Python GUI …........…........…........…........…........…...........…........…............…........….............................…........…................ 48
29.2 Tkinter …........…........…........…........…........…............…........…............…........…..............................…........…...…............... 48
29.3 Window Size ….…........…........…........…........…........…........…........…........…........…........…........…........…........…........…... 48
29.4 Title Bar ….............…........…........…........…........…........…...….................…........…........…........…........…........…...........…... 48
29.5 Background Color ….........…........…........…........…........…...….................…........…........…........…........…........…...........…... 48
29.6 Creating Labels …........…........…........…........…................…........…................................…........…........….....….......….......... 49
29.7 Positioning Labels with .place() ….…........…........…........….........…........…............…........…......................…........…........…... 49
29.8 Positioning Labels with .grid() ..…............…........…............…........…............…........…..............…....................…........…........ 49
29.9 Positioning Labels with .pack() ..…............…....…............…........…..............…........................…............…........…..............… 50
29.10 Formatting Labels: Foreground .........…........…............…........…............…........….................…........…............…..........…........ 50
29.11 Formatting Labels: Background ....…........…............…........…............…........…....................…........…............…...........…........ 51
29.12 Formatting Label Text ...........…............…........…............…........…............…..........................…............…...................…........ 51
29.13 Displaying Images in Labels .........…............…........….............…........….............…........….............…........…...............…........ 51
29.14 Buttons ...…........…............…........…............…........….............…...................…...................….............….......…..................... 52
29.15 Entry Boxes ...…........…............…........…............…........…...................…...................…...........................................…............ 52
29.16 Coding with Entry Boxes and Buttons ...…..............…........…...............…........…............…........…....................…........…......... 53
29.17 Frames ...….......................…........…...............….................…........…...............….................…........…...............…................. 55
29.18 Buttons Within Frames ...…...........................….................…........…...............….................…........…....................................... 55
29.19 Interaction Between Frames ...…...........................….................…........…...............….................…........….............................. 56
P.8 Apply & Practice: We're Still Cooking! ...….…..........…...............…........…............…........…............…............….....….............. 57
30.1 Dialog Boxes ...…........…............…........…............…........…..............…........…............…........….......…...…...…..................... 58
31.1 Menu Bars: Creating Menu Bars in Tkinter ...…........…............…........…............…........…............…........…............…............. 60
31.2 Customizing Menu Bars ...…........…............…........…............…........…..............…........…............…........….......…...….......... 61
32.1 Events & Binding: Tkinter Key Events ...…........…............…........…...........…............…........….......…...…...….......................... 62
33.1 Working with Databases: Python & SQLite3 ...........…........…...............…........…............…........….........................….............. 63
33.2 Installing SQLite3 on Max OS X ..........…........…...............…........…............….…........…...............…........…............…............. 63
33.3 Installing SQLite3 on Windows .......…........…...............…........…............…........…................................................................... 63
33.4 Creating a Database ............…...............…........…............…........…........................................................................................... 63
33.5 Creating a Table ............…...............…........…............…........….............…........…..................................................…........…... 63
33.6 Writing to Databases ............…...............…........…............…....................…........…............…........……...........................….... 65
33.7 Reading Databases ............…...............…........…............…....................…........…............…...…..................................…….... 67
33.8 Modifying Databases ............…...............…........…............…...................…........…...…...................................…........….….... 68
34.1 Web Frameworks: Pre-Requisites ...…........…............…...................…........…...…...................................…........….…............. 71
34.2 Bottle ....…........…..........................................…...................…........…...…...................................…........….…......................... 71
34.3 Creating a Website .....…........…............…...................…........…...…...................................…........….…................................. 71
34.4 Routes ...…........…............…........…............…........…..............…...........................…........….….........................….......…......... 72
34.5 Posts ...…........…............…........…..............…...........…...........…...........…...........….........................…..................….............. 75
34.6 404 Pages ...….....…........…............…........…..............…...........…...........…...........…...........…............…...................….......... 76
34.7 Integrating SQLite3 into Webpages ...….....…........…............…........…..............…..............…...........…...........…............…...... 76
34.8 Data Security: Hashing Data ...….....…........…............…........…..............…..............….........…...................…...........….......... 82
34.9 HashLib ...….....…........…............…........…..............…..............…...........….................…...............…...............…......….......... 83
34.10 Bcrypt and PBKDF2 ...….....…........…............…........…..............…..............…...........….................…...............…................... 85
35.1 Python's Socket Module ........…........…............…........…..............…..............…...........…...........…............…......................... 87
35.2 Creating a Server/Client Program ...…..................…...........…........…............…........…...........…........….............................….. 87
36.1 Email Programming: Python's SMTP Module ...…..................…...........…........…............…........…...........…........…............… 90
37.1 Python and Arduino: Embedded Systems ..…..............…..............…...........….................…...............…...............…......….......... 93
37.2 Arduino Uno ...….....…........…............…........…..............…..............…...........….................…..........................…................... 93
37.3 Arduino IDE ........…........…............…........…..............…..............…...........…...........…............…............................................. 93
37.4 Setting Up Arduino ...…..................…...........…........…............…........…...........…........…...................................................….. 93
37.5 Serial Monitor ...…................................…...........…........…............…........…...........…........…...............................................… 94
37.6 Serial Monitor: Writing ...….…................................…...........…........…............….….....................................................…......... 94
37.7 Serial Monitor: Sending ...…..................…........................…........…............…........…...........….............................…............… 95
37.8 PySerial ...….…..................…...........…........…............….….............................…...................................................................... 96
37.9 PySerial with Bottle .........…...........…........…............….….............................…........................................................................ 98

5
INSTALLING PYTHON
A.1 - Installing Python

Throughout this book, we will be using Python 3.3.2. Many of the simple calculations that we'll perform can be
done directly through the interpreter, which comes bundled with the Python IDLE (Integrated Development
Environment). In case you are unfamiliar with these terms, let's take a few moments to explain what they are.

A.2 - IDLE & Shell (Interactive Interpreter)

The IDLE is basically a package from Python. It includes a type of text editor called a compiler which allows us
to enter, edit and save code. A compiler runs all of our code immediately. The package also includes a
debugger, which checks the syntax of our code as well as a window called the Python shell. The shell is also
known as the interpreter and the interpreter is simply a program window where we can directly enter and run
code, allowing us to see the results immediately. It executes our code, line by line. The shell is also called the
interactive interpreter because of the way that it allows instant interaction between the user and the code. The
shell cannot save code, so it is only ideal for small snippets of code or simple calculations that do not need to
be saved.

Once your IDLE is installed, you can use the shell (interpreter) to run simple code that does not need to be
saved and the IDLE text editor or compiler to edit and save serious programs.

A.3 - Python 3.3.2. Mac OS X

Python comes pre-installed on Mac OS X, but is often outdated. Running Python on OS X is as simple as
opening Terminal and typing “python”; however, for this book, it is highly recommended that you simply
download the latest version with the IDLE.

Download 3.3.2: http://www.python.org/getit/

A.4 - Python 2.7.5 for Windows

The latest version of Python for Windows is 2.7.5. Simply download the IDLE for either a 64 or 32-bit to get
started.

Download 2.7.5: http://www.python.org/getit/

A.5 - Resources

If you need further installation help, visit: https://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html

6
NUMERIC TYPES
1.1 - Numeric Types

In Python, there are four types of numbers, called numeric types. In this book, we will be covering only two:
floats and integers. Floats are decimal numbers while integers are not. Using these numeric types and a set of
mathematical symbols like + and -, called operators, we can perform mathematical calculations in Python. As
we move into expressions and begin to write programs, the importance of numeric types will begin to make a
lot more sense, but for now, let's calculate some floats and integers in our Python shell to better understand
their basic syntax.

We can add “2”, an integer to “2.0”, a float:

>>> 2 + 2.0
4.0

We can divide “1.0”, a float by “1”, an integer:

>>> 1.0 / 1
1.0

We can add “3+3”, two integers and then divide the result by “2.0”, a float:

>>> (3+3) / 2.0


3.0

Basically, we are performing simple mathematical equations. We are specifying the number type in such detail
though because in Python, we need to distinguish between a float and an integer.

1.2 - Arithmetic Operators

An operator is a mathematical symbol, like + and -. Some operators can do special tasks, but the most basic
mathematical operators, called arithmetic operators can be used together with numeric types to perform
mathematical equations in Python. The following table shows some of the most common arithmetic operators in
Python. You may wish to use it as a reference as we begin to study and write our own programs.

Operator Name Arithmetic Example


>>> 3 * 3
* Multiplication Multiplies two or more numbers
9
>>> 5 / 2.5
/ Division Divides two or more numbers
2.0
>>> 10 + 4
+ Addition Adds two or more numbers
14
>>> 10 - 4
- Subtraction Subtracts two or more numbers
6
>>> 4 ** 2
** Exponent Returns the exponent
16
>>> 30 % 29
% Modulus Divides and returns remainder
1
>>> 4 + 4 == 8
== Equal Checks if two values are equal
True
>>> 4 + 4 != 7
!= Not Equal Checks if two values are unequal
True

7
ORDER OF EVALUATION
2.1 - Order of Evaluation

In Section 1.1, we performed some basic calculations using floats, integers and operators. In one of the
examples, we added 3 to 3 within parenthesis and then divided the result by 2.0:

>>> (3+3) / 2.0


3.0

Notice that in this expression, Python evaluated the (3+3) first, then divided the result by 2. This has to do with
the order of how operations are evaluated, called the order of evaluation in Python. Simply put, Python
evaluates from left to right and evaluates all parenthesis and subexpressions first. When a subexpression is
present inside of another subexpression, the inner-most subexpression becomes the first operand and is
evaluated first. Let's look at an example:

>>> (3 * (2+2)) / 4
3.0

In the expression above, Python evaluates the inner-most subexpression (2+2) first, then multiples the result by
3. The result of that calculation is then calculated by 4.

When no parenthesis are used in an expression, Python uses the standard order of evaluation. You may have
learned the acronym “Please Excuse My Dear Aunt Sally” in a math or Excel class. The capital letters in “My
Dear Aunt Sally” stand for multiplication, division, addition and subtraction. Python uses this order in the
absence of parenthesis. Let's look at an example:

>>> 1 + 25 / 2
13.5

In the expression above, Python evaluates 25 / 2 (division) first, then adds 1 (addition). Let's break down a few
more expressions to better understand the order of evaluation:

>>> 400 - 1 / 2
399.5

In the above expression, 1/2 is evaluated first because division comes before subtraction. The result is subtracted
from 400.

>>> - (20 - 5)
-15

This type of expression is called a unary expression. A unary expression is one that is composed of a single
value. When a negative is used outside of a parenthesis, as shown above, it negates the result.

8
VARIABLES
3.1 - Variables

A variable is a symbol or name that stands for a value. They are important in programming because they allow
us to write more flexible programs. Variables can hold many things including a word, sentence or number. Let's
create a variable called “your_age” and assign the number 14 to it. Then, let's print the “your_age” variable:

>>> your_age = 14
>>> print (your_age)
14

We can now use the variable “your_age” to perform various calculations or tasks. If we wanted to change the
value of “your_age” again, we can easily do this by writing “your_age” once again and assigning a new value to
it.

Notice that we used an equals sign “=” to assign 14 to “your_age”. This equals sign is also called an
operator, but not the same kind of operator that we looked at in Section 1.2. Those operators were
being used for arithmetic while this one is being used for assignment; thus the name assignment
operator. Remember the difference between assignment and arithmetic operators when you begin to
program. An equals sign =, is for assignment, while a double equals sign == is to check if one
value is equal to another.

Let's take a look at some of the different ways that we can assign values to variables:

>>> your_age = 14
>>> my_age = 29
>>> print (my_age - your_age)
15

In the code above, we subtracted one variable from another. Notice the format that we used to perform a simple
mathematical equation using variables. We can also change the value of a variable using another variable:

>>> his_age = 5
>>> his_age = your_age
>>> print (his_age)
14

Notice how “his_age”, which originally held a value of 5, now holds 14.

9
STRINGS
4.1 - Strings

A string is simply a set of characters. A character is any single bit of information that we type such as a letter,
number, symbol or space. If we were to ask Python to count the length of the string “Python rocks!” for us, the
program would return 13. This includes the space and the exclamation mark (!).

Strings are identified by the quotation marks around them. We can put single ('), double (") or even triple quotes
(""") around strings. Python accepts all 3 as long as we are consistent, using the same type at both the beginning
and end of the string. Let's take a look at 3 ways that we can write strings in Python:

>>> print ('I am a string because I am in single quotes')


I am a string because I am in single quotes

>>> print ("I am still a string even though I am in double quotes")


I am still a string even though I am in double quotes

>>> print ("""Yes, I'm still a string in triple quotes""")


Yes, I'm still a string in triple quotes

4.2 - Referencing Characters in a String

Characters within a string can be referenced using a set of square brackets ([]) and a colon (:). For example, if
we have a string named “Python” assigned to a variable named “program” and wanted to get the 3rd character,
“h” from the string, we can reference it by using 3 in square brackets:

program = "Python"
program[3]
'h'

Notice that we called “h” the 3rd character rather than “t”. This is because the first character in a string is
considered to be at the 0 index in Python.

If we wanted to get all the characters after the 3rd character, we would leave out the second reference:

program[3:]
'hon'

If we wanted to get all the characters before the 3rd character, we would leave out the first reference:

program[:3]
'Pyt'

Finally, if we wanted to get all characters from the 3rd until the 5th, we would write:

program[3:5]
'ho'

We can also reference indices in a string in the reverse order. For example, let's change the variable program to
hold a long string called “XXXXX XXXXX XXX XXXXX XX XX8X” and reference the number 8 towards the end of
the string:

>>> program = "XXXXX XXXXX XXX XXXXX XX XX8X"


>>> program[-2]
'8'

Notice how we used a [-2] which starts the count from the end of the string and works its way back.

10
4.3 - Finding an Index in a String

The location (or index) of specific characters can be found within a string using the find() method. In the
example below, we would like to find out the index of the letter M:

name = "My Name"


name.find("M")
0
name.find("y")
1

Notice again that the “M” in “My Name” is considered to be at the 0 index, not the 1st.

4.4 - Concatenating Strings

One of the most useful operators that can be used with strings is the plus (+) operator. When we “add” 2 strings
together, we are telling Python to combine those strings. This is called concatenation. Here is an example:

>>> print ("Python " + "rocks!")


Python rocks!

When we concatenate strings, we need to be aware of how we space characters so that we don't get weird
spacing. We also need to know that there are special conversions needed to combine strings with integers and
floats. We will learn more about this and how to properly convert strings in the coming sections.

4.5 - Repeating Strings

Strings can be “multiplied” using the multiply (*) operator. This may come in useful in some of your future
programming. An example of this is when we multiply the string “Go” by 5:

>>> print ("Go" * 5)


GoGoGoGoGo

Notice how the word “Go” prints one after the other, without any space. To fix this, using correct spacing, we
should place a space after “o” in our print statement.

4.6 - Splitting Strings

A portion of a string can be cropped using the split() method and specifying where the string should be split. In
the example below, we would like to split the string after the first word “your”:

name = "Your name is Kareem"


name.split("Your")
['', ' name is Kareem']

4.7 - Escaping

We know that we can identify strings by the quotation marks around them, but what if the string itself has
quotation marks in it? Escaping is to place a backslash (\) before the quotation marks within the string itself to
tell Python that these quotation marks should not be considered code, but rather part of the string. Here is an
example:

>>> print (“I said, \”Where are you going? Are you going home?””)
I said, "Where are you going? Are you going home?"

11
FUNCTIONS & ARGUMENTS
5.1 - Functions & Arguments

Now that we've looked at strings, now would be a good time to introduce functions. A function is a useful
command that performs a procedure or specific task. A function can be accompanied by an argument (also
called a parameter) which is what the function operates on. Look at the code in the previous sections. We have
been using the function print() that operates on a string argument all along:

print ( "Python, " + "rocks!" )

function argument

In Python, we can choose between a large range of built-in functions, like print(), or create functions ourselves
called user-defined functions. Over the next few sections, in our text and code, we will focus only on built-in
functions and will look at user-defined functions in section 20.1.

5.2 - Built-In Functions

len() is a useful built-in function. When used, it will return the number of characters within a specific string. For
example, the word “computer” has 8 characters. Let's look at how we would use the length function to get the
same answer in our Python shell:

>>>len("Computer")
8

We could also use a function itself as an argument. Let's say that we wanted to print the len function that we
just wrote inside of our IDLE text editor, we would use len() as the argument of the print function:

print (len("Computer"))

argument

function

There are many built-in functions and more that we'll learn throughout this book, but here are a few to get you
started and to better your understanding of how functions look and work:

dir()

When used in the shell, returns a list of all the variables that we have defined so far. You may wish to use this
function for longer programs for a glance at all your declared variables.

float()

Converts a string or a number to a float.

help()

Let's say that we forget what the len or dir function does, if we use help(len) or help(dir), Python will return
some information on those particular functions. Use help() when you forget what a function does.

12
COMMENTS
6.1 - Using Comments

Before we begin writing longer and more elaborate programs, now would be a good time to introduce
comments. A comment is simply text written within a program that is ignored by the interpreter. Think of
comments like the titles at the top of each page or the numbers accompanying each section in this book.
Without them, the book would have no structure and it would be difficult to navigate. Comments work the
same way, allowing us write what we need to write about the program within the program, without these
remarks affecting our code in any way.

In Python, the syntax or format for writing comments is simply a hex symbol (#) before the text. Let's use
comments in the len() function program that we wrote in the last section to better understand how comments
look:

# Prints the length of the string "Computer"


print (len("Computer"))

This would print:

As you write more and more programs, be sure to use comments to make the program more organized and
easier to read.

13
BOOLEANS
7.1 - Booleans

Python can distinguish whether something is true or not using a boolean. A boolean is a data type that has two
possible values, either “true” or “false”. In previous sections, we learned about arithmetic and assignment
operators. For example, we said that a single equals sign (=) is an assignment operator, used to assign a value to
a variable and that a plus sign (+) is an arithmetic operator, used to add two or more operands. With booleans,
we are introduced to a new type of operator called a comparison operator. A comparison operator is used in
expressions to perform comparisons. One comparison operator is a double equals sign (==), which indicates
that something is equal. Let's look at some examples of how this operator is used:

>>> 1 == 1
True
>>> "r" == "r"
True
>>> 4 > 9
False
>>>

The opposite of equal (==) is not equal, indicated by an exclamation mark immediately followed by an equals
sign (!=). Here are two examples:

>>> 3 != 5
True
>>> "A" != "A"
False

7.2 - Comparison Operators

The following table shows some of the most common comparison operators in Python. You may wish to use it as
a reference as we begin to study and write our own programs.

Operator Name Arithmetic Example


>>> 4 + 4 == 8
== Equal Checks if two values are equal
True
>>> 4 + 4 != 7
!= Not Equal Checks if two values are unequal
True
Checks if one value is greater >>> 4 > 3
> Greater Than
than another True
Checks if one value is lesser >>> 4 < 3
< Lesser Than
than another False
Checks if one value is greater >>> 4 >= 4
>= Not Equal
than or equal to another True
Checks if one value is lesser >>> 3 <= 4
<= Not Equal
than or equal to another True

14
CONTAINMENT
8.1 - Containment

Now that we know 3 types of operators, let's look at a 4th called a membership operator. A membership
operator is an operator that is used to check whether something is contained or not contained inside of another.
This process is called containment. There are only two membership operators: in and not in. Let's take a look at
a few examples of how they can be used:

>>> "A" in "Apple"


True
>>> "A" not in "Apple"
False
>>>

The code above checks whether the string “A” is contained in the string “Apple” and returns a boolean value.

We can also check if a string is contained inside of a variable:

>>> my_name = "Victor"


>>> "V" in my_name
True

8.2 - Membership Operators

The following table shows the two membership operators in Python:

Operator Name Arithmetic Example


Checks whether one value is >>> "A" in "Apple"
in in
inside of another True
Checks whether one value is >>> "A" not in "Apple"
not in not in
not inside of another False

15
USER INPUT
9.1 - Getting User Input

A very important aspect of programming is of course getting user input. As this is one of my favorite parts of
Python, let's get right into it and look at a way to ask the user a question and process his/her answer.

question = "What is your name?"


print (question)
answer = input()

print ("Your name is " + answer + "!")

When we run the code above, we get:

What is your name?


Victor
Your name is Victor!

To ask the user to input something, we used a built-in function called input() and assigned it to a variable
named “answer”. We can specify as many inputs as we want within our programs using a different variable
name each time. When the above program runs, it immediately prints the question followed by the input area,
where the user can input text. The program then stores this value and returns it when we asked the program to
print “Your name is” plus the answer variable. Reiterating what we have already learned, notice how we
formatted the print line, using concatenation and used correct spacing between the quotation marks within the
strings.

Practice writing a few small programs in your shell like the one above to get used to the syntax of the input()
function. Experiment as well. Doing so will definitely serve you well as we get into more complicated
programs.

16
OBJECTS CONVERSION
10.1 - Converting Strings & Integers

Before we get started writing our first input program, we should first understand how variables and objects are
understood and then converted in Python. Imagine that we ask a user for information with an input(). The user
types in “Apple” and Python goes to process it. If the process was a numerical calculation, how would Python
be able to add “Apple” plus 20 for example? Reversely, if the input was a number, Python would think that the
number is a string and start breaking it down as one. Therefore, we as programmers must tell Python what is a
string and what is an integer, or what value needs to be converted to these types using two very important
functions called the str() and int() function. Let's modify the input program that we wrote in the last section to
help us better understand how conversions work:

question = "What is your name?"


print (question)
answer = input()

name = str(answer)
print ("Your name is " + name + "!")

Notice that we added this line to the program:

name = str(answer)

By adding this, we have told Python to convert whatever the user inputs into answer into a string. Now this
string will be able to print correctly alongside “Your name is ” and Python will not try to do something strange
like add “Your Name is” + 20. It now sees name as a string and will print it as such.

Let's look at one more example before we write our first input program:

print ('Type in a number:')


response = input()

number = int(response)
half = number / 2

print ("Your number divided by 2 is ' + str(half))

We took a number from the user and declared that number as an integer. We performed a calculation which
understands the variable number to be an integer. Then we printed that answer as a string alongside “Your
number divided by 2 is”. If all of this makes sense, let's try our first program.

17
APPLY & PRACTICE
Are We There Yet?

Directions & Starting Code:

Your younger brother is turning 9, but he would like to know how much longer it will be before he is allowed to
drive. Write a program that allows the user to enter the age of your brother and prints how long it will be before
he can drive. The law of your country allows young adults to drive at the age of 17.

question = "What is your age?"


print (question)
response = input()

Task:

Declare variables for driving_age and for the calculation that is needed. Also, be sure to declare certain
variables as strings or integers. After that, print the message “You have ___ years until you can drive.”

Solution:

Be sure to try as hard as you can and multiple times before looking at the solution, but if you do get stuck in a
loop, the solution is located in back of the book.

18
INDENTING
11.1 - Indenting

Before we move on to the very important if statement, we should understand indenting in Python. Previously,
we emphasized how important proper spacing is when writing strings. Indenting is even more important. An
indent is the space before text that is a certain distance from the left margin. If we do not indent our code
properly, Python will give us the following error:

Syntax error
expected an indent block

Indent mistakes are common and sometimes it takes a few indent errors to get us to realize just where our
indent mistake is within our code; however, Python code must be properly indented in order to run. As we start
learning and using the if statement and other functions in the next sections, give a part of your focus to how we
indent.

19
IF STATEMENT
12.1 - The If Statement

The if statement is a major area in Python and in programming in general. The if statement helps us to decide
between two or more alternatives and output different results based on each. Let's look at a simple if program
that also uses the in operator that we learned about in Section 8.1:

>>> if "Adobe" in "Adobe Acrobat”:


print "Acrobat is owned by Adobe"

The program checks whether the “Adobe” string is in the “Adobe Acrobat” string. If it is, Python will print
"Acrobat is owned by Adobe". Notice that a colon (:) is located at the end of the line that contains the if
statement. If this colon is missing, the program will not run.

If the colon is missing from the end of the if line, Python will give you the following error:

SyntaxError: invalid syntax

Another way to use the if statement is to perform a mathematical check. Let's say that we are creating a program
to check whether there are enough trucks to move a certain number of pipes to a construction zone. For our
problem, we know that it takes 3 trucks to move one pipe. We also know that we have 400 trucks and 1300
pipes:

trucks = 400
pipes = 1300

if pipes > 3 * (trucks):


print ("Not enough trucks")

The program performs a calculation using the variables that we assigned values to as well as the formula that
we got from the problem.

Notice that both programs above are only half complete. If “Adobe” was not in the “Adobe Acrobat” or if there
were enough trucks, then we should be able to print those options as well. An if statement needs an alternative
called an else statement, which we will cover in the next section.

20
APPLY & PRACTICE
Shorter Message Service

Directions:

Your school uses an SMS service to provide updates to parents and high school students about important
school-related announcements. You have been asked to write a message informing all parents that the science
fair is cancelled due to a heavy sand storm. The SMS program checks all messages to ensure that they are not
longer than 70 characters. Your task is to write the portion of the program that does the limit check.

sms1 = "School is closed due to a sandstorm. Please check the website for more info"
sms2 = "School is closed. Sandstorm. Check website"
sms3 = "Sandstorm has closed the school. Please check website"

Task:

Write a program that checks whether each sms variable is equal to or less than 70 characters. If so, print the
message along with another message that gives the actual length. The output should contain the message
followed by a period and then the statement “Number of Characters: 34”

Be sure to use the len() function and remember that we must convert variables to strings when printing them.
Your first output line should look like this:

School is closed. Sandstorm. Check website. Number of Characters: 42

Solution:

Be sure to try as hard as you can and multiple times before looking at the solution, but if you do get stuck in a
loop, the solution is located in back of the book.

21
ELSE STATEMENT
13.1 - The Else Statement

The else statement in Python is a part of the if statement and is obviously an additional check within the code.
Let's look at the same program that we used before, but this time with the else statement.

if "Adobe" in "Adobe Acrobat":


print ("Acrobat is owned by Adobe")
else:
print ("Acrobat is not owned by Adobe")

The above program will print “Acrobat is owned by Adobe". Notice that the lines that contains the if and else
statements both end with the colon. Just like the if statement, if the colon is missing for our else line, the
program will not run.

Now let's change the previous program so that it returns the else statement:

if "Adobe" in "Microsoft":
print ("Acrobat is owned by Microsoft")
else:
print ("Acrobat is not owned by Microsoft")

Output:

Acrobat is not owned by Microsoft

Let's look at another program to help us get more familiar with both statements. The following program uses a
greater sign (>), a comparison operator that we learned about Section 7.1. This will check whether one value is
greater than another.

sum1 = "203"
sum2 = "102"

if sum1 > sum2:


print ("Sum 1 is greater than Sum 2")
else:
print ("Sum 1 is less than Sum 2")

We've declared some variables, checked them and printed certain strings based on the checks using an if and
else statement. Obviously, “Sum 1 is greater than Sum 2” will be the result.

22
ELIF STATEMENT
14.1 - The Elif Statement

The elif statement is basically the 3rd part in the if group. If we are using 3 or more checks within the code, we
would use the elif statement between the if and else to check a third option. Here is a simple example using the
previous program. We'll make the value of sum1 and sum2 equal to do a third check with elif:

sum1 = "203"
sum2 = "203"

if sum1 > sum2:


print ("Sum 1 is greater than Sum 2")
elif sum1 == sum2:
print ("Sum 1 is equal to Sum 2")
else:
print ("Sum 1 is less than Sum 2")

Notice that we've used the colon at the end of the elif line once again and that a double equal sign (==) was
used (see section 7 for the difference between = and ==). The above program will print “Sum 1 is equal to Sum
2”.

>>> Move on to the next Apply & Practice to implement what you have learned.

23
APPLY & PRACTICE
To Drive or Not to Drive

Directions & Starting Code:

Finally, your brother has turned 17! He is now ready to drive, but must first register online for an appointment at
the driving school for his first test. On the website, he has to first pass a preliminary check to see whether he is
17 or older. If he enters a valid birth year, he will be taken to the registration page. You will be writing the
program that checks and validates his year of birth. The current year is 2013.

name = input("Please enter your first name: ")


year = input("Please enter your 4-digit year of birth: ")

Task:

Write a program that asks the user for his name and date of birth. Be sure to convert the date of birth variable to
an int. Using if, determine if the user is old enough to register. If he/she is, print “Welcome ____ ” and his/her
name. If not, print “You are not old enough to register”.

Solution:

Be sure to try as hard as you can and multiple times before looking at the solution, but if you do get stuck in a
loop, the solution is located in back of the book.

24
LISTS
15.1 - Lists

Before we move on to the very important for loop, let's examine the concept of lists in Python as we will be
using these to practice our for loop. Lists contain comma separated elements in square brackets. By creating
lists, we are able to store a wealth of information inside of a single variable. Let's create a short shopping list
using Python and then follow that with a print:

shopping_list = ["Apples", "Bananas", "Oranges", "Avocados", "Garlic", "Onions", "Chicken", "Lamb", "Eggs"]
print (shopping_list)

Here is our output:

["Apples", "Bananas", "Oranges", "Avocados", "Garlic", "Onions", "Chicken", "Lamb", "Eggs"]

15.2 - Referencing Items in a List

In Section 4.2, we looked at how to reference an index in a string. Referencing items in a list works exactly the
same way, except that instead of returning a character or set of characters, Python will return an item in the list.
Using our shopping list above, let's see what is in the 0 index:

>>> shopping_list = ["Apples", "Bananas", "Oranges", "Avocados", "Garlic", "Onions", "Chicken", "Lamb", "Eggs"]
>>> shopping_list[0]
'Apples'
>>>

“Apples” is in our 0 index. Just like in a string, the first item is considered to be at the 0 index, not the 1st.

If we had a much longer list and wanted to reference items at the end of the list, we could use the same format
that we used when referencing characters in strings:

>>> shopping_list[-1]
'Eggs'

15.3 - Appending Lists

Now that we've created our first list, let's look at some of the methods that we can use in Python to modify it.
We'll start with append(), which adds an item or many items to a list. Below, we'll create a new list called
new_list and then add a new element to it. Notice how the new element goes directly to the last index.

>>> new_list = ["P", "Y", "T", "H", "O"]


>>> new_list.append("N")
>>> print (new_list)
['P', 'Y', 'T', 'H', 'O', 'N']
>>>

15.4 - Extending Lists

Another method is extend(), which combines two lists. Below, we'll create two lists, list1 and list2, combine the
two and then print out list1. Watch what happens:

>>> list1 = ["A", "B", "C"]


>>> list2 = ["D", "E", "F"]
>>> list1.extend(list2)
>>> print(list1)
['A', 'B', 'C', 'D', 'E', 'F']

25
15.5 - Sorting Lists (Ascending)

A very useful method in lists is sort(). Bringing in our shopping list that we wrote earlier, let's sort the list in an
ascending alphabetical order:

>>> shopping_list = ["Apples", "Bananas", "Oranges", "Avocados", "Garlic", "Onions", "Chicken", "Lamb", "Eggs",
"Yogurt"]
>>> shopping_list.sort()
>>> print (shopping_list)
['Apples', 'Avocados', 'Bananas', 'Chicken', 'Eggs', 'Garlic', 'Lamb', 'Onions', 'Oranges', 'Yogurt']

Notice the index of Apples and Avocados in our original list and their index after the sort.

15.6 - Sorting Lists (Descending)

Just as we can sort the list in an ascending order, we can also sort in a descending order using sort(reverse =
True) as shown in the following example:

>>> shopping_list.sort(reverse = True)


>>> print (shopping_list)
['Yogurt', 'Oranges', 'Onions', 'Lamb', 'Garlic', 'Eggs', 'Chicken', 'Bananas', 'Avocados', 'Apples']
>>>

15.7 - Reversing

We can also reverse the order of lists freely, not specifically in an ascending or descending alphabetical order.
To reverse a list at any time, we can use the reverse() method. Let's print our list where we last left off; sorted in
an descending alphabetical order, starting with Yogurt and apply the reverse method to it:

>>> print(shopping_list)
['Yogurt', 'Oranges', 'Onions', 'Lamb', 'Garlic', 'Eggs', 'Chicken', 'Bananas', 'Avocados', 'Apples']
>>> shopping_list.reverse()
>>> print(shopping_list)
['Apples', 'Avocados', 'Bananas', 'Chicken', 'Eggs', 'Garlic', 'Lamb', 'Onions', 'Oranges', 'Yogurt']
>>>

15.8 - Counting

We can count number of occurrences of a specific item in the list using the count() method:

>>> shopping_list.count("Apples")
1

15.9 - Removing

If we do not want an element in a list, we can simply remove it using the remove() method:

>>> print (shopping_list)


['Yogurt', 'Oranges', 'Onions', 'Lamb', 'Garlic', 'Eggs', 'Chicken', 'Bananas', 'Avocados', 'Apples']
>>> shopping_list.remove("Onions")
>>> print (shopping_list)
['Yogurt', 'Oranges', 'Lamb', 'Garlic', 'Eggs', 'Chicken', 'Bananas', 'Avocados', 'Apples']
>>>

“Onions” is now removed from the shopping list.

26
15.10 - Popping

The pop() method is similar to the remove() method, except that rather than delete the item completely, pop()
will remove an item, but place it in another variable. Let's remove the 0 index, “Apples” from our original
shopping_list and “pop” it into another variable:

>>> shopping_list = ["Apples", "Bananas", "Oranges", "Avocados", "Garlic", "Onions", "Chicken", "Lamb", "Eggs",
"Yogurt"]
>>> takeapplesout = shopping_list.pop(0)
>>> takeapplesout
'Apples'

We created a new variable called “takeapplesout” and told Python to pop the 0 index out of our shopping list.
When we call “takeapplesout” we get “Apples” and if we call shopping_list, we'll see that “Apples” has been
removed:

>>> shopping_list
['Bananas', 'Oranges', 'Avocados', 'Garlic', 'Onions', 'Chicken', 'Lamb', 'Eggs', 'Yogurt']

27
TUPLES & DICTIONARIES
16.1 - Tuples

In the previous section, we looked at lists and some methods to modify them. The fact that we could append,
delete or change the values in a list at any time means that a list is a mutable container type, which in
programming means, it is able to be changed. Mutable container types, like lists are useful when we know that
our values will need to be modified or change later in our program. If we are sure that our values will not
change, and would like to use something very similar to lists, then using a tuple is a good option. Tuples are just
like lists, except that they are immutable (i.e. values within them cannot be changed) and use two parenthesis ()
instead of two square brackets []. Let's write a simple tuple to store the weights of 3 weightlifters:

>>> wlift = (85, 90, 88)


>>> tuple(wlift)
(85, 90, 88)

Notice our use of two parenthesis () and the tuple() method to call our “wlift” tuple.

We can use many of the same methods on tuples that we used for lists, except for those that would imply that
we are trying to change something in our tuple, like appending or changing the index (position) of a value.

16.2 - Dictionaries

In the physical world, the function of a dictionary is that it allows us to find a certain word and a corresponding
definition. In Python, a dictionary functions in almost the same way and is similar to a list or tuple. The only
difference is that instead of holding one or more values within a single variable in square brackets, dictionaries
hold one or more pair of variables, a value and its corresponding element called a key inside of curly braces {}.
The key is then used to reference the value. Note that unlike tuples, dictionaries are mutable. Let's create a
dictionary that holds the weight of 4 house items to better understand how dictionaries work:

>>> weight = {"Cup":2, "Phone":3, "Pot":4, "Vase" : "No Weight Recorded"}

We named our dictionary “weight” and assigned four values to it (Cup, Phone, Pot and Vase) along with
corresponding keys (2, 3, 4, No Weight Recorded). Notice that a colon : is used between the value and the key.
Notice also that strings are kept in quotation marks while integers are not. Now let's use the values() method to
see only the values in our dictionary:

>>> weight.values()
dict_values([4, 2, 3, 'No Weight Recorded'])

And the keys() method to see only the keys in our dictionary:

>>> weight.keys()
dict_keys(['Pot', 'Cup', 'Phone', 'Vase'])

16.3 - Deleting Items in a Dictionary

Dictionary items can be deleted using the del function, specifying the dictionary name and using a pair of
square brackets []:

>>> weight = {"Cup":2, "Phone":3, "Pot":4, "Vase" : "No Weight Recorded"}


>>> del weight["Cup"]
>>> weight
{'Pot': 4, 'Phone': 3, 'Vase': 'No Weight Recorded'}

28
16.4 - Adding Items to a Dictionary

Dictionary items can also be added by specifying the dictionary name followed by a pair of square brackets
with the new value name then an equals sign proceeded by the key. Since we deleted “Cup” in our last
example, let's add it back to our dictionary:

>>> weight["Cup"] = 2
>>> weight
{'Pot': 4, 'Cup': 2, 'Phone': 3, 'Vase': 'No Weight Recorded'}

Notice the format used to add “Cup” back. Notice also that Python did not use any particular order when
placing our item into the dictionary. In Python, unlike lists and tuples, dictionaries have no particular order.

16.5 - Combining Dictionaries

By using the update() method, we can update or combine one dictionary with another:

>>> weight
{'Pot': 4, 'Cup': 2, 'Phone': 3, 'Vase': 'No Weight Recorded'}
>>> other_items = {"Bottle" : 4, "Spoon" : 1}
>>> weight.update(other_items)
>>> weight
{'Pot': 4, 'Bottle': 4, 'Spoon': 1, 'Cup': 2, 'Phone': 3, 'Vase': 'No Weight Recorded'}

We created a new dictionary called “other_items” and used update() to add it to our weight dictionary.

29
FOR LOOP
17.1 - For Loop

Now that we understand if statements and lists, we can dive into the for loop. The for loop is a statement that
allows code to be repeatedly executed. Imagine that we want to take our shopping list that we wrote earlier and
do more with it than just modify or sort it, like evaluate and print specific information within it. We can use a
for loop to accomplish these types of tasks. Let's write a short program to give us only the items in the list that
start with the letter “A” and then evaluate what we did:

>>> for x in shopping_list:


if x[0] in "A":
print(x)

Apples
Avocados

We told the program to look into shopping_list and assigned a variable x for that task. We also told it to look for
an “A” in the [0] index of each item. It worked through the list and found that Apples and Avocados have an “A”
in the [0] index and gave those strings to x. Next, we simply printed the x variable.

Note that we could have used any for “task” variable that we wanted, not just x. We could have also written:

for things_that_start_with_A in shopping_list:

30
APPLY & PRACTICE
This Programmer is No Dodo

Directions & Starting Code:

Well, the word is out that you are a pretty talented programmer. Even the head of the local museum heard about
your skills and has asked for your help with a new program. The extinct bird exhibit is looking for a program
that will organize and sort through a large list of bird species and produce a list of those birds that are extinct.
There are two random lists that will need to be put together and one bird that needs to be added to the
combined list. Any bird that is extinct has an XT at the end of the name, preceded by a space. Use this to filter
out the extinct from the non-extinct in your program.

bird_list1 = ["Elephant Bird XT", "Woodcreeper", "Lyrebird", "King Island Emu XT", "Whistler", "Ovenbird",
"Bowerbird"]
bird_list2 = ["Dodo XT", "Scrubbird", "Upload Moa XT", "Oriole", "Cardinal", "Crested Shelduck XT",
"Amsterdam Duck XT"]

Task:

Write a program that first extends list2 to list1. Then append the extinct bird, “Red Rail” to list1. Notice that any
extinct birds end with a space followed by a “XT”. Next, use a for loop and if statement to search for the “X” in
the second-to-last index. Print a list of all extinct birds.

Solution:

Be sure to try as hard as you can and multiple times before looking at the solution, but if you do get stuck in a
loop, the solution is located in back of the book.

31
COUNTERS
18.1 - Counters

In Python, counters allow us to count how many instances of a particular operation we have done. We can print
these counters or use them for specific functions. Let's go back to the shopping list that we created earlier and
write a program that will count how many items we have in our list. We could simply use len(shopping_list) to
get the answer, but for the purpose of learning counter, we'll use the counter option:

shopping_list = ['Yogurt', 'Oranges', 'Onions', 'Lamb', 'Garlic', 'Eggs', 'Chicken', 'Bananas', 'Avocados',
'Apples']
counter = 0
for x in shopping_list:
counter = counter + 1
print (counter)

Output:

10

The program assigns 0 to the counter variable. A for loop is then used, with x as the variable to run through
each string in the list. Each time a string is referenced, counter becomes itself + 1. At “Yogurt” the counter
becomes 0 + 1, then at “Oranges” it becomes 1 + 1, then at “Onions”, 2 + 1 and so on. Finally, we print
whatever counter is by the end of the list.

Note that we do not have to use the word “counter” to keep track of the count. We could use any relevant
word, as long as we increment the value correctly (i.e. value = value + 1). In the next section, as we learn about
the while loop, this point will become clearer.

32
WHILE LOOP
19.1 - While Loop

In the previous sections, we learned that an if statement, together with else and elif can all be used to check if
certain conditions are true or not and execute a target statement based on those conditions. In Python, a while
loop can also be used to check if certain conditions are met, creating a loop that will keep on executing as long
as the condition is met. Let's look at some examples.

Let's say we would like to count and list the number of cars that are currently being finalized for shipping at a
car factory. When our program finds that 30 cars have been finalized, it tell us “All cars finalized. Ready to
ship.” It would be very difficult to write such a program using if, else and elif statements. Rather, take a look at
how the while loop can accomplish all of this in only 6 lines of code:

cars = 0
while (cars < 31):
print ("Car " + str(cars) + " is finalized.")
cars = cars + 1
else:
print ("All cars finalized. Ready to ship")

The program first assigns a 0 value to the cars variable. Then we use the while loop to check if cars is less than
31. As long as this condition is true, we ask it to print that “Car x is finalized” with x being the current count of
cars at the moment in the loop. Immediately after that, we add 1 to the current count of cars. FInally, when the
count reaches 30, the loop breaks because the condition is no longer true. When that becomes the case, the
else then last print statement is executed.

Let's look another program that uses a nested if statement with the while loop. Nesting is where one function of
the code is combined or inserted inside another, usually indicated by indentation.

We want the user to enter a specific number between 1 and 5. As long as the user does not get the right answer,
the program will keep asking for the number. If the user gets the number correct, then the program prints “You
got it” and then breaks. A break terminates the loop and continues to the next indented area.

while True:
guess = int(input("Please enter a number between 1 and 5: "))
if guess == 2:
print ("You got it!")
break

The program assigns an input to the guess variable, asking the user to enter a number between 1 and 5 (integer
only). Next, it uses an if statement to determine if the guess is true or not. If the answer is not “2” then the loop
continues. If the answer is “2” then the print statement is executed and the program breaks. If we did not use
the break, the program would print “You got it!” but keep asking us to enter a number:

Please enter a number between 1 and 5: 2


You got it!
Please enter a number between 1 and 5: 2
You got it!
Please enter a number between 1 and 5:

Now is a good time to practice what we know and see how well we understand while loops.

33
APPLY & PRACTICE
Four, No More

Directions & Starting Code:

BabyNames Inc. sends a weekly email to their subscribers giving new parents great ideas for baby names. They
usually have a special theme, like flowers, popular or religious names. Next week's theme is 4-letter names.
They need your help to write a program that will allow their staff to create 4-letter names, but nothing longer
and nothing shorter.

name = ("Please type a baby name: ")

Task:

Create a program that will ask the user for a name. The program prints “The name length is too short” if the
name is less than 4 characters, “The name length is too long” if the name is more than 4 characters and “That's
a valid name length” if the name is 4 characters exactly. After that, the program breaks. Use your knowledge of
the len() function, while True loop, if, elif and else to write the program. Don't forget to use escaping when
printing a string that has quotation or apostrophe marks within the sentence, such as in “That's a valid name
length”.

Solution:

Be sure to try as hard as you can and multiple times before looking at the solution, but if you do get stuck in a
loop, the solution is located in back of the book.

34
TRY & EXCEPT
20.1 - Exception Handling

As we continue to write more and more programs, it is a good idea to consider the errors that might come about
from a user not entering information in the way that our program was intended. For example, when we learned
about while loops, we looked at a program that asked a user for a number between 1 and 5. If you tried this
program in the shell interpreter, you may have found that if the user entered a symbol or letter, the program gave
an error:

Please enter a number between 1 and 5: a


Traceback (most recent call last):
File "/Users/Air/Documents/Python/IDLE Projects/counter1.py", line 2, in <module>
guess = int(input("Please enter a number between 1 and 5: "))
ValueError: invalid literal for int() with base 10: 'a'

Obviously the program wanted an integer (as we specified when we wrote the program), but the user entered
something else. Rather than just leave our program in the gutter and the user with a strange error message, we
can use exception handling to “customize” these errors. An exception is an error that is found within the
program. Exception handling is basically error handling; code that catches a single or range of possible errors
and sends the user information accordingly. Exception handling can clean up the program and limit the amount
of errors that users get. Using the 1-5 number program that we created earlier, let's see how exception handling
can help us inform the user that he/she should only enter a number. Notice how our previous program would
give a program error if the user entered “a”. This program will give an informative message instead.

while True:
guess = (input("Please enter a number between 1 and 5: "))

try:
number = int(guess)
except ValueError:
print('You must enter a number. Try again')
else:
if number == 2:
print ("You got it!")
break

Like it did previously, the program assigns an input to the guess variable, asking the user to enter a number
between 1 and 5. Next, and before we use our if statement, we set up our exception handling, using try, except
and else. We then convert guess into an integer and place it within the number variable. Now Python knows
that we are expecting only an integer. To ensure this, we use ValueError as the exception. ValueError is used
when a function receives information that is of the right type, but not the right value. It is one of many exception
errors that we can choose from in Python. If the program finds an error in the value entered, then “You must
enter a number. Try again” is executed along with guess (“Please enter a number between 1 and 5: “).

If try is not executed, then our program continues as it did before under the else, using an if statement to
determine if the guess is true or not. If the answer is not “2” then the loop continues. If the answer is “2” then
the print statement is executed and the program breaks. Notice again that if we did not use the break, the
program would print “You got it!” but keep asking us to enter a number:

______________________________________
For a complete list of exception errors, visit Python.org's exception page: http://docs.python.org/2/library/exceptions.html

35
USER-DEFINED FUNCTIONS
21.1 - User-Defined Functions

In Section 5, we looked at built-in functions and have used a few of them including print(), len(), str(), int() and
input(). These were helpful because they performed certain tasks for us without us having to actually program
them. For example, we did not have to program the len() function, telling Python how it should work before we
used it to get the length of an object. This is what makes Python a clearly object-oriented programming (OOP)
language.

Built-in functions have their purpose, but in Python programming, to get programs to do what we need them to
do and to reduce the amount of code that we write, we have to create functions of our own. Let's take a look at
how we can create a user-defined function in Python:

def model (car):


print (("The model of this car is: ") + (car))

model("Lamborghini Gallardo")
model("Tesla Model S")
model("Mercedes SL55")

The program first declares that this is a user-defined function by specifying def before all else. Next, we create a
name for our function, “model” and the name of the argument that the function will operate on, “car”. Notice
how we ended our def line with a colon (:) just like in if and else statements. If this colon is missing, the def will
not work. Next, we specify what our function does. In this case, our function simply prints, “The model of the
car is: ” and whatever will be fed into the argument, “car”. We can then use our function as we like, specifying
a different argument each time to be placed in “car”. When we run our code, we'll see:

The model of this car is: Lamborghini Gallardo


The model of this car is: Tesla Model S
The model of this car is: Mercedes SL55

Now let's use another built-in function call k_to_p() to convert kilos to pounds. Wait, there is no built-in
function called k_to_p! We made it up. That's fine through because we'll need it for our next program. Let's
build a weight converter program together to better understand how user-defined functions work. Our program
will ask the user to choose whether he/she would like to covert kilos to pounds or pounds to kilos. First, we
want to create 2 functions, one for kilos to pounds and another for pounds to kilos:

def k_to_p(weightk):
return weightk * 2.2

def p_to_k(weightp):
return weightp / 2.2

We'll call our kilos to pound function “k_to_p” and assign “weightk” to it. “weightk” will be what the user
enters. Next, we'll use return, which holds the result of the function. weightk * 2.2 is our calculation for k_to_p.
We'll do similarly for our pounds to kilos function. Next, we'll print the options and assign the input() choice as
an integer.

print ("Press 1 to convert kilos to pounds")


print ("Press 2 to convert pounds to kilos")
print ("Press 3 to exit the program")
choice = int(input())

______________________________________
Program continued on next page ...

36
Now we can begin our if statement, specifying that input should be a float. We were introduced to floats in
Sections 1 and 5. The float() function converts a string or a number to a float (decimal).

if choice == 1:
weightk = float(input("What is your weight in kilos: "))
print (k_to_p(weightk))
elif choice == 2:
weightp = float(input("What is your weight in pounds: "))
print (p_to_k(weightp))
else:
print ("Program ended")

If the user presses “1”, the input() is given to “weightk” which calculates according to the formula that we
assigned under def k_to_p. If the user presses “2”, the “weightp” does similarly and if the user presses another
button, the program ends.

Here is the output of our program:

Press 1 to convert kilos to pounds


Press 2 to convert pounds to kilos
Press 3 to exit the program
1
What is your weight in kilos: 65
143.0

If all of this makes sense, let's try a program of our own.

37
APPLY & PRACTICE
Now We're Cooking!

Directions & Starting Code:

SmokeyKitchenOnline publishes a variety of popular cooking videos via their YouTube channel. Recently, many
European and Asian subscribers have been writing to the channel asking about measurement conversions.
SmokeyKitchenOnline now wants a program for their website that converts cups to milliliters and vice versa, as
these are the two most popular request from subscribers.

print ("Press C to convert cups to milliliters")


print ("Press M to convert milliliters to cups")
print ("Press X to exit the program")

Task:

Create a program that will convert cups to milliliters and milliliters to cups. The program should ask the user to
enter a “C” for cups to milliliters, an “M” for milliliters to cups and an “X” to exit the program. If the user enters
any other character, the program will print “You must enter a C, M or X” and keep giving the user the chance to
enter a C, M or X without breaking. If the user does enter a measurement and the program converts it, the
program will break, not asking for another measurement.

Use your knowledge of the def, while True loop, if, elif and else to write the program. Be sure to indent all code
properly and don't forget to convert strings and floats correctly. You will also need to break the program at the
correct line. Note that you will not need to use error exceptions in this program.

Solution:

Be sure to try as hard as you can without looking at the solution, but if you do get stuck in a loop, the answers
are located in back of the book.

38
MODULES
22.1 - Modules

In the physical world, a module is a smaller part of a larger unit. By breaking down a large object into smaller
parts, more focus can be applied to details, which in turn benefits the unit as a whole. In Python, a module
works in exactly the same way, serving as a bit of code that performs a specific task. It can be referenced within
larger code to perform its designated task along with other modules and can come both pre-installed with the
IDLE, in which they simply need to be imported, or can created by the user. We will cover both types in this
section.

First, let's take a look at a common module called math and see how we can import and use it. In Python, there
is a method called sqrt() which returns the square root of an argument. To use it, we must first tell Python to
import the math module. If we do not, this is what we would get:

>>> sqrt(2)
Traceback (most recent call last):
File "<pyshell#161>", line 1, in <module>
sqrt(2)
NameError: name 'sqrt' is not defined

Python tells us that “sqrt” is not defined so let's import the math module and try it again:

>>> import math


>>> math.sqrt(2)
1.4142135623730951

39
CLASSES & OBJECTS
23.1 - Classes & Objects

To understand classes and objects, let's recall how the math module and sqrt() method worked. After we
imported the math module and went to write our sqrt() method, you may have noticed that the Python Shell was
trying to assist us with what should go into the parenthesis. This is because all of this information is already
defined within the math module and the parenthesis are expecting a certain pre-defined argument. Now
imagine that we are writing a program that deals with certain student information and we already know that
each new student variable that we create will need to hold specific information like age, grade, section, etc.
With classes, we can pre-define these fields and use them over and over again. Classes are user-defined and
define a set of attributes that act like a mold. Every time we use this mold and create a new instance of it, we
are creating an object. This concept of creating objects that work off this kind of mold is the main idea behind
object-oriented programming.

To get started, let's create a class that will hold student information. We'll create the mold which will keep the
name of the student, his/her age, grade and section. First, we must declare that this is a class and give the class a
name. In this case, we'll use the name “Student_Info”:

class Student_Info:

Next, we want to define a new function using def and give it an initialization method (written as __init__).
Recall how we defined an object as a new instance of a class. __init__ is simply a way to automatically
initialize the function when a new object is created. After __init__, we want to use self which will be the first
argument that the method works off of. The word “self” is not required, but an initial argument is:

class Student_Info:
def __init__(self, name, age, grade, section):
self.student_name = name
self.student_age = age
self.student_grade = grade
self.student_section = section

In the code above, we declared four variables and passed name, age, grade and section into each of them.
Next, we want to write a print function that will print all of the variables above in a string:

def displayStudent(self):
print("Name: " + str(self.student_name) + ", Age: " + str(self.student_age) + ", Grade: " +
str(self.student_grade) + ", Section: " + str(self.student_section))

Now, we want to create some objects that work off the Student_Info class (or mold) that we just created. We can
name the objects whatever we like:

student_1 = Student_Info("Ahmed", 15, 9, "A")


student_2 = Student_Info("Mohammed", 15, 9, "B")
student_3 = Student_Info("Daniel", 15, 9, "A")

Next, we'll use the displayStudent() function to display the student info:

student_1.displayStudent()
student_2.displayStudent()
student_3.displayStudent()

When we run this code, we should see:

Name: Ahmed, Age: 15, Grade: 9, Section: A


Name: Mohammed, Age: 15, Grade: 9, Section: B
Name: Daniel, Age: 15, Grade: 9, Section: A

40
DIRECTORIES
24.1 - Creating a Directory

In the next few sections, we will look at ways to create, modify and remove directories and files using Python.
This is an interesting part of programming because it allows us to manipulate data within our operating system
and see the results instantly.

To begin, we want to create a new folder on our desktop called “Wisdom” to add, modify and delete files in it
later. To start communicating with our operating system, we need to first import the os module, which allows us
to work with our current operating system. By doing so, we can perform operations on files located on our OS:

>>> import os

The os module can also be used for other important os-related operations. For example, if you wanted
to open an .exe program in Windows, you can use the os module to first access your operating system
and then os.system(“directory of exe”) to open that program from Python.

We can now create our first directory using the mkdir() method. Since we're using a Macbook Air and want to
create this folder on our desktop, we will use /Users/Air/Desktop as our directory. Be sure to specify your
desktop directory correctly when writing the code.

>>> os.mkdir("/Users/Air/Desktop/Wisdom")

In Windows, in order for Python to read the directory's backslashes correctly, we must tell Python to
read it as a raw string by putting an r immediately before the quotation (r"/Users/Air/Desktop/Wisdom").
Note that this will apply to all directory commands that we perform in this section for Windows.

If your desktop is in view, you should now see a folder called “Wisdom” on it.

24.2 - Removing a Directory

We can remove a directory using the rmdir() method. Let's remove the Wisdom directory that we just created:

>>> os.mkdir("/Users/Air/Desktop/Wisdom")

For the next few program examples, we'll want to save our work on our desktop in a folder called “Wisdom” so
let's create that again before continuing on to section 3.1.

>>> os.mkdir("/Users/Air/Desktop/Wisdom")

41
READING FILES
25.1 - Reading Files

In Python, files can be read and written to by first accessing the file using the open() file type and specifying
both the file directory and the mode, which tells Python how to open the file. There are many different modes in
Python, but throughout the next few sections, we will only be looking at five.

Before we look at a few examples of how to open and read a file, let's first create a text file in our Wisdom
folder and look at four different open modes. First, using Notepad, TextEdit or any other text editor, create a .txt
file in your Wisdom folder and name it “wisdom.txt”. Write the following text in the file:

Note the location of your text file. For the next few examples, we'll use Users/Air/Desktop/Wisdom/wisdom.txt
as our directory. Next, let's look at five different open modes, their functions and where the cursor is within the
file when they are called:

Mode Function Cursor Location During Read/Write


r Reads Start of file
r+ Reads and writes Start of file
w Writes Start of file
w+ Writes and reads Start of file
a Appends End of file

Now, let's create a variable called “inside_our_text” to open our file in and open our file using open() and
specifying the file directory, file name and the mode:

>>> inside_our_file = open("/Users/Air/Desktop/Wisdom/wisdom.txt", "r")

file directory mode

Now that we've told Python to access our file, let's use the read() method to begin reading parts it. We want to
read the first 12 characters in wisdom.txt:

>>> first_twelve = inside_our_file.read(12)


>>> print (first_twelve)

Notice that we've created a new variable called “first_twelve” and used the .open() function immediately after
the name of our open file variable. By specifying 12, we asked for the first 12 characters. Here is the output:

Early to bed

We can also use a with statement to open files. A with statement works in exactly the same way as the previous
code, but uses a more concise logic. Try running the following code:

>>> with open("/Users/Air/Desktop/Wisdom/wisdom.txt", "r") as inside_our_file:


first_twelve = inside_our_file.read(12)
print(first_twelve)

42
WRITING TO FILES
26.1 - Writing to Files

In the same way that we read files, we can also write to files using the open() file type and specifying both the
file name and mode. Keep in mind that if a file does not exist, you can also create it using open(). Let's delete
our current wisdom.txt file and recreate it using Python:

>>> new_saying = open("/Users/Air/Desktop/Wisdom/wisdom.txt", "w+")


>>> new_saying.write("When you see a person who has been given more than you in money and beauty, look
to those, who have been given less")
>>> new_saying.close()

Notice that we used the w+ method as well as a new method called close(), which simply closes the file after
we've accessed it. Closing the file will need to be done before you see the changes in the text file. We've now
successfully written our saying to our text file using Python:

Note that we can also use the with statement when we write to files:

>>> with open("/Users/Air/Desktop/Wisdom/wisdom.txt", "w+") as new_saying:


new_saying.write("When you see a person who has been given more than you in money ...")
new_saying.close()

Now let's use the append mode (see our modes chart on page 6) to add another saying to our file. First, we'll
need to declare this mode when we open our file for writing:

>>> with open("/Users/Air/Desktop/Wisdom/wisdom.txt", "a") as new_saying:

Notice that “w+” was replaced with an “a”. We can now append a new saying to our file:

new_saying.write("If the son of Adam had a valley of gold, he would desire another one")
new_saying.close()

If we check our text document at this point, we'll notice that the new saying comes directly after the previous
saying. This is because, as we read in our modes chart on page 6, when we use the append mode, the cursor
goes to the end of the last character in our file. We can fix this by creating a break using \n within our string. A
break is like hitting enter on your keyboard. It returns the cursor to the next line. Let's try our code again, with
the break at the start of our saying:

new_saying.write("\nIf the son of Adam had a valley of gold, he would desire another one")
new_saying.close()

We should now see the new saying on a different line:

43
FILE OPERATIONS
27.1 - Renaming Files

Along with reading and writing to files, we can also rename files using the .rename() method. Let's rename our
current “wisdom.txt” file to “wise_sayings.txt” using Python:

>>> import os

Now we can begin renaming our file:

>>> import os
>>> os.rename("/Users/Air/Desktop/Wisdom/wisdom.txt", "/Users/Air/Desktop/Wisdom/wise_sayings.txt")

Notice the format used in the rename operation and method. Our file should now be named wise_sayings.txt.

27.2 - Removing Files

We can also delete files using the remove() method. Let's delete our newly named “wise_sayings.txt” file using
Python:

>>> import os
>>> os.remove("/Users/Air/Desktop/Wisdom/wise_sayings.txt")

Notice the format used in the remove operation and that the os module must also be imported (if not previously
imported). It is also important to point out that Python does not do anything more than remove the file entry
from the disk, freeing up space. How and in which way the file deletes depends on your filesystem's setup and
the file may or may not go directly to Trash or the Recycle Bin.

27.3 - Getting FIle Info

Let's say that we wanted Python to give us back info on the file that we've just opened or wrote to. There are a
number of attributes, called file object attributes that we can use to get current file information.

Attribute Function
.name Returns the name of the file
.closed Checks to see if the file is closed and returns a boolean
.mode Returns the mode used

Let's use all three attributes listed in the chart above to give us information on a text file that we'll create in our
Wisdom folder. First, let's create the file within the folder:

>>> new_saying.write("An apple a day, keeps the doctor away")

Now, let's create a variable called “check”, open our file and use the .name, .closed and .mode attributes to get
the name and mode of the file, as well as to check whether that file is currently closed or not:

>>> check = open("/Users/Air/Desktop/Wisdom/wisdom.txt", "wb")


>>> check.name
/Users/Air/Desktop/Wisdom/wisdom.txt
>>> check.closed
False
>>> check.mode
wb

44
APPLY & PRACTICE
Logging the Login

Directions

Your school is creating a new automated lunch system that allows students and parents to choose tomorrow's
lunch items from an online menu. You have been asked to write the login portion of the program. The 4-digit pin
for the system changes everyday with tomorrow's pin being 6572.

Starting Comments:

# Import os, make system_info directory and open login_attempts.txt file in append mode

# Create tomorrow's pin variable and user input variable

# Create while loop and check

# Create nested if and else within loop that also prints to the text file

# Close file and break loop after else statement

Task:

Use your previous knowledge of while True, if and else statements, as well as your knowledge of creating and
writing to files to create a simple login program that will ask the user for the 4-digit pin. Each time the user
enters a wrong pin, the programs prints “Incorrect pin” and asks them to try again, but also writes “Login failed”
on a new line (each time) in a text file named “login_attempts.txt” in a folder named “system_info”s. Finally, if
the user enters the correct pin, the login_attempts.txt file closes and the program prints “Welcome. You must be
hungry”. You must create the directory and file directly from your program.

Solution:

Be sure to try as hard as you can without looking at the solution, but if you do get stuck in a loop, the answers
are located in back of the book.

45
CSV FILES
28.1 - Working with CSV Files

Python can also work with CSV files. CSV (Comma Separated Values) files are a common spreadsheet export
and import format that separates row and column cell information with commas (instead of within cells). To get
a better look at how a CSV file looks and works, let's create a simple spreadsheet file using our spreadsheet
program and then convert it to a CSV:

We've created a spreadsheet using LibreOffice that contains mock student information within 5 rows and 3
columns. We now want to save our file as a CSV text file. If the program prompts you for a format to save in, be
sure to choose Unicode (UTF-8).

Saving in unicode allows us to save our file as text saving ordinary readable characters such as
characters, digits, punctuation, and some special characters such as tabs and line breaks. A binary file
on the other hand contains only binary characters, which are a collection of 0s and 1s.

Notice how the information that was once separated by cells is now separated by commas; hence the name
Comma Separated Values.

Since we've saved our file in unicode, we must tell Python to read it as such. To do this, we can use the rt
mode, which will read our file as text.

Mode Function Cursor Location During Read/Write


rt Reads file as text Start of file
rb Reads file as binary Start of file

Now, we want to read and print our information from our CSV onto our Python program. First, let's import the
CSV module:

import csv

46
Now, let's use our with and open statement to open our file:

with open("/Users/Air/Desktop/student_list.csv", "rt") as student_info:

Next, we want to use the reader object, which will run over each line in our CSV file. We'll use reader with the
for loop to get a variable x, with x being each new line:

reader = csv.reader(student_info)
for x in reader:
print (x)

When we run our code, we'll see:

['Name', 'Phone', 'Grade Level']


['Ahmed', '0504353544', '6']
['Noah', '0509442135', '4']
['Daniel', '0561039454', '7']
['Abdur-Rahman', '0501119834', '1']

We can also write to CSV files using writer instead of reader. Let's see how we can append a new row of
student information to our CSV file. We'll want to use the a mode in this case:

import csv
with open('/Users/Air/Desktop/student_list.csv', 'a') as student_info:
writer = csv.writer(student_info)
writer.writerow(["Ali", "0504325923", "6"])

Notice how we've used the writer object as well as a new method called writerow to append content held
within it to a new row. Also, notice the format that we've used for our data. If we look at our CSV file now, we'll
see the following:

Name,Phone,Grade Level
Ahmed,0504353544,6
Noah,0509442135,4
Daniel,0561039454,7
Abdur-Rahman,0501119834,1
Ali,0504325923,6

47
PYTHON GUI
29.1 - Python GUI

Up until now, you've been using either the shell or IDLE text editor to build, save and run code. Though you
may have seen the results of your programs in the shell or IDLE text editor, the program is missing the very
important “face” that we would expect from any program. For example, when you open up Microsoft Word,
Photoshop or Adobe Reader, you don't see a bunch of code or a code-like interface. You see a window with
icons, graphics and navigation. This whole design is called a GUI. GUI stands for Graphical User Interface and
gives programs a sort of face, complete with icons, graphics, windows and navigation.

29.2 - Tkinter

The Python 3.3.2 IDLE comes installed with a GUI toolkit called Tkinter. We can use Tkinter by importing it at
the very start of our program and then importing everything from the toolkit. Just as in many other programs, an
asterisk (*) allows us to call everything. In this case, we'll import everything from tkinter using the following
code:

from tkinter import *

Now that we've imported Tkinter and everything in it, let's create a window of a certain height and width. First,
we want to create our window root by giving it a name. We'll reference this root over and over again to tell
Python which window we are referring to as we write our code. We'll name our root firstGui:

firstGui = Tk()

29.3 - Window Size

We can now begin to add features to our GUI window such as .geometry(), which will size the window.

firstGui.geometry("400x120")

Notice that the x coordinate (width) comes first followed by the y (height). Notice also how we use the
character “x” between the width and height.

29.4 - Title Bar

Now, we can give our main window a title, such as the title bar that you've seen in Windows or Mac programs.
We'll call our window, “Are We There Yet?” and code it as follows:

firstGui.title("Are We There Yet?")

When you build and run your program, you should now see something like this:

29.5 - Background Color

We can use the .configure() method and the background option to set a background color:

firstGui.configure(background="#FFFFFF")

48
29.6 - Creating Labels

In Python, we can add widgets like labels or images to our program window to make it more user-friendly. A
widget is a GUI component that enhances the UX (user experience). Labels are simply text or images placed
within the window. To create a label, we must first give it a name and assign the function label() to it. Next,
we'll need to specify the text that we want to be displayed inside of our label:

firstLabel = Label(text="Welcome")

29.7 - Positioning Labels with .place()

If you try to run the code above, you will notice that nothing will appear in the window. This is because
firstLabel needs a location within our program window before we can see it. If we wanted firstLabel to be 30
pixels from the left of the window and 30 pixels down from the top, we can do this using a geometry manager
called .place() and specifying our coordinates:

firstLabel = Label(text="Welcome").place(x=30,y=30)

Notice that the .place() method goes at the end of our line of code and that the x coordinate is specified first.

29.8 - Positioning Labels with .grid()

We can also place our objects within the window in a grid format by using the the .grid() geometry manager
and specifying the row(s) and column(s) that we want our content to appear in. Let's position our firstLabel next
to a new label and use the .grid method to position them:

firstLabel = Label(text="Welcome").grid(row=0,column=0)
secondLabel = Label(text="Benvenuto").grid(row=0,column=1)

Notice that the 1st row is considered to be the 0th row. We then created 2 columns within that row by assigning
firstLabel to the 0th column and secondLabel to the 1st. If we run the program, we should see something like this:

We can control how cells span across rows or columns columnspan and rowspan arguments within our .grid
method. For example, if we had 3 rows and 3 columns in a grid and wanted the top row to span across all 3
columns, we would replace our normal row and column code with the following:

.grid(columnspan=3)

Also, we can also push the contents of a cell to the top (North), right (East), bottom (South) or left (West) of the
cell itself using a sticky argument within our .grid method: An example would be .grid(stricky=E).

49
29.9 - Positioning Labels with .pack()

Another geometry manager is .pack(), which can lay our labels out one after the other within the container that
it is contained in. Two important arguments that the method takes are fill and side. Let's see how these work:

firstLabel = Label(text="Welcome").pack(side=TOP)
secondLabel = Label(text="Benvenuto").pack(side=LEFT)

Using side within .pack() will send “Welcome” to the top and “Benvenuto” to the left:

If we add .fill() with an argument of X to “Welcome”, but not to “Benvenuto”, this will allow “Welcome” to
“follow” me as the window is expanded. “Benvenuto” would stay where it is, even as the window expands:

firstLabel = Label(text="Welcome").pack(side=TOP,fill=X)
secondLabel = Label(text="Benvenuto").pack(side=LEFT)

We could also use Y to allow the label to “follow” the window expansion vertically.

29.10 - Formatting Labels: Foreground

Color usually makes everything, including GUIs more appealing. In Python, we can add color to our labels
using the fg (foreground) and bg (background) variable and specifying the desired color:

firstLabel = Label(text="Welcome",fg="#990033").place(x=30,y=30)

Notice the format of the fg variable and that we used a hex triplet of #990033 to get the color red.

A hex triplet is a six-digit number used in web design languages to represent colors. Each digit can
contain a number, from 0 to 9 or letter, from A to F and specifies how intense to make either the red,
blue or green. When these are combined in a 6-digit code, we get a specific color.

50
29.11 - Formatting Labels: Background

Now that we've given our label a color using fg (foreground), let's change the background color to a light grey:

firstLabel = Label(text="Welcome",fg="#990033",bg="#EEEEEE").place(x=30,y=30)

Notice the format of the bg variable and that we used a hex triplet of #EEEEEE to get the color grey.

29.12 - Formatting Label Text

We can also change the font of the label using font=() as an argument within out Label() function.

firstLabel = Label(text="Welcome",font=("Verdana",20)).place(x=30,y=30)

Notice how we used two arguments: the font type and size, separated by a comma.

29.13 - Displaying Images in Labels

Just as we can add labels and text to our program window, we can also add images. In earlier versions of
Python, we could use a large variety of images formats by simply downloading and installing an additional
library called the Python Imaging Library (PIL). PIL has yet to be released for Python 3.3.2 (at the time that this
book was written), but Python 3.3.2 does allow us to use .gifs without the PIL. As we continue to write programs
and use images throughout the next few sections, be sure to convert any images that you plan on using into
.gifs.

To better understand how images can be imported and used, let's rewrite the “To Drive or Not to Drive”
program that we wrote in our previous book, Guide to Programming in Python 3.3.2. As we rewrite the
program, we'll use what we have learned so far about Tkinter, labels and the .place method to give our program
a GUI.

To get started, let's convert our student driver image to a .gif. Choose any 118 by 120 pixel image to be your
student driver image. Next, let's get the basics of the window up by importing the entire Tkinter library,
assigning a name for the window, giving it a geometry (size) and giving it a title:

from tkinter import *


driverGui = Tk()
driverGui.geometry("300x180")
driverGui.title("To Drive or Not to Drive")

Next, let's declare a new variable and use the PhotoImage() function to tell Python where our image is:

51
driver = PhotoImage(file="/Users/Air/Desktop/stu_driver.gif")

Next, let's create a new label variable called label_1 to hold our image:

label_1 = Label(image=driver)

Finally, let's place our label 30 pixels from the left and 30 pixels from the top:

label_1 = Label(image=driver).place(x=30,y=30)

Our final code looks something like this:

from tkinter import *


driverGui = Tk()
driverGui.geometry("300x180")
driverGui.title("To Drive or Not to Drive")
driver = PhotoImage(file="/Users/Air/Desktop/stu_driver.gif")
label_1 = Label(image=driver)
label_1 = Label(image=driver).place(x=30,y=30)

When we run our code, we should see the following:

29.14 - Buttons

A button is another useful widget that be added to our GUI. Buttons are clickable objects within our GUI
window that run or execute code. In Tkinter, the code for buttons resembles the code for labels:

button_1 = Button(text="Continue").grid(row=1,column=1)

Notice that the button has a name, text and a location using the grid method.

29.15 - Entry Boxes

An entry box is another widget that be added to our GUI. Entry Boxes, also known as text boxes, take
arguments that the user enters. Imagine entry boxes like the input() function, except with a GUI face. In Tkinter,
the code for an entry box also resembles the code for a label or a button:

entry_1 = Entry(textvariable = year).grid(row=1,column=1)

Notice that the entry has a name and location, but also holds a variable called textvariable that will hold the
information that the user enters. textvariable comes pre-installed in Python and will need to be used to hold the
variable that being entered into the entry box. In the code above, textvariable will hold a variable that we made
up called year.

52
29.16 - Coding with Entry Boxes and Buttons

Now that we've understood buttons and entry boxes, let's rewrite our “To Drive or Not to Drive” and replace
the process, that formerly used input() and our enter key, with an entry box and buttons.

First, we want to delete a lot of the code from our program that may confuse us as we write this program. We
also want to use comments so that we can stay more organized and on track as we code. Modify your starting
code so that it looks something like this:

from tkinter import *


driverGui = Tk()
driverGui.geometry("300x100")
driverGui.title("To Drive or Not to Drive")

Next, let's have a look at the original code for “To Drive or Not to Drive” that we wrote in our previous book.
Do not import this code into our new program yet, but let's have a look at it here for reference only:

name = input("Please enter your first name: ")


year = input("Please enter your 4-digit year of birth: ")

date_of_birth = int(year)
if date_of_birth < 1995:
print ("Welcome " + str(name))
else:
print ("You are not old enough to register")

To get this code to work using our new format, we will first need an entry box and a button. Next, we'll need to
create a function that will hold our whole check process. Let's create one called ageprocess and nest our if and
else statement within it. Note that instead of printing our information to the screen using print() as we did
before, we will output the answers to labels that we will create and position in the program window. We also
want to create a variable that will hold whatever the user enters into the entry box.

Let's break down our code step-by-step so that we can understand it better. First, we want to create the entry
box and button and position them in a grid format next to one another:

year_entry = Entry(textvariable = year).grid(row=0,column=0)


process_button = Button(text = "Check", command = ageprocess).grid(row=0,column=1)

We've called our entry box year_entry and assigned a variable called year to it. Remember that in order to tell
Python that we are entering some sort of text, we must use textvariable. Next, we've placed it in the 0th row and
0th column.

Next, we've called our button process_button, gave it some text and a position at the 0th row and 1st column.
We've also given it a function to process called ageprocess, which we will create now. Notice that we've used
the straight-forward word “command” to tell this button which function to process.

Now we want to create our ageprocess function. We can do this using the steps that we covered in our previous
book:

def ageprocess():
dob = year.get()
if dob < 1995:
label_1 = Label(text="Welcome").grid(row=1,column=0)
else:
label_1 = Label(text="You are not old enough to register").grid(row=1,column=0)
return

53
year_entry = Entry(textvariable = year).grid(row=0,column=0)
process_button = Button(text = "Check", command = ageprocess).grid(row=0,column=1)

We first give our function a name. In this case, ageprocess(). Next, we attach a .get() method to our year variable
which will get whatever the user enters into year (in our year_entry entry box below).

Then, we write our if statement as normal, as we did in previous programs, except that instead of using print() to
show results, we create a label, called label_1 instead where we output the various statements to be printed. We
also position these to appear in the 1st row, 0th column, which will place them underneath our entry and button.

At this point, we're all set, but if you try to run the code, you'll get the following error:

NameError: name 'year' is not defined

We haven't told python that year, which is entered into year_entry is to be processed as an int. We can do this
by adding the following after our function and before our entry box:

def ageprocess():
dob = year.get()
if dob < 1995:
label_1 = Label(text="Welcome").grid(row=1,column=0)
else:
label_1 = Label(text="You are not old enough to register").grid(row=1,column=0)
return

# This is where we tell Python that year is an int


year = IntVar()

year_entry = Entry(textvariable = year).grid(row=0,column=0)


process_button = Button(text = "Check", command = ageprocess).grid(row=0,column=1)

Combine this code with the initial starting code from above and you should see something like this:

Congratulations! You've written your first Python program as a GUI. Your final code, complete with comments
should look something like this:

from tkinter import *


driverGui = Tk()
driverGui.geometry("300x100")
driverGui.title("To Drive or Not to Drive")

# This is where we define our ageprocess function


def ageprocess():
dob = year.get()
if dob < 1995:
label_1 = Label(text="Welcome").grid(row=1,column=0)
else:
label_1 = Label(text="You are not old enough to register").grid(row=1,column=0)
return

54
# This is where we tell Python that year is an int
year = IntVar()

# This is where we place our entry box and button


year_entry = Entry(textvariable = year).grid(row=0,column=0)
process_button = Button(text = "Check", command = ageprocess).grid(row=0,column=1)

29.17 - Frames

Within a GUI window, it is common to see buttons, images and other widgets organized in a type of grid where
one area contains a menu for example while another contains buttons. These areas are usually frames. Frames
allow us to organize widgets within other widgets, giving us a far more friendly GUI. Let's look at a few
examples of how frames work.

First, we'll import the following starting code:

from tkinter import *


frameGui = Tk()
frameGui.geometry("400x200")
frameGui.title("2-Frame Window")

Next, we'll create a variable to hold our first frame called frame1 and specify a height, width and background
color. We'll also pack it and specify the padding, which is the space around the frame in relation to the other
frames around it. If we use padx, this specifies the padding on the x axis, from the left side of the window; pady
specifies the padding from the top.

frame1 = Frame(height=100, width=100, background="#999999")


frame1.pack(fill=X, padx=5, pady=5)

Let's create another, darker frame:

frame2 = Frame(height=100, width=400, background="#555555")


frame2.pack(fill=X, padx=5, pady=5)

If we run our code, we'll see two frames within our window.

29.18 - Buttons Within Frames

If we would like to add a button (or any widget) to a frame, we'll first create a button as we did in the section
above, then put the name of the frame that we want to target as our first argument. Let's import the code that we
left off with in the frames section:

from tkinter import *


frameGui = Tk()
frameGui.geometry("400x300")
frameGui.title("2-Frame Window")
frame1 = Frame(height=100, width=400, background="#999999")
frame1.pack(fill=X, padx=5, pady=5)
frame2 = Frame(height=100, width=400, background="#555555")
frame2.pack(fill=X, padx=5, pady=5)

Then add frame1 as an argument of Button():

frame1button = Button(frame1, text="Button 1", bg="#999999")


frame1button.grid(row=1, column=3)

55
And do the same with the 2nd button:

frame2button = Button(frame2, text="Button 2", bg="#555555")


frame2button.grid(row=1, column=3)

If we run our code, we should see:

You may notice that even though a background color was specified for each button, in OS X, the color does not
display. This is just how OS X and Tkinter work together at the moment. The button background color will
display in Windows:

29.19 - Interaction Between Frames

We can also interact between frames by simply using the desired method along with the frame name. Using the
same starting code that we used in the previous section, let's add two user-defined functions that will change
the background color of each frame when a button is clicked:

def frame1color():
frame1.config(background="#555555")
return

def frame2color():
frame2.config(background="#999999")
return

frame1button = Button(frame1, text="Change Frame 2 Color", background="#999999", command=frame2color)


frame1button.grid(row=1, column=3)
frame2button = Button(frame2, text="Change Frame 1 Color", background="#555555", command=frame1color)
frame2button.grid(row=1, column=3)

56
APPLY & PRACTICE
We're Still Cooking!

Directions

SmokeyKitchenOnline publishes a variety of popular cooking videos via their YouTube channel. A few months
ago, they approached you with a program request. The issue was that many European and Asian subscribers
were writing to the channel asking about measurement conversions. SmokeyKitchenOnline and their
subscribers loved your program and now want to see it as an application. Remember, they want a program that
converts cups to milliliters and vice versa, as these are the two most popular request from subscribers.

Starting Comments:

# Import and initial window setup


# Window is 411 pixels by 140 pixels
# Title of window is "Measurement Converter by SKO"

# This is where we declare the c_to_m function


# which gets the cups from an entry box and multiples it by 236.588

# This is where we declare the m_to_c function


# which gets the milliliters from an entry box and divides it by 236.588

# This is where we tell Python that cups and mils are ints

# This is where we place our .gif image that is 404 pixels by 57 pixels

# This is where we place our cups label, entry box and button to convert to milliliters

# This is where we place our milliliters label, entry box and button to convert to cups

Task:

Create a GUI program that will convert cups to milliliters and milliliters to cups. Use your previous knowledge
of def and Python arithmetic operations as well as your knowledge of GUI window setups, the .grid() method,
labels, buttons, images and a 404 px by 57 px image of a kitchen to recreate a GUI that resembles the program
shown here:

Solution:

Be sure to try as hard as you can without looking at the


solution, but if you do get stuck in a loop, the answers
are located in back of the book.

Challenge Yourself:

Try creating the same program again. This time, use frames and every time a conversion is made, record the
value entered in a CSV file. After a few conversions, check your CSV file to ensure that all values are recorded.

57
DIALOG BOXES
30.1 - Creating Dialog Boxes in Tkinter

A dialog box (also called a message box) is a program pop-up window that is used to both alter or warn the
user, prompting him/her to press “Ok” when the message is read and ask the user a question, prompting a “Yes”
or “No” response. Dialog boxes can be very helpful in navigating around a program and Tkinter's messagebox
module is an excellent and easy tool to create different types of dialog boxes. The messagebox module is
automatically imported when you import everything or * from tkinter.

Let's go ahead and modify our We're Still Cooking! program from the previous section by adding an Exit button
that will open a dialog box prompting the user to confirm the exit. If the user clicks “Yes” the program will close
and if the user clicks “No” a different process will occur. We'll first import the starting code from our program,
expanding the height to 150:

from tkinter import *


smokeyGui = Tk()
smokeyGui.geometry("411x150")
smokeyGui.title("Measurement Converter by SKO")

Next, we'll declare our conversion functions as we did in the original program:

def c_to_m():
conversion1 = cups.get() * 236.588
label_1 = Label(text=conversion1).grid(row=3,column=2)
return

def m_to_c():
conversion2 = mils.get() / 236.588
label_1 = Label(text=conversion2).grid(row=3,column=2)
return

Now, we'll create our exit button function that will either direct the user back to the program or exit the
program via a .askquestion() dialog box. The .askquestion() dialog box is used to ask the user a yes or no
question. Other types, like the .showinfo() or .showwarning() dialog boxes are used to show information to or
give the user a warning. We'll attach .askquestion() to messagebox and give the method an argument of (1) our
dialog box title, (2) our message within the dialog box and (3) the icon that we wish to use for this dialog. We
can choose between an “error”, “info”, “question” or “warning” icon:

def exitit():
check = messagebox.askquestion("Exit", "Exit the Program?",icon="warning")
if check == "yes":
smokeyGui.destroy()
else:
again_label = Label(text="Please try again").grid(row=3,column=1)
return

Next, we'll check if our variable is equal to “yes” (the default true answer to the askquestion dialog box). If yes,
we'll use the .destroy() method with our root variable to exit our program. If no is clicked, we'll print a label on
our main program window telling the user to try again.

We'll then continue with our code and add the exit button with the command to process the exitit function:

cups = IntVar()
mils = IntVar()

kitchen = PhotoImage(file="/Users/Air/Desktop/smkitch.gif")

58
img_label = Label(image=kitchen).grid(columnspan=3)

cup_title = Label(text="Cups: ").grid(sticky=E)


cups_entry = Entry(textvariable = cups).grid(row=1,column=1)
cups_process = Button(text="Convert to Milliliters",command=c_to_m).grid(row=1,column=2)

mil_title = Label(text="Milliliters: ").grid(row=2,column=0)


mil_entry = Entry(textvariable = mils).grid(row=2,column=1)
mil_process = Button(text = "Convert to Cups",command=m_to_c).grid(row=2,column=2)

exit_process = Button(text = "Exit",command=exitit).grid(row=3,column=2)

When we run our program and click Exit, we should get a dialog box with a warning icon and a prompt to click
Yes or No:

If we click “Yes”, the program exits. Otherwise, a label is printed on our main program window:

59
MENU BARS
31.1 - Creating Menu Bars in Tkinter

A menu bar is an area in a GUI where the user is able drop-down a selection of menu options. In OS X, the
menu bar that accompanies the desktop looks something like this:

Menu bars are extremely important, if not essential and help the user to navigate around the most important
parts of the program. Just like the messagebox feature of Tkinter, the Menu() function is automatically imported
when you import everything or * from tkinter. Let's create a simple menu bar for our We're Still Cooking!
program. First, let's import the starting code up until the title:

...
smokeyGui.title("Measurement Converter by SKO")

Next, we'll create a new menu instance by creating a variable and assigning Menu() to it. Menu() takes our root
window as the argument. This will create the actual, but now empty menu bar. To display the menu, we'll use
the .config() method with an argument of menu=the name of our menu.

smokey_menu = Menu(smokeyGui)
smokeyGui.config(menu=smokey_menu)

After this, the creation of the main menu titles and their cascading menu items are easy. For every main menu
item that we want in our menu bar, we'll create a variable and assign Menu() to it, with the name of our menu
as our argument. If we want to see File and About in our menu bar, we'll simply do the following:

file_dd = Menu(smokey_menu)
help_dd = Menu(smokey_menu)

Now that we've declared variables for our menu items, we'll use the .add_cascade() method to create the actual
menu items. Cascade is a good word for the method because from each of these items, other items will “pour”
down in a sequential manner. Notice how the method takes the name to display and the target menu item as
arguments:

smokey_menu.add_cascade(label="File", menu=file_dd)
smokey_menu.add_cascade(label="Help", menu=help_dd)

Lastly, for every menu item that we want to drop down from the main menu items, we'll use the
.add_command() method with a label and a command as its arguments. In this case, we'll exit our program
with Quit and run a function called alerter that displays a dialog box for our About:

file_dd.add_command(label="Quit",command=smokeyGui.destroy)
help_dd.add_command(label="About",command=alerter)

When we add the rest of the code from our We're Still Cooking! Program, we should see the following:

60
31.2 - Customizing Menu Bars

We can also add other types of menu items to our menu bar such as a separator or an icon to the left or right of
our menu items. A separator is a thin, usually gray bar that separates items in a drop down menu to make
related menu items more distinct. Let's add a separator between our Quit and Another Item in our File menu
using the .add_separator() method:

file_dd.add_command(label="Quit",command=smokeyGui.destroy)
file_dd.add_separator()
file_dd.add_command(label="Another Item",command=anotherfunction)
help_dd.add_command(label="About",command=alerter)

We can also add icons to accompany items in our menu. You may have noticed that these icons, especially in
OS X give the program menu a very unique design. To add an icon to our image, we must first create a
PhotoImage variable as we did with Tkinter previously. After that, we'll use the .add_command() method with
label, image and compound as an argument:

pc_image = PhotoImage(file="/Users/Air/Desktop/computer.gif")
file_dd.add_command(label="Another Item", image=pc_image, compound="left",command=anotherfunction)

61
EVENTS & BINDING
32.1 - TKinter Key Events

So far, we've been using the mouse to select and click widgets. You may have noticed that when you press enter
or return after entering a value into an entry box, nothing happens. This is because in Python, and in this case,
Tkinter, no click or key press event was used in our code. An event is an action from the user like a click of a
key, mouse button or even entering a window. When we create an event, we can bind it to functions and
methods. This is called binding the event. Let's look at an example of how we can bind the return key event (or
any other key) to an entry box, allowing us to click a button or conveniently press enter to process our function.
We'll first import some starting code:

from tkinter import *


dayConverter = Tk()
dayConverter.title("Days to Hours")

Next, we'll create two user-defined functions; one for our key press and one for our normal button click. These
will just simply convert the entered value of days into hours:

def key(event):
conversion = daysentry.get() * 24
label1 = Label(text=str(conversion) + " hours").grid(row=2,column=0)
return
def normal():
conversion1 = daysentry.get() * 24
label1 = Label(text=conversion1).grid(row=2,column=0)
return

Notice that we used event as the argument for our key function. Next, we'll declare our textvariable daysentry
as an int variable:

daysentry = IntVar()

Now, we'll go ahead and create our labels and entry boxes; however, right after our entry function (days), we'll
use the bind method to bind the return key to days. Instead of using command as we do with our button, our
“command” for the return key comes right after <return>:

Label(text="Days: ").grid(row=0,column=0)
days = Entry(textvariable=daysentry)
days.bind("<Return>",key)

We are not limited to the <return> key of course. We can also use <BackSpace>, <Shift_L>, <Alt_L>,
<Pause>, <F1> - <F12>, <End>, <Up>, <Down>, <Left>, <Right>, <Insert> and other keys. We can
also create key combinations like <Shift-Up>, allowing us to hold down Shift and then press Up.

Next, we'll grid days and finish our button as normal:

days.grid(row=0,column=1)
submit_button = Button(text="Convert",command=normal)
submit_button.grid(row=1,column=0)

If we run our program, we can now use the enter key or click Convert to run our program:

62
WORKING WITH DATABASES
33.1 - Python & SQLite3

A database is a software product whose primary function is to store and retrieve data. A popular database
system is Oracle. Another is Microsoft SQL Server, which uses the SQL language to insert, query, update, delete
and modify data.

Throughout this section, in order to help us understand more about how Python can interact with databases,
we'll focus on a small, serverless and zero-configuration database engine named SQLite3.

33.2 - Installing SQLite3 on Mac OS X

Just like Python itself, SQLite3 comes pre-installed on Mac OS X. To check your version, simply open Terminal
and type sqlite3:

sqlite3
SQLite version 3.7.13 2012-07-17 17:46:21
Enter ".help" for instructions
Enter SQL statements terminated with a ";"

SQLite can also be downloaded as a shell. Visit http://www.sqlite.org/download.html for more information.

33.3 - Installing SQLite3 on Windows

SQLite can be downloaded as a shell for Windows. Visit http://www.sqlite.org/download.html

33.4 - SQLite: Creating a Database

For our next program, to demonstrate how to create, enter, store, retrieve and delete information from a
database using sqlite3, we'll create a mock inventory program for a suit boutique. The complete program will
stretch across the next few sections, so be sure to consider the next few sections as project-based instruction
and follow along accordingly. To start, we'll first create our database directory by creating a folder on the
desktop called “store_info” where we will store our database and table, the area of our database where fields
are held, organized in rows and columns. Next, we'll use Terminal or Command Prompt to create our database
and table. Open Terminal and type in “sqlite3” followed by the directory of the folder that will hold the
database. At the end of the directory, type a name for the database followed by .db. In this case, we'll call our
database “sdata.db”:

$ sqlite3 /Users/Air/Desktop/store_info/sdata.db

At this point SQLite will start, waiting for our next instruction:

SQLite version 3.7.13 2012-07-17 17:46:21


Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>

33.5 - SQLite: Creating a Table

Now we'll go ahead and create a table by typing “create” then “table” then “storedata” (the name of the table)
at the sqlite prompt. Within the parenthesis that follow, we'll create a few columns. These work like the
columns in Excel or any other spreadsheet program; data will be organized underneath them. For our database,
we want to have an item number (item_no), item name (item_name) and item price (item_price):

create table storedata(item_no, item_name, item_price);

63
If you now open your student_data folder, you should see that a database named sdata.db has been created.
This database consists of a table named “storedata” which holds three columns: item_no, item_name and
item_price. It is also worth noting that we could specify the type of data that we are entering. For example, if we
know that item_no will be an integer, name a string and price a float, we could write the same line in this way:

create table storedata(item_no INTEGER, item_name TEXT, item_price FLOAT);

64
WRITING TO DATABASES
33.6 - SQLite3 Databases: Writing

Now that we've created a database and table, let's see how we can interact with it using Python. In IDLE, we
start our code with the very familiar tkinter module and now, the sqlite3 module as well. We'll also create a root
variable, geometry and title:

from tkinter import *


import sqlite3
sstore = Tk()
sstore.geometry("504x570")
sstore.title("Suit Inventory")

Next, we'll create a simple GUI that consists of a 496 by 188 mage of a man in a suit, a footer image, some
labels, entry boxes, buttons and a listbox. As you copy the code below, you may wish to use the image on page
66 of this section as a guide for what the final program will look like:

image_holder = PhotoImage(file="/Users/Air/Desktop/suit_1.gif")
image_label = Label(image=image_holder).grid(row=0, columnspan=2, pady=2, padx=2)
status_text = Label(text="Please enter the item number (e.g. DC3402A1)")
status_text.grid(row=1, columnspan=2, pady=3, padx=3)
text_item_no = Label(text="Item No: ")
text_item_no.grid(row=2, column=0, pady=3, padx=3, sticky=E)
text_entry_item_no = Entry(width=47)
text_entry_item_no.grid(row=2, column=1, pady=3, padx=3)
text_item_name = Label(text="Model: ")
text_item_name.grid(row=3, column=0, pady=3, padx=3, sticky=E)
text_entry_item_name = Entry(width=47)
text_entry_item_name.grid(row=3, column=1, pady=3, padx=3)
text_item_price = Label(text="Price ($): ")
text_item_price.grid(row=4, column=0, pady=3, padx=3, sticky=E)
text_entry_item_price = Entry(width=47)
text_entry_item_price.grid(row=4, column=1, pady=3, padx=3)
item_button = Button(text="Add", command=add_item, width=7)
item_button.grid(row=5, column=1, pady=3, padx=9, sticky=E)
item_list = Listbox(width=60,height=7)
item_list.grid(row=6, columnspan=2, pady=3, padx=10)
all_button = Button(text="Show All", command =show_list, width=7)
all_button.grid(row=7, column=0,pady=3, padx=3)
delete_button = Button(text="Delete", command=del_item, width=7)
delete_button.grid(row=7, column=1, pady=3, padx=9, sticky=E)
image_holder1 = PhotoImage(file="/Users/Air/Desktop/suit.gif")
image_label1 = Label(image=image_holder1).grid(row=8, columnspan=2, pady=2, padx=2)

Next, we'll create a function called add_item which will give the status of the entry boxes, open a connection to
our database, store the entered data and then close the connection. It will then delete the contents of the entry
boxes for the next entry. First, let's create a simple if statement to ensure that the entry boxes are not empty. If
one of them are, then the user gets an appropriate statement:

def add_item():
if text_entry_item_no.get() == "":
status_text["text"] = "Please enter the item number (e.g. DC3402A1)"
elif text_entry_item_name.get() == "":
status_text["text"] = "Please enter the product model"
elif text_entry_item_price.get()== "":
status_text["text"] = "Please enter the product price"

65
At the else statement, the program will create three new variables out of what the user enters into the entry
boxes, to be inserted into our database table:

else:
item_entry1 = text_entry_item_no.get()
item_entry2 = text_entry_item_name.get()
item_entry3 = text_entry_item_price.get()

Next, we will create another variable that will connect out to our SQLite3 database and a variable that creates a
cursor object. Cursor objects allow us to keep track of where we are within our database results and to call
these results from our database.

connection = sqlite3.connect('/Users/Air/Desktop/store_info/sdata.db')
cursor_v = connection.cursor()

With our cursor placed, we can now execute a command. Notice the format of the execution in the code
below. We insert into [the name of our table] then declare the column name(s) along with values. For each
column, we want to use a ? within the parenthesis and the use the commit() method to verify the execution. The
commit method is needed to complete the operation:

cursor_v.execute("insert into storedata (item_no, item_name, item_price) values (?,?,?)", (item_entry1,


item_entry2, item_entry3))
connection.commit()

We can now close the cursor object and if needed, the database variable as well using .close(). We'll also clear
the entry boxes and reset the status of our label to its original message to be ready for the next entry. Note that
when we use the .delete() method below, the argument 0, END acts like a range and means that the 0 index
will be deleted until the END. 0, END can always be used to delete all the text in an entry box.

cursor_v.close()
text_entry_item_no.delete(0, END)
text_entry_item_name.delete(0, END)
text_entry_item_price.delete(0, END)
status_text["text"] = "Please enter the item number (e.g. DC3402A1)"
return

If we were to put 1,END or 1,2 as the range, then only those indexes will be deleted. Be sure to play around
with these values to see how they work in detail:

66
READING DATABASES
33.7 - SQLite3 Databases: Reading

We can now start our second function, which will connect out to our database and use a simple for loop to pull
all data from our table. First, we'll clear whatever is in the list box using the .delete method. Next, we'll create a
connection, as we did with the add_name function and assign a new execute command to a variable called list.
This command asks Python to get everything from storedata.

def show_list():
item_list.delete(0, END)
connection = sqlite3.connect('/Users/Air/Desktop/store_info/sdata.db')
cursor_v = connection.cursor()
list = cursor_v.execute("select * from storedata")

We can now commit to the changes and begin a for loop that runs through every row in list, which is now
everything from storedata. It then uses the .insert() method to insert the result at the end of each row into our
list box. Unlike .delete() which works on a range, the argument for .insert() is first the index, then the string, text
or variable. To append row to our list box, we'll use (END, row) as our argument:

connection.commit()
for row in list:
item_list.insert(END, row)
cursor_v.close()
return

Notice how we always close our cursor object. We can now view all the records in our database at any time.

67
MODIFYING DATABASES
33.8 - SQLite3 Databases: Deleting

We can now start our third and final function, which will allow us to select an item name in the list and delete
it from our database. We first must create a variable called item_selected that holds the current selection from
our list. Next, we'll create three variables that hold the 0th, 1st and 2nd index of item_selected, which will be
the first, second and third item in the list.

def del_item():
item_selected = item_list.get(ACTIVE)
delete_item0 = item_selected[0]
delete_item1 = item_selected[1]
delete_item2 = item_selected[2]

Next, we connect to our database as we did before. This time; however, we'll use DELETE FROM in our execute
method, deleting the variable that holds the selected items in our list:

connection = sqlite3.connect('/Users/Air/Desktop/store_info/sdata.db')
cursor_v = connection.cursor()
cursor_v.execute("DELETE FROM storedata WHERE item_no=? and item_name=? and item_price=?",
(delete_item0, delete_item1, delete_item2))

Finally, we commit to the changes and close our cursor object:

connection.commit()
cursor_v.close()
item_list.delete(ANCHOR)
return

We can now delete any record that we select in our list box.

Our final code should look something like this:

from tkinter import *


import sqlite3
sstore = Tk()
sstore.geometry("504x570")
sstore.title("Suit Inventory")

def add_item():
if text_entry_item_no.get() == "":
status_text["text"] = "Please enter the item number (e.g. DC3402A1)"
elif text_entry_item_name.get() == "":
status_text["text"] = "Please enter the product model"
elif text_entry_item_price.get()== "":
status_text["text"] = "Please enter the product price"
else:
item_entry1 = text_entry_item_no.get()
item_entry2 = text_entry_item_name.get()
item_entry3 = text_entry_item_price.get()
connection = sqlite3.connect('/Users/Air/Desktop/store_info/sdata.db')
cursor_v = connection.cursor()
cursor_v.execute("insert into storedata (item_no, item_name, item_price) values (?,?,?)", (item_entry1,
item_entry2, item_entry3))
connection.commit()
cursor_v.close()
text_entry_item_no.delete(0, END)

68
text_entry_item_name.delete(0, END)
text_entry_item_price.delete(0, END)
status_text["text"] = "Please enter the item number (e.g. DC3402A1)"
return

def show_list():
item_list.delete(0, END)
connection = sqlite3.connect('/Users/Air/Desktop/store_info/sdata.db')
cursor_v = connection.cursor()
list = cursor_v.execute("select * from storedata")
connection.commit()
for row in list:
item_list.insert(END,row)
cursor_v.close()
return

def del_item():
item_selected = item_list.get(ACTIVE)
delete_item0 = item_selected[0]
delete_item1 = item_selected[1]
delete_item2 = item_selected[2]
connection = sqlite3.connect('/Users/Air/Desktop/store_info/sdata.db')
cursor_v = connection.cursor()
cursor_v.execute("DELETE FROM storedata WHERE item_no=? and item_name=? and item_price=?",
(delete_item0,delete_item1,delete_item2))
connection.commit()
cursor_v.close()
item_list.delete(ANCHOR)
return

image_holder = PhotoImage(file="/Users/Air/Desktop/suit_1.gif")
image_label = Label(image=image_holder).grid(row=0, columnspan=2, pady=2, padx=2)
status_text = Label(text="Please enter the item number (e.g. DC3402A1)")
status_text.grid(row=1, columnspan=2, pady=3, padx=3)
text_item_no = Label(text="Item No: ")
text_item_no.grid(row=2, column=0, pady=3, padx=3, sticky=E)
text_entry_item_no = Entry(width=47)
text_entry_item_no.grid(row=2, column=1, pady=3, padx=3)
text_item_name = Label(text="Model: ")
text_item_name.grid(row=3, column=0, pady=3, padx=3, sticky=E)
text_entry_item_name = Entry(width=47)
text_entry_item_name.grid(row=3, column=1, pady=3, padx=3)
text_item_price = Label(text="Price ($): ")
text_item_price.grid(row=4, column=0, pady=3, padx=3, sticky=E)
text_entry_item_price = Entry(width=47)
text_entry_item_price.grid(row=4, column=1, pady=3, padx=3)
item_button = Button(text="Add", command=add_item, width=7)
item_button.grid(row=5, column=1, pady=3, padx=9, sticky=E)
item_list = Listbox(width=60,height=7)
item_list.grid(row=6, columnspan=2, pady=3, padx=10)
all_button = Button(text="Show All", command =show_list, width=7)
all_button.grid(row=7, column=0,pady=3, padx=3)
delete_button = Button(text="Delete", command=del_item, width=7)
delete_button.grid(row=7, column=1, pady=3, padx=9, sticky=E)
image_holder1 = PhotoImage(file="/Users/Air/Desktop/suit.gif")
image_label1 = Label(image=image_holder1).grid(row=8, columnspan=2, pady=2, padx=2)

69
And the GUI program should look something like this:

Congratulations! You've written your first database program using SQLite3. In the coming sections, we'll learn
more about databases, creating a website that allows a user to sign up for an account and log in afterwards. Be
sure to read the prerequisites carefully before diving into the next section.

70
WEB FRAMEWORKS
34.1 - Pre-Requisites: HTML and CSS

Before attempting the web frameworks section, basic knowledge of HTML and CSS is required. If you would
like to learn these languages, w3schools.com is a great place to start. If you're already familiar with both of
these web languages, then this section will allow you to tie your knowledge of HTML, CSS, SQLite3 and Python
all together to create a dynamic website. This type of development is called full-stack web development, where
you are not only programming the front-end (what the user sees like HTML and CSS), but also the back-end or
server-side using a robust language like Python. Famous sites like YouTube and Instagram use Python as a back-
end language.

34.2 - Bottle

There are many Python web frameworks out there, but none of them are as easy to understand and use as a
framework called Bottle. Bottle's website describes it as:

“A fast, simple and lightweight WSGI micro web-framework for Python. It is distributed as a single file module
and has no dependencies other than the Python Standard Library.”

What does that mean? It means that to get a site up using bottle, all you have to do is download a single .py
called bottle, add it to your site folder and import it into your code; it's that simple. Let's get started. Our goal is-
with our knowledge of HTML, CSS and SQLite3- to get a working website up that allows a user to sign-in or
sign-up for an account.

34.3 - Creating a New Website

To create our first website, let's make a folder on desktop called site. Next, we'll download the bottle.py file
from Bottlepy.org and once this file is downloaded, add it to our site folder. Now, let's create a new .py file, save
it as home.py in site and import the following from bottle:

from bottle import run, get, post, request, route

Next, we'll put in a run function, with an argument of a local host and port of 8000. In networking, a port
serves as the network communication's endpoint in a host's operating system, much like the way an extension
works for a phone number. There are thousands of port numbers that we can use on a PC. In this case, we'll use
port 8000 because one, it is usually not dedicated and two, is the most widely used for web servers and HTTP
access:

run(host='localhost', port=8000)

Our code should now look like this:

from bottle import run, get, post, request, route


run(host='localhost', port=8000)

And when we run it, we should see a server running:

With this still running and visible on your screen, let's open a browser and type: localhost:8000. We should see
some activity on the Python shell, something like "GET / HTTP/1.1" 404 726. If you see activity on the shell,
we're good to go. Remember that we'll need to quite and re-run the server every time we change our website.

71
34.4 - Routes

Now that we've got our site running, we'll create our first route. A route is a path that the user will take; it
triggers code that will put the user on a new page, for example or go to process a form. For example, if we want
our first page to be called home and simple show a paragraph that reads “Hello”, we'll create a route for it as
follows:

from bottle import run, get, post, request, route

@route('/home')
def home():
return "<p>Hello</p>"

run(host='localhost', port=8000)

Now, if we type in localhost:8000/home in our browser, we should see a paragraph that displays “Hello”. Let's
say that we wanted to put a link underneath paragraph to a new page. We can create another route and simple
use that route name as the link. Here's an example:

from bottle import run, get, post, request, route

@route('/home')
def home():
return '''<p>Hello</p>
<a href="/about">About page</a>

'''

@route('/about')
def home():
return "<p>This is the about page</p>"

run(host='localhost', port=8000)

Notice how 3 single quotation marks were used to wrap around multiple HTML code.

If all of this makes sense so far, we're ready to launch our first site. The code below is for a working HTML and
CSS site. You should already be familiar with the HTML and CSS code below. It uses an internal stylesheet, a
Google API font, hotlinked images and some basic CSS positioning. Copy and paste this into your home.py file
and run it on port 8000 to see what happens. If it works, modify the HTML and CSS code to better suit your
tastes before we move on:

@route('/home')
def home():
return '''

<!DOCTYPE html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Muli' rel='stylesheet' type='text/css'>
<meta charset="UTF-8">

<style>
body{
margin: 0px;
padding: 0px;

72
}
h1{
font-family: 'Muli', sans-serif;
color:black;
}
h1#lefter{
font-family: 'Muli', sans-serif;
color:black;
float: left;
margin-left:10px;
}
p{
font-family: 'Muli', sans-serif;
color:black;
margin:20px;
}
img#orange_logo{
margin-top:8px;
margin-left:10px;
width:250px;
float: left;
}
img#banner{
width:100%;
margin-top: 50px;
}
form{
margin-top: 30px;
float: right;
margin-right: 20px;
}
.logfont{
font-family: 'Muli', sans-serif;
font-size: 10px;
color:black;
padding-right:10px;
padding-left:10px;
}
.header{
margin-top: 0px;
width:100%;
height:80px;
background-color: #FFFFFF;
position: fixed;
}
a:link {
text-decoration: none;
}
a:visited {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
a:active {
text-decoration: underline;

73
}
</style>
<title>First Bottle Site Example</title>
</head>

<body>
<div class="header">

<img id="orange_logo" src="http://www.thebusinessof.net/wordpress/wp-


content/themes/thebusinessof/images/asmallorange-logo-320x80.png">

</div>

<img id="banner" src="http://cdn.elegantthemes.com/preview/eStore/wp-content/uploads/2010/08/featured-


2.jpg">

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut aliquet at sem non ullamcorper. Sed
molestie orci et varius consequat. Pellentesque aliquet nisi at diam suscipit aliquet. Nullam efficitur diam quis
dolor eleifend dignissim. Ut malesuada tincidunt arcu et gravida. Sed ac semper lacus. Vivamus tincidunt, nisi
id eleifend congue, ante libero ultrices nibh, vel iaculis tortor odio non tellus. Nulla et aliquam lectus, vel
scelerisque nibh. Nam ornare, massa et tristique aliquet, enim est rutrum lectus, vitae dictum tellus felis at
neque. Praesent mollis sapien sed massa ornare cursus. Phasellus ultricies at urna sed malesuada. Etiam
interdum tortor sed orci ultricies, sit amet condimentum dolor fringilla.</p>
<p>Integer nisi felis, efficitur non ex in, feugiat vulputate tortor. Vestibulum egestas tempus commodo.
Pellentesque sed tortor eget orci commodo congue et et felis. Duis eu aliquet nunc, id elementum urna.
Quisque eget interdum neque. In faucibus sit amet turpis id tincidunt. Curabitur finibus vel massa sed
venenatis.</p>

</body>

</html>
'''

run(host='localhost', port=8000)

If sticking with the CSS above, the site should look something like this:

74
34.5 - Posts

Now that we've got a basic site up, let's process our first web form using post, an HTTP method that sends form
data. First, we'll create our form. You should already be familiar with the following CSS and HTML code for this
particular form:

CSS:

.header{
margin-top: 0px;
width:100%;
height:80px;
background-color: #FFFFFF;
position: fixed;
}

HTML:

<div class="header">
<img id="orange_logo" src="http://www.thebusinessof.net/wordpress/wp-
content/themes/thebusinessof/images/asmallorange-logo-320x80.png">

<form action="/home" method="post">


<span class="logfont">Username:</span><input name="username" type="text" />
<span class="logfont">Password:</span><input name="password" type="password" />
<input value="Login" type="submit" /> <span class="logfont"><a href="">Sign Up</a></span>
</form>
</div>

Your form should look something like this:

Next, we'll create a new route. This time with an additional argument of method='POST'. We'll also create a
function called do_login() and within that, do a simple check to make sure that the username is “Victor”. If it is,
the site returns “Login was correct”. Otherwise, it returns “Login failed”.

@route('/home', method='POST')
def do_login():
username = request.forms.get('username')
password = request.forms.get('password')
if username == "Victor":
return "<p>Your login information was correct.</p>"
else:
return "<p>Login failed.</p>

75
If we re-run our server and site, we should be able to now log in with the username “Victor” and fail without it.
Obviously, “Victor” is pre-defined in our code and would not be a realistic way to allow access, but this
example does show how we can use POST easily. We will improve this login area once we create a database.

34.6 - 404 Pages

Sometimes, for one reason or another, a page will not load or just seems to go missing. This is called a 404
page, a standard response code in HTTP telling the user that the link is broken. Let's code our page so that it
can handle errors and display a custom 404 page. First, we must import error in addition to what we already
have:

from bottle import run, get, post, request, route, error

Next, we'll hotlink to any random 404 image online and create the following code:

@error(404)
def error404(error):
return '''

<img src="http://familius.com/Data/Sites/1/systemfiles/oops-404.png">

'''

Now, if we re-run our server and site and type in localhost:8000/home/mypage, or any other page that does not
exist, we should get the 404 error:

34.7 - Integrating SQLite3 into Webpages

In the same way that we've used SQLIte3 to create and update a database in the Tkinter GUI earlier in the
course, we can also use it with the web. Let's create a sign-up page and allow the user to store his/her
username, email and password. We'll then check our database to ensure that this information is being
appended to it.

First, let's make sure that the original home page has a link to the new sign-up page that we'll be creating. We
can do this by simply adding /signup to the a href for sign-up in our original form.

76
HTML:

<div class="header">
<img id="orange_logo" src="http://www.thebusinessof.net/wordpress/wp-
content/themes/thebusinessof/images/asmallorange-logo-320x80.png">

<form action="/home" method="post">


<span class="logfont">Username:</span><input name="username" type="text" />
<span class="logfont">Password:</span><input name="password" type="password" />
<input value="Login" type="submit" /> <span class="logfont"><a href="">Sign Up</a></span>
</form>
</div>

Your form should still look something like this, but now link to a page called sign-up. We haven't created this
route yet, so it will not work at this point:

Next, we'll create our database. If you have forgotten how to do this, have a look back at the SQLite3 section
from earlier. We'll need to create a database in the same folder as our site called users.db with a table called
user. In that table is cemail and cpassword. Go ahead and insert a few values into the database to ensure that
the table is created and working.

Now, we'll import SQLite3 into our program. We do this as we've done before:

from bottle import run, get, post, request, route, error


import sqlite3

Next, we'll create a sign-up route, complete with HTML and CSS code. The entire code is as follows:

@route('/signup')
def signup():
return '''

<!DOCTYPE html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Muli' rel='stylesheet' type='text/css'>
<meta charset="UTF-8">

<style>
body{
margin: 0px;
padding: 0px;
}

77
h1{
font-family: 'Muli', sans-serif;
color:black;
}
p{
font-family: 'Muli', sans-serif;
color:black;
margin:20px;
}
p#create{
font-family: 'Muli', sans-serif;
color:black;
margin:20px;
font-size: 20px;
}
img#orange_logo{
margin-top:8px;
margin-left:10px;
width:250px;
float: left;
}
img#banner{
width:100%;
margin-top: 50px;
}
.logfont{
font-family: 'Muli', sans-serif;
font-size: 15px;
color:black;
padding-right:10px;
padding-left:10px;
}
.header{
margin-top: 0px;
width:100%;
height:80px;
background-color: #FFFFFF;
position: fixed;
}
a:link {
text-decoration: none;
}

a:visited {
text-decoration: none;
}

a:hover {
text-decoration: underline;
}

a:active {
text-decoration: underline;
}
td{
padding: 5px;

78
}
input{
width: 200px;
}
form{
padding-top:20px;
padding-bottom: 20px;
background-color:#E5E4E2;
}
</style>
<title>First Bottle Site Example</title>
</head>

<body>
<div class="header">

<img id="orange_logo" src="http://www.thebusinessof.net/wordpress/wp-


content/themes/thebusinessof/images/asmallorange-logo-320x80.png">

</div>

<img id="banner" src="http://cdn.elegantthemes.com/preview/eStore/wp-content/uploads/2010/08/featured-


2.jpg">

<center>
<p id="create">Create your Small Orange Account</p>

<form action="/signup" method="post">


<table>
<tr><td><span class="logfont">Email:</span></td><td><input name="cemail" type="text" /></td></tr>
<tr><td><span class="logfont">Create a Password:</span></td><td><input name="cpassword"
type="password" /></td></tr>
<tr><td><span class="logfont">Confirm Password:</span></td><td><input name="cpassword2"
type="password" /></td></tr>
<tr><td></td><td><button type="submit" />Sign Up</button></td></tr>
</table>
</form>
</center>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut aliquet at sem non ullamcorper. Sed
molestie orci et varius consequat. Pellentesque aliquet nisi at diam suscipit aliquet. Nullam efficitur diam quis
dolor eleifend dignissim. Ut malesuada tincidunt arcu et gravida. Sed ac semper lacus. Vivamus tincidunt, nisi
id eleifend congue, ante libero ultrices nibh, vel iaculis tortor odio non tellus. Nulla et aliquam lectus, vel
scelerisque nibh. Nam ornare, massa et tristique aliquet, enim est rutrum lectus, vitae dictum tellus felis at
neque. Praesent mollis sapien sed massa ornare cursus. Phasellus ultricies at urna sed malesuada. Etiam
interdum tortor sed orci ultricies, sit amet condimentum dolor fringilla.</p>
<p>Integer nisi felis, efficitur non ex in, feugiat vulputate tortor. Vestibulum egestas tempus commodo.
Pellentesque sed tortor eget orci commodo congue et et felis. Duis eu aliquet nunc, id elementum urna.
Quisque eget interdum neque. In faucibus sit amet turpis id tincidunt. Curabitur finibus vel massa sed
venenatis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut aliquet at sem non ullamcorper. Sed
molestie orci et varius consequat. Pellentesque aliquet nisi at diam suscipit aliquet. Nullam efficitur diam quis
dolor eleifend dignissim. Ut malesuada tincidunt arcu et gravida. Sed ac semper lacus. Vivamus tincidunt, nisi
id eleifend congue, ante libero ultrices nibh, vel iaculis tortor odio non tellus. Nulla et aliquam lectus, vel

79
scelerisque nibh. Nam ornare, massa et tristique aliquet, enim est rutrum lectus, vitae dictum tellus felis at
neque. Praesent mollis sapien sed massa ornare cursus. Phasellus ultricies at urna sed malesuada. Etiam
interdum tortor sed orci ultricies, sit amet condimentum dolor fringilla.</p>
<p>Integer nisi felis, efficitur non ex in, feugiat vulputate tortor. Vestibulum egestas tempus commodo.
Pellentesque sed tortor eget orci commodo congue et et felis. Duis eu aliquet nunc, id elementum urna.
Quisque eget interdum neque. In faucibus sit amet turpis id tincidunt. Curabitur finibus vel massa sed
venenatis.</p>

</body>

</html>
'''

Your sign-up page should look something like this:


We'll
also
need
to

create a route for posting. Notice that cemail, cpassword and cpassword2 are all from the form. We'll first do a
check to make sure that the passwords are equal using a simply Python control statement and then go off and
enter these values into our database, just as we did before:

@route('/signup', method='POST')
def do_signup():
cemail = request.forms.get('cemail')
cpassword = request.forms.get('cpassword')
cpassword2 = request.forms.get('cpassword2')
if cemail == "" or cpassword == "" or cpassword2 == "":
return "<p>All fields required</p>"
elif cpassword != cpassword2:
return "<p>Passwords do not match</p>"
else:

80
connection = sqlite3.connect('/Users/Air/Desktop/site/cp/users.db')
cursor_v = connection.cursor()
cursor_v.execute("insert into user (cemail, cpassword) values (?,?)", (cemail, cpassword))
connection.commit()
cursor_v.close()
return "<p>Sign up successful. Info added to database</p>"

If we run our server and site now, we should be able to successfully add a new user to the database. Let's sign
up a new user and open our database in Terminal to check that the new user is added:

Before we move on to the next section, try improving the overall UI and UX of the program on your own using
Python, CSS and some JQuery libraries. You can improve the sign-in and sign-up page so that if anything is left
blank, the user is notified. Better yet, give the user a flash message, a small notification that pops up or slides in
to let the user know that something has succeeded or failed. Below is an example (on the left) after a sign-up.

You could also try enhancing the look of forms using CSS or JQuery. Try PureCSS.io, Bootstrap or JQueryMobile
to change the look of the sign-up button, for example (on the right):

81
This would also be a good time to also add a database connection to our sign-in page as well. In our previous
code for the sign-in area, we created a simple control statement to check if the username was equal to “Victor”.
Let's rewrite it so that the program performs a simple check to see if the username and password are in
database. If they are, the program returns “Welcome”, otherwise it returns “User not found”.

First, we'll do the check to see if all fields have been filled in. We can either return a message or use a flash
message as we did with out improved sign-up page. If all fields are in, we'll create a connection and select all
those rows where the email and password are equal to the values entered by the user. If the database did not
find anything at execute, then None is returned. After that, we'll select only that one row using the .fetchone()
method and store it in row. Then we do a check to see if row is empty or None. If it is, the username or
password were not found to be correct. Otherwise, the user sees “Welcome”. This can be a simple return as
shown below or a more friendly flash message:

@post('/home')
def do_login():
cemail = request.forms.get('username')
cpassword = request.forms.get('password')
if cemail == "" or cpassword == "":
return "<p>All fields required</p>"
else:
connection = sqlite3.connect('/Users/Air/Desktop/users.db')
cursor_v = connection.cursor()
cursor_v.execute("SELECT * FROM user WHERE cemail=? AND cpassword=?", (cemail,cpassword))
row = cursor_v.fetchone()
if row == None:
return "<p>Username or password invalid</p>"
else:
return "<p>Welcome</p>"

Now if we enter a valid username and bad password or bad username and valid password, we'll get the error
message. If we enter a valid username and valid password, we should see “Welcome”.

34.8 - Data Security: Hashing Data

In all of our previous database programs, we added user information as plain text (e.g. a password of “123”
went into our database as “123”). To validate these passwords, we simply checked if they were in the database
or not. There are some major security issues with storing everything as plain text. If a hacker were to attack our
database table for example, he/she would be able to access all of our passwords and clearly read them. One
such attack is called an SQL injection, where malicious SQL statements are inserted into an entry field to dump
the database contents.

Although we will not get too deep into security at this point, there are a few things that we can do to improve
the security of our program and learn a little about security along the way. One such security technique is called
hashing. Hashing is when an algorithm is applied to our data to convert it to an unreadable sequence of letters
and numbers. The value returned by a hash function is often called a hash, hash value or checksum. Here, the
phrase “Hello World” is hashed using one algorithm called SHA1:

0a4d55a8d778e5022fab701977c5d840bbc486d0

There are two important things to keep in mind with regards to hashing. Firstly, hashing is not encryption.
Encryption is when you encrypt or cipher data using a secret key. You can then use that key to decrypt or
decipher that same data. Thus, encryption is meant to be reversible as long as the one reversing it has the key.
Secondly, like the first point, hashing is one-way and is not meant to be undone.

In the next section, we'll re-write our sign-up form so that the passwords are hashed as they go into our
database. We'll then check to see if the hashing worked.

82
34.9 - HashLib

Python comes with a built-in hashing module called Hashlib. It contains some of the most popular hashing
algorithms like SHA1, SHA224, SHA256, SHA384, and SHA512. We'll better understand these as we work
through this section, but for now, let's hash our sign-up form data. First, we need to import hashlib:

import hashlib

Next, let's examine this line of code to be used in our hashing function before we continue:

hashlib.sha1(password.encode('utf-8')).hexdigest()

algorithm used returns hexadecimal digits

In the above code, we've attached the algorithm to be used, sha1 to hashlib. Our password will be passed to
our function and the .encode() method converts it to UTF-8 (see page 46). Our final function, with all the
previous libraries, will look something like this:

from bottle import run, get, post, request, route, error


import sqlite3,
import hashlib

def encrypt_password(password):
encrypted_pass = hashlib.sha1(password.encode('utf-8')).hexdigest()
return encrypted_pass

Now, we're ready to update our sign-up form:

@post('/signup')
def do_signup():
...
if cemail == "" or cpassword == "" or cpassword2 == "":
return "<p>All fields required</p>"
elif cpassword != cpassword2:
return "<p>Passwords do not match</p>"
else:
connection = sqlite3.connect('/Users/Air/Desktop/users.db')
connection.create_function('encrypt', 1, encrypt_password)
cursor_v = connection.cursor()
cursor_v.execute("insert into user (cemail, cpassword) values (?,encrypt(?))", (cemail, cpassword))
connection.commit()
cursor_v.close()
...

Notice that we now have used a new method, .create_function(). This method take 3 arguments: name (the
name used to call the function), the number of parameters (1 in this case) and a callable object (the function
itself). We'll then used encrypt in our execute line to encrypt the password. Let's run our sign-up page again. If
we enter a username of victor@me.com and password of abc, the password should be hashed:

83
Now, let's update our login area, so that all entered passwords are hashed as well. We can do this with our
select * from in almost the same way that we did the insert into:

@post('/home')
def do_login():
cemail = request.forms.get('username')
cpassword = request.forms.get('password')
if cemail == "" or cpassword == "":
return "<p>All fields required</p>"
else:
connection = sqlite3.connect('/Users/Air/Desktop/users.db')
connection.create_function('encrypt', 1, encrypt_password)
cursor_v = connection.cursor()
cursor_v.execute("SELECT * FROM user WHERE cemail=? AND cpassword=encrypt(?)",
(cemail,cpassword))
row = cursor_v.fetchone()
if row == None:
return "<p>Username or password invalid</p>"
else:
return "<p>Welcome</p>"

Let's run our sign-in page again. If we enter a username of victor@me.com and password of abc, the site should
welcome us.

So far, our hashes seem to work great, but there is a problem. Hashes can be easily broken. Have a look at what
happened when we ran our hashed password, a9993e364706816aba3e25717850c26c9cd0d89d through
crackstation.net:

Not only was the password decrypted, even the algorithm that we used was revealed. So what now?

84
34.10 - Bcrypt and PBKDF2

It's important to know that database security is an ever-evolving art and that the previous examples were
designed to shed a little light on the issue, not cover everything or even really scratch the surface. However, for
the sake of learning and not leaving our program vulnerable to easy attacks, let's do one more major security
improvement to our sign-up and sign-out areas before completing this section. To do this, we'll look at two
password-based key derivation functions: bcrypt and PBKDF2. Bcrypt is used by many industry professionals
and allows for “modern password hashing for your software and your servers”. It incorporates a salt (or
randomization) to protect against attacks. Bcrypt in Python allows us to hash a password and then later check
that password to see if it matches the previous hashed password, which is exactly what we need for our login
area. PBKDF2 (Password-Based Key Derivation Function 2) is another modern function for passwords that works
similar to bcrypt, but unlike bcrypt, is much easier to install and use. For this reason, we'll use PBKDF2.

To get started, we'll download the pbkdf2.py file from https://pypi.python.org/pypi/pbkdf2, bring it into our
current site folder and import it. Let's set up a simple program that just takes in a password, hashes it and spits
out the hashed password. Remember that in our previous hash examples, the hashed version of the password
“abc” would be the same every time.

from pbkdf2 import crypt

while True:
pw = input("Password: ")
pwhash = crypt(pw)
print(pwhash)

Now you'll notice that even though we've entered “abc” thrice, every hashed (and salted) version is different:

This is a much more secure way to go about things. For our final security revision to our website, let's go ahead
and implement PDKDF2 to our sign-up and sign-in forms.

First, we'll need to import pbkdf2. The top of our main .py file should look like this now:

from bottle import run, get, post, request, route, error


import sqlite3
from pbkdf2 import crypt

Next, let's modify our code to incorporate the new PBKDF2 hash:

def do_signup():
...
return "<p>Passwords do not match</p>"
else:
pwhash = crypt(cpassword)

85
connection = sqlite3.connect('/Users/Air/Desktop/users.db')
cursor_v = connection.cursor()
cursor_v.execute("insert into user (cemail, cpassword) values (?,?)", (cemail, pwhash))
connection.commit()
cursor_v.close()
...

Now, when a new user signs up, we should see the new and improved hashed password in our database.

Finally, we'll modify the sign-in area so that it works with the new hashed password. First, we need to get the
user's former hashed password from the 1st index of the row that holds the record. Next, we'll use PDKDF2's
crypt() function to process it:

@post('/home')
def do_login():
….
else:
connection = sqlite3.connect('/Users/Air/Desktop/users.db')
cursor_v = connection.cursor()
cursor_v.execute("SELECT * FROM user WHERE cemail=?", (cemail,))
row = cursor_v.fetchone()
pwhash = row[1]
if pwhash == crypt(cpassword, pwhash):
return "<p>Welcome. You're logged in.</p>"
else:
return "<p>Invalid Username or Password</p>"

Now, even though both passwords were hashed completely differently (when stored and when queried), the
program can still match them for authentication:

86
NETWORK PROGRAMMING
35.1 - Python's Socket Module

In the last few sections, we've looked at programs that communicated mainly with our own computers;
communicating with everything from our operating system to CSV files to databases. Now would be a good
time to introduce a different type of programming that allows computers to communication across a network;
this type of programming is called network or socket programming.

There are a few terms to understand before we begin socket programming in Python. In networking, a network
socket is the endpoint of a communication flow across a computer network. Most communications today are
based on IP (Internet Protocol); hence most network sockets are internet sockets. In Python, the socket module
is what we use for tasks that involve network communications. A socket has a socket address, which is simply
the combination of an IP address and a port number. Think of an IP address like a telephone connection; the
phone number is the IP address and the extension is the port number. Based on this address, internet sockets
deliver incoming data packets to the appropriate application process. We'll look at ports more in-depth in the
next section.

35.2 - Creating a Server/Client Program

For our next program, to demonstrate how to establish network connections with Python, we'll create a mock
chat program that will allow two users to communicate from different computers using a host IP address. We'll
create two programs: one to act as the server and the other as the client. As with our previous program, the
complete program will stretch across the next few sections, so be sure to consider the next few sections as
project-based instruction and follow along accordingly. To get started, let's first create our server program by
creating a new window in IDLE and saving the file as server.py. Next, let's import everything from the socket
module:

from socket import *

Next, we'll create a variable called host. The host will hold the IP address that will act as the server. This IP will
need to be changed to your own or left blank (if the connection will be local, on one computer):

host = '111.1.1.1'

Next, we'll create a variable called port. In networking, a port serves as the network communication's endpoint
in a host's operating system, much like the analogy that we gave of a port acting like an extension in a phone
number. There are thousands of port numbers that we can use on a PC. In this case, we'll use port 8000 because
one, it is usually not dedicated and two, is the most widely used for web servers and HTTP access:

port = 8000

Next, we'll create a variable called our_socket that holds the socket function. The function will have two
arguments: First, a default initialization named AF_INET which sets the rules for our socket connection and
second, the type of communication; typically SOCK_STREAM for connection-oriented protocols and
SOCK_DGRAM for connectionless protocols:

our_socket = socket(AF_INET, SOCK_STREAM)

Next, we'll use the .bind() method, which binds the host's address and port number to the socket. We'll use two
arguments: our host variable and our port variable. Note that bind() usually takes only one argument. To have it
take two, we'll need to use double parenthesis:

our_socket.bind((host, port))

Next, we'll use the .listen() method, which takes a number as an argument, stating the amount of connections
that it will be “listening” to. In this case, we'll only have one connection (from and to the other chat program) so
we'll use 1 as the argument:

87
our_socket.listen(1)

Next, we'll use the .accept() method, which accepts the connection. When a connection is accepted, the
method receives two bits of information; the first we'll store in a variable called conn and the second- the IP
address- in a variable called addr, which we'll reference later:

conn, addr = our_socket.accept()

Now, in order to notify our server of who just connected, we can print the information that is being held in addr
as a string:

print ('Received connection from ' + str(addr))

Next, we'll start a while loop and create a variable called data. This variable holds our connection and the
.recv() method, which receives the message and takes an argument of 1024 bytes (bytes of data that we are
trying to receive). Next, we'll print that the data was received and print the message in data. Next, we'll create a
variable called reply which collects the reply and sends it using the .send() method. Since sockets send
information as bytes in Python 3.3.2, we'll need to convert reply to unicode. See page 48 for more information
on unicode.

while True:
data = conn.recv(1024)
print ("Received " + str(data))
reply = input("Reply: ")
conn.send(bytes(reply,'UTF-8'))

Lastly, we'll close our connection:

conn.close()

Our final code for our server program should look something like this:

from socket import *


host = ''
port = 8000
our_socket = socket(AF_INET, SOCK_STREAM)
our_socket.bind((host, port))
our_socket.listen(1)
conn, addr = our_socket.accept()
print ('Received connection from ' + str(addr))
while True:
data = conn.recv(1024)
print ("Received " + str(data))
reply = input("Reply: ")
conn.send(bytes(reply,'UTF-8'))
conn.close()

Our server is now ready to run, but will not do anything because we have not created a client program to
connect to. Now we're ready to create our client program. To do this, create a new window and save the file as
client.py. As we did before, we'll create our socket:

from socket import *


host = ''
port = 8000
our_socket = socket(AF_INET, SOCK_STREAM)
our_socket.connect((host, port))

88
We'll then create a while loop and use the variable “message” to take the message from the user. It then sends
this message in unicode. The server program will receive the message. When the server's user replies, the reply
is received and printed:

while True:
message = input("Your Message: ")
our_socket.send(bytes(message,'UTF-8'))
reply = our_socket.recv(1024)
print ("Received " + str(reply))

We'll then close our socket:

our_socket.close()

Our final code will look something like this:

from socket import *


host = ''
port = 8000
our_socket = socket(AF_INET, SOCK_STREAM)
our_socket.connect((host, port))
while True:
message = input("Your Message: ")
our_socket.send(bytes(message,'UTF-8'))
print ("Awaiting reply...")
reply = our_socket.recv(1024)
print ("Received " + str(reply))
our_socket.close()

If we want to run our programs, we'll need to open Terminal and change the directory to the directory that holds
our file. In Terminal, enter “cd” then the directory location, in this case Desktop. We then start Python by typing
“python3” followed by the name of our file (server.py). If no error occurs, we are ready to start the client
program.

To start the client program, we'll follow the same steps as we did with the server, except that we'll type
“python3” followed by “client.py”. When we do this, a connection is made, printing “Received connection
from 111.1.1.1” on the server program and prompting us for a message on our client program. We can now
begin to communicate across both programs:

89
EMAIL PROGRAMMING
36.1 - Python's SMTP Module

The smtplib module allows us to send emails via SMTP using Python. SMTP stands for Simple Mail Transfer
Protocol and is the standard protocol for sending and routing emails. The most popular email services like
Gmail, Yahoo! And Outlook use SMTP to send and receive emails. In the next few examples, we'll see how to
set up our code to allow sending of emails from our code. We'll be using Gmail's SMTP settings, but any
service can be used. To find the SMTP settings for your mail provider, simply search for it in Google.

In the next example, we'll create a simple email GUI using tkinter and smtplib. We'll first breakdown our user-
defined function that will hold all the code that we need to send our email. After that, we'll create the GUI and
link the button to the function. Let's first import smtplib, the library for using SMTP in Python. This module, like
Tkinter, comes pre-installed in Python:

from tkinter import *


import smtplib

Next, we'll create a function called emailer and put in 2 lines of code that will take the email and message from
2 entry boxes in our GUI:

def emailer():
recipient = goto.get()
message = gomessage.get()

Next, we'll create two variables, gaccount to hold our Gmail username and gpass to hold our password:

gaccount = "viceliasrodriguez@gmail.com"
gpass = "iwillnevertell"

With these credentials, we'll reach out to the server to begin our authentication. First, we must specify the
server. We do this by creating our main SMTP object, using the .SMTP() method. This method will hold the
server address for Gmail as well as the port:

server = smtplib.SMTP("smtp.gmail.com", 587)

We also need to connect to our server using extended SMTP protocols, which are a set of stricter SMTP
protocols. To do this, we'll use the .ehlo() method. If we do not need the extended protocol, we can use .helo().
Another security measure is to connect to our server using TLS. TLS or Transport Layer Security is a set of
protocols to help communicate information more securely over the internet. We also need to log in by passing
the information from gaccount and gpass into the .login() method. Notice the format of these three important
methods:

server.ehlo()
server.starttls()
server.login(gaccount, gpass)

Finally, we'll create a try and except that will use the .sendmail() method, taking the sender's email account, the
recipient's email account (in square brackets) and the message as its 3 arguments. If the program gets through
that successfully, we'll print a label telling the user the good news and then use the .quit() method to quit our
connection to our server:

try:
server.sendmail(gaccount, [recipient], message)
status_label = Label(text="Your email has been sent successfully").grid(row=5,columnspan=2)
server.quit()

90
Otherwise, we'll print the bad news and also quit the connection:

except:
status_label = Label(text="Error. Email not sent").grid(row=5,columnspan=2)
server.quit()
return

Now we'll go ahead and insert our GUI code:

goto = StringVar()
gomessage = StringVar()

tlabel = Label(text="To: ").grid(row=0,column=0,sticky=E,pady=10)


tentry = Entry(textvariable=goto,width=30).grid(row=0,column=1)
mlabel = Label(text="Message: ").grid(row=2,column=0,pady=10)
mentry = Entry(textvariable=gomessage,width=30).grid(row=2,column=1)
ebutton = Button(text="Send",command=emailer).grid(row=4,column=1,sticky=E)

When we run our code and check our email, we should see:

Note that in this case, our email went into the Junk or Spam folder. This is due to Gmail's new security protocols
that route our email accordingly due to it being sent from a 3rd party program and not Gmail itself.

If your code didn't work, it most likely isn't an error on your part. SMTP has a lot of limitations, especially in
terms of security with other sites. A better solution is getting an email API, like Mailgun that enables you to
send, receive and track email easily. The service has free and paid accounts. Check it out for a quick and
seamless email solution.

91
PYTHON & ARDUINO
37.1 - Embedded Systems

Until now, we've been using Python to create all types of software. We've controlled user input via a GUI and
login data via a web form, but we have yet to see how Python can control something other than software-
something like an embedded system. An embedded system is a computer system with a hardware, mechanical
or electrical component. When you see something as basic as a light turn on or off or something as advanced as
a self-parking car, these are all using embedded systems. Throughout the next few sections, we'll look at how
we can program a few simple embedded systems using Python, opening up a world of opportunity to develop
more complex systems. We'll start by getting an LED (a small light bulb) to blink on and off based on user input
and move into more complex systems.

37.2 - Arduino Uno

To complete the next few projects, you'll need an Arduino Uno microprocessor and a few items from the basic
Arduino kit. Arduino is an open-source electronic platform that allows use to create basic embedded systems.
Uno is just the version; the most popular version of Arduino. For a beginner, the Official Arduino Starting Kit is a
great kit to start with and comes with a booklet that guides you through the basics of some really fun and
exciting projects. The Arduino Uno itself is extremely inexpensive and can be purchased online or at a local
store. The first project in this section only requires the Arduino UNO and its accompanying USB cable. The
second project will require a little more hardware, which will be listed.

37.3 - Arduino IDE

Before we can dive into the Python side of Arduino, we need to understand the basics of Arduino, so let's
explore just enough to get us through to the Python-side of things. Let's first download the Arduino IDE from
arduino.cc. We'll first program in this IDE and then incorporate the Python IDE later on. When you open the
Ardunio IDE, you'll see something like this:

Here is where we give our Arduino commands in a


language called C. Of course, we'll only use this
language for the basics, but transition back into
Python.

37.4 - Setting Up Arduino

Let's first examine the very basic parts of the Uno


that we'll need for the first project.

Pin 13: Look at the image top-left. You'll see pins with numbers 1-13 (right-to-left) on the top. Right below pin
13 is a little LED. We'll be using this pin and LED in our first program. From this pin, you can then setup
external LEDs just by connecting jumper wires, which are not needed for this project, but will be later.

92
To get started, let's open up Arduino IDE and connect our Uno via the USB cable. A green light- not the pin 13
light, but a larger one near the word “ON”- should come on letting you know that your Arduino is being on and
being powered. If this does not happen, check the following: Check Tools > Board and ensure that
Arduino/Genuino Uno is selected. Also check Tools > Port and ensure that the right USB port is selected. You
can find out which port is being used by keeping the Port menu open and unplugging and plugging your USB
from the Arduino. If the light is on, we're ready to begin. In our IDE, let's examine the starting code or sketch
that is provided.

void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}

void setup() is where we put code that will run once. For example, if we want power to go to a particular pin,
we will declare that in setup(). When we want to do something with that pin, we can do that in loop(). Here is
an example:

void setup() {
pinMode(13,OUTPUT);
}
void loop() {
digitalWrite(13,HIGH);
}

pinMode() configures a pin to behave either as an input or an output. It takes two arguments, the pin and the
mode. In this case, we want to our LED at pin 13 to output a flash; hence the mode is OUTPUT and the pin is
13. Remember to end every line of code in this program with a ; (semicolon).

pinMode(13,OUTPUT);

Now that we've declared our pin, let's examine the digitalWrite() code. digitalWrite() is our way of writing
either a HIGH (on) or LOW (off) value to the pin. It takes two arguments, the pin and the value.

digitalWrite(13,HIGH);

This will now send voltage (5 volts) to pin 13.


Click Upload on your Arduino IDE and you should
see the built-in LED near pin 13 light up. You've
just communicated with your Arduino.

Now let's turn off the LED:

digitalWrite(13,LOW);

Let's turn it on and off repeatedly, but add a delay


(in milliseconds) between each:

digitalWrite(13,HIGH);
delay(1000);
digitalWrite(13,LOW);
delay(1000);

If we run this code and upload to our Arduino, we


should now see a blinking LED. We've done this entirely in the Arduino IDE in a new language. In the next few
sections, we'll learn how to interact with this system using Python.

93
37.5 - Serial Monitor

An important part of a system is real-time feedback to either the programmer or user. For example, it would be
nice to not only see the LED blink, but read “the light is currently on” somewhere on our screen. This is where
the serial comes in. The serial is used for communication between the Arduino and computer, providing
valuable feedback to either the programmer or user. We'll start by using Arduino's serial, but eventually replace
it with PySerial, Python's version of the serial.

37.6 - Serial Monitor: Writing

Using the blinking LED code from the previous section, let's add a few lines of code that will allow us to
actually read about what is happening in our system. To launch the serial in the Arduino IDE, go to Tools >
Serial Monitor or click on the magnifying glass icon at the top-right of the IDE.

Now let's try a few lines of code:

void setup() {
pinMode(13,OUTPUT);
Serial.begin(9600);
}

void loop() {
digitalWrite(13,HIGH);
delay(1000);
Serial.println("The Light is On");
digitalWrite(13,LOW);
delay(1000);
Serial.println("The Light is Off");
}

First we'll use Serial.begin(9600) to let our program know that we going to be using the Serial. The argument is
the baud rate, or bits per second. In this case, we used 9600. If you're not sure what to set this number to,
simply open the Serial Monitor and the baud rate should be displayed at the bottom-right of the monitor. Ensure
that both the baud rate shown in the monitor and your code match.

Next, we'll use Serial.println() to print a line of code to the Serial when something happens in our code. In this
case, after the delay, we printed “The Light is On”. When we upload this code or sketch, we should see the LED
flash on and off, but also see some feedback in the serial monitor:

94
37.7 - Serial Monitor: Sending

We can also send data to our program via the serial monitor. Let's say that we want to turn on the LED when we
press “1” or turn it off when we press “0”, we can create a program to do this and send this data through the
serial. Here is an example of such a program:

int LED;

void setup() {
pinMode(13,OUTPUT);
Serial.begin(9600);
}

void loop() {
while(Serial.available() == 0){}
LED = Serial.parseInt();
if(LED == 1){
digitalWrite(13,HIGH);
Serial.println("Light is ON");
}
else{
digitalWrite(13,LOW);
Serial.println("Light is OFF");
}
}

First we declared a variable, an integer called LED. Note the way to do this in C/C++. Within out loop, we
created a while loop. The syntax for while loop here is similar to Python where the condition is the argument of
while(), within the parenthesis. The following pair of curly braces hold the statement if true and outside the
statement if false. In this case, Serial.available() just checks to see if anything has been entered into the serial
monitor. If nothing has been entered, then available will be 0; if anything has been entered, then 1. If nothing
was entered, nothing happens, but if Serial.available() is equal to 1, then we break out of the while loop.

Once out of the loop, we need to get what's in the serial using .parseInt() and store it in LED. ParseInt() returns
the first valid integer from the serial. In this case, the user would enter either a 1 or something else. If he/she
entered “1”, the light gets turned on. Otherwise, the light turns or stays off.

As mentioned earlier, the Official Arduino Starting Kit is a great kit to start to learn more about Arduino. The kit
comes with a project booklet that, at the moment has about 12 exciting projects, ranging from the basics to
getting a motor to start.

37.8 - PySerial

With all the Python that we've learned so far, wouldn't it be nice to write and control the previous LED program
using the familiar Python IDE? With PySerial, we can. PySerial gives us access to the serial port and allows us to
interact with the program that we've uploaded to our Arduino.

First, we need to download PySerial. Once installed, open Python IDLE and import it:

import serial

Next, we'll need to declare a variable for our serial connection. To create the connection, we'll use serial.Seria()
and two arguments, the port number and the baud rate:

arduinoData = serial.Serial('/dev/cu.usbmodem1421',9600)

95
Next, we'll create a simple counter, print a statement and create a while loop that will keep taking the user's
input, either a 1 for ON or 2 for OFF. Everything here we're highly familiar with, with the exception of
.encode(), which simply returns an 8-bit string version of the unicode string that we entered.

import serial
arduinoData = serial.Serial('/dev/cu.usbmodem1421',9600)
counter=0
print("Enter 1 for ON and 2 for OFF")
while(counter < 10):
user_choice = input()
if user_choice == "1":
arduinoData.write("1".encode())
print("Light should be on!")
else:
arduinoData.write("2".encode())
print("Light should be off!")

Now we can upload our sketch as normal, but instead of opening Arduino's serial monitor, simply run your
Python code. Pin 13 should light up on 1 and turn off on 2 (or any other character other than 1).

We can also communicate with Arduino when there is a more complex circuit involved. For example, let's try
to turn a motor on or off. It's worth noting here that nothing will change in our Python code. We'll still connect
to the serial and enter a 1 or 2 to turn the motor on or off. A schematic (a diagram of an electronic circuit) and
sketch code for the motor circuit are provided below:

96
Sketch code for the Arduino IDE:

int UserChoice;
int motorPinPlus = 4;
int motorPinMinus = 5;
int motorPinEnable = 6;

void setup()
{
pinMode(motorPinPlus, OUTPUT);
pinMode(motorPinMinus, OUTPUT);
pinMode(motorPinEnable, OUTPUT);
Serial.begin(9600);
}

void loop()
{
Serial.println("1: Turn Motor On - 0: Turn Motor Off");
while(Serial.available() == 0){}
UserChoice; = Serial.parseInt();
if(UserChoice; == 1){
int motor_speed;
setMotor(true, 100);
Serial.println("The Motor is On");
}
else{
int motor_speed;
setMotor(true, 0);
Serial.println("The Motor is Off");
}
}

void setMotor(boolean forward, int motor_speed)


{
digitalWrite(motorPinPlus, forward);
digitalWrite(motorPinMinus, !forward);
analogWrite(motorPinEnable, motor_speed);
}

When we upload the sketch and open our serial monitor, the motor should turn on when we press 1 and off
when we press 0. The same should happen when we use PySerial instead.

37.9 - PySerial with Bottle

In section 34, we looked at Bottle, the micro web-framework for Python and used it to create the backend to
our website. Now imagine if we could combine what we already know in Arduino, PySerial and Bottle to create
a web app that controls an embedded system? This would open up a world of potential to create a home
automated system where, for example, you can control lights in your room from anywhere in the world via a
browser. Let's go ahead and get our motor to run, but this time via a web browser using Bottle.

We'll create a simple bottle app with two simple HTML forms, one with our ON button and another with our
OFF. Let's first do our imports, including serial:

import bottle
from bottle import run, get, post, request, route, error, default_app
import serial

97
Next, we'll create our routes. When the ON button is clicked, we'll access the / route via the post method and
run the code that sends “!” through the serial. When OFF is clicked, the /off route code is executed. In both
cases, we redirect back to the original form so that we can continue to be able to click the buttons:

@route('/')
def home():
return '''
<h1>Turn Motor On/Off</h1>
<form style="display:inline" action="/" method="post">
<button style="height:100px; width:100px" type="submit" >ON</button>
</form>

<form style="display:inline" action="/off" method="post">


<button style="height:100px; width:100px" type="submit">OFF</button>
</form>

'''

@route('/', method='POST')
def do_login():
arduinoData = serial.Serial('/dev/cu.usbmodem1421',9600)
arduinoData.write("1".encode())
return bottle.redirect('/')

@route('/off', method='POST')
def do_login():
arduinoData = serial.Serial('/dev/cu.usbmodem1421',9600)
arduinoData.write("0".encode())
return bottle.redirect('/')

run(host='localhost', port=8000)

Run the web app and head to localhost:8000 in a web browser. When ON is clicked, the motor should start!

98
SOLUTIONS
Are We There Yet?

Code:

driving_age = 17
age = int(input("What is your age?"))
years_to_drive = driving_age - age
print ("You have " + str(years_to_drive) + " years until you can drive")

Shorter Message Service

Code:

sms1 = "School is closed due to a sandstorm. Please check the website for more info"
sms2 = "School is closed. Sandstorm. Check website"
sms3 = "Sandstorm has closed the school. Please check website"

if len(sms1) <= 70:


print (str(sms1) + ". Number of Characters: " + str(len(sms1)))
if len(sms2) <= 70:
print (str(sms2) + ". Number of Characters: " + str(len(sms2)))
if len(sms3) <= 70:
print (str(sms3) + ". Number of Characters: " + str(len(sms3)))

To Drive or Not to Drive

Code:

name = input("Please enter your first name: ")


date_of_birth = int(input("Please enter your 4-digit year of birth: "))

if date_of_birth < 1995:


print ("Welcome " + str(name))
else:
print ("You are not old enough to register")

This Programmer is No Dodo

Code:

bird_list1 = ["Elephant Bird XT", "Woodcreeper", "Lyrebird", "King Island Emu XT", "Whistler", "Ovenbird",
"Bowerbird"]
bird_list2 = ["Dodo XT", "Scrubbird", "Upload Moa XT", "Oriole", "Cardinal", "Crested Shelduck XT",
"Amsterdam Duck XT"]
bird_list1.append("Red Rail XT")
bird_list1.extend(bird_list2)

for x in bird_list1:
if x[-2] in "X":
print (x)

99
Four, No More

Code:

name = ("Please type a baby name: ")

while True:
length= str(input(name))

if len(length) < 4:
print ('The name length is too short')
elif len(length) > 4:
print ('The name length is too long')
else:
print ('That\'s a valid name length')
break

Now We're Cooking!

Code:

def c_to_m(measurec):
return measurec * 236.588

def m_to_c(measurem):
return measurem / 236.588

print ("Press C to convert cups to milliliters")


print ("Press M to convert milliliters to cups")
print ("Press X to exit the program")

while True:
choice = str(input())

if choice == "C":
measurec = float(input("Enter the number of cups: "))
print (c_to_m(measurec))
elif choice == "M":
measurem = float(input("Enter the number of milliliters "))
print (m_to_c(measurem))
elif choice == "X":
print ("Program ended")
else:
choice not in "CMX"
print ("You must enter a C, M or X")
break

100
Logging the Login

Code:

# Import os, make system_info directory and open login_attempts.txt file in append mode
import os
os.mkdir("/Users/Air/Desktop/system_info")
new_file = open("/Users/Air/Desktop/system_info/login_attempts.txt", "a")

# Create tomorrow's pin variable and user input variable


tom_pin = 6572
check = ("Please enter the 4-digit pin: ")

# Create while loop and check


while True:
pin = int(input(check))
# Create nested if and else within loop that also prints to the text file
if pin != tom_pin:
print("Incorrect pin")
new_file.write("\nLogin failed")
else:
print("Welcome. You must be hungry")
# Close file and break loop after else statement
new_file.close()
break

We're Still Cooking!

Code:

Import and initial window setup


# Window is 411 pixels by 140 pixels
# Title of window is "Measurement Converter by SKO"

from tkinter import *


smokeyGui = Tk()
smokeyGui.geometry("411x140")
smokeyGui.title("Measurement Converter by SKO")

# This is where we declare the c_to_m function


# which gets the cups from an entry box and multiples it by 236.588

def c_to_m():
conversion1 = cups.get() * 236.588
label_1 = Label(text=conversion1).grid(row=3,column=2)
return

# This is where we declare the m_to_c function


# which gets the milliliters from an entry box and divides it by 236.588

def m_to_c():
conversion2 = mils.get() / 236.588
label_1 = Label(text=conversion2).grid(row=3,column=2)
return

# This is where we tell Python that cups and mils are ints

101
cups = IntVar()
mils = IntVar()

# This is where we place our .gif image that is 404 pixels by 57 pixels

kitchen = PhotoImage(file="/Users/Air/Desktop/smkitch.gif")
img_label = Label(image=kitchen).grid(columnspan=3)

# This is where we place our cups label, entry box and button to convert to milliliters

cup_title = Label(text="Cups: ").grid(sticky=E)


cups_entry = Entry(textvariable = cups).grid(row=1,column=1)
cups_process = Button(text="Convert to Milliliters",command=c_to_m).grid(row=1,column=2)

# This is where we place our milliliters label, entry box and button to convert to cups

mil_title = Label(text="Milliliters: ").grid(row=2,column=0)


mil_entry = Entry(textvariable = mils).grid(row=2,column=1)
mil_process = Button(text = "Convert to Cups",command=m_to_c).grid(row=2,column=2)

102

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy