Python Book PDF
Python Book PDF
ii
Alex Bowers
LearnToProgram, Inc.
Vernon, Connecticut
iii
LearnToProgram.tv, Incorporated
27 Hartford Turnpike Suite 206
Vernon, CT06066
contact@learntoprogram.tv
(860) 840-7090
2013 by LearnToProgram.tv, Incorporated
ISBN-13: 978-0-9888429-7-7
ISBN-10: 0988842971
All rights reserved. No part of this document may be reproduced or
transmitted in any form or by any means, electronic, mechanical,
photocopying, recording, or otherwise, without prior written permission of
LearnToProgram.tv, Incorporated.
Limit of Liability/Disclaimer of Warranty: While the publisher and
author have used their best efforts in preparing this book, they make
no representations or warranties with respect to the accuracy or
completeness of the contents of this book and specifically disclaim any
implied warranties of merchantability or fitness for a particular purpose.
No warranty may be created or extended by sales representatives or
written sales materials. The advice and strategies contained herein may
not be suitable for your situation. You should consult with a professional
where appropriate. By following the instructions contained herein, the
reader willingly assumes all risks in connection with such instructions.
Neither the publisher nor author shall be liable for any loss of profit
or any other commercial damages, including but not limited to special,
incidental, consequential, exemplary, or other damages resulting in whole
or part, from the readers use of, or reliance upon, this material.
Mark Lassoff, Publisher
Kevin Hernandez, VP/ Production
Alison Downs, Copy Editor
Alexandria OBrien, Book Layout
Ardit Sulce, Technical Writer
Jeremias Jimenez, Technical Editor
iv
Dedication
To the team at LearnToProgram: thank you for your trust and faith in
me. Working alongside you has been incredible.
A special thank you to Mark for his guidance and assistance throughout
the entire process.
Finally, a thank you to my parents, Caroline and Lee, and my brother
Jonathan, for putting up with my seclusion while I harbored and honed
my passion for programming.
vi
Table of ConTenTs
Getting Started ..................................................................................11
1.1 Acquiring the Tools ...................................................................... 11
1.2 Hello World in Python ................................................................. 19
The Basics ...........................................................................................23
2.1 Getting Started with Variables ................................................... 23
2.2 Data Types.................................................................................... 26
2.3 Arithmetic Operators ................................................................... 34
2.4 Understanding the Order of the Operators ................................. 36
2.5 Comments ..................................................................................... 37
2.6 Variable Scope.............................................................................. 38
Chapter 2 Lab Exercise ...................................................................... 40
Conditionals........................................................................................43
3.1 If Statements ................................................................................ 43
3.2 Else Statements ............................................................................ 46
3.3 Elif Statements............................................................................. 47
3.4 Switch Statements Workaround.................................................. 49
3.5 Inline if ......................................................................................... 51
Chapter 3 Lab Exercise ...................................................................... 53
# AND Truth Table: ........................................................................... 55
# OR truth table: ................................................................................ 55
# NOT truth table: ............................................................................. 56
# Main Challenge: .............................................................................. 56
Looping ................................................................................................60
4.1 While Loops .................................................................................. 60
4.2 For Loops ...................................................................................... 64
4.3 Try, Except, Finally ..................................................................... 68
4.4 Break, Continue, and Else ........................................................... 72
Chapter 4 Lab Exercise ...................................................................... 76
Lists ......................................................................................................80
5.1 A Closer Look at Lists .................................................................. 80
5.2 Modifying Lists ............................................................................ 84
5.3 Sorting Lists ................................................................................. 89
Chapter 5 Lab Exercise ...................................................................... 93
Receiving Inputs ................................................................................98
6.1 Press any key to continue .......................................................... 98
6.2 Data Input .................................................................................. 100
Chapter 6 Lab Exercise .................................................................... 104
Predefined String Functions ........................................................106
7.1 Using Strings as Objects............................................................ 106
7.2 Splitting and Joining Strings ................................................... 111
Chapter 7 Lab Exercise .................................................................... 115
Custom Functions ...........................................................................118
vii
viii
ix
CHAPTER 1
geTTing sTarTeD
ChapTer obJeCTiVes:
You will be able to set up the Python development environment.
You will be able to set up Eclipse with PyDev as the platform where the
Python code will be written.
You will be able to write and run your first Python program.
11
of the installers listed on the webpage. Which one you should choose
depends on your operating system. As my operating system is the 64
bit version of Windows 7, I would download the Python 3.3.1 Windows
X86-64 MSI Installer. Of course, you likely have a different combination
of hardware and operating system. Thats one of the nice things about
Pythonit runs on practically any hardware and operating system.
After the Python installer file has been downloaded, double-click on it
and follow the prompts to install it.
Next, well set up the Eclipse IDE (Integrated Development Environment)
where you can write, edit, debug and run the Python code.
Eclipse can be downloaded for free from its official webpage at:
www.eclipse.org/downloads
You will see many versions of Eclipse listed on the webpage. The one we
are going to use throughout this book is Eclipse
Standard (version 4.3 as of this writing) and
This book uses:
also known as Eclipse Kepler. Once the file has
Eclipse 4.3
been downloaded, double-click it to begin the
installation. (You may need to extract the file
from a compressed folder first.)
In general, Eclipse is a well-supported platform and can be used on many
operating systems. Eclipse is also designed to work with many different
programming languages. Ive used Eclipse for Java, PHP, and C++
development. Eclipse Classic will allow us to install an add-on so that we
may use the Python interpreter within Eclipse.
Figure 1.1: The Eclipse executable appears in the extracted Eclipse folder downloaded from
the website.
12
You might need the Java Runtime Environment installed on your system
before installing Eclipse. If you dont have it, you will be prompted
accordingly during the installation process.
If this is the case, you can download the Java Runtime Environment
from:
Oracles official Java site located at:
http://java.com/en/download/index.jsp
Tip: For Windows users, if you install the Eclipse IDE 32-bit version
then you must install the Java Runtime Environment (JRE) 32-bit
version. The same is true if you are installing 64-bit versions.
Also, if you install Eclipse to, for example, folder C:\Eclipse, then
you must override the default installation folder of the JRE and
install the JRE to C:\Eclipse\jre because this is where the Eclipse
IDE installation program will expect to find the Java Runtime
Environment. You can go to:
http://stackoverflow.com/questions/2030434/eclipse-no-java-jre-jdkno-virtual-machine to view various users comments and solutions
to various problems you may encounter while installing the Eclipse
IDE and the Java Runtime Environment for Windows.
After you have installed Eclipse and run it for the first time, you will see
a window that looks like this:
13
Now, we need to tell Eclipse where in the system the Python interpreter
is located. To do this, go to the New button.
Type a name for the interpreter. It does not matter what name you choose
1.1 Acquiring the Tools
15
16
Type a name for the project, change the Grammar Version to 3.0 and
choose your Python interpreter from the Interpreter drop-down list.
Mine would be Python3.3 which is the interpreter name I created in the
previous step.
Click Next and then Finish to close the window.
You should now see the PyDev project environment with its Package
Explorer window on the left-hand side as shown in the previous image.
17
18
Figure 1.8: Creating a new folder for storing Python script files
19
Enter a name for the file. Since this is the file where we are going to write
our first Hello World program, I will name mine Hello.py where py
is the file extension indicating that particular file is a Python script. Once
we have created our empty Python file, we can start coding right away.
The area within the Eclipse environment where you are going to write
20
print("Hello, world")
The print phrase is a Python keyword, which means it is a special word
that is used and recognized by Python as a function. The quoted text
Hello, worldis the text we are actually going to output. Notice that it is
surrounded by quotes and is known as a string.
After you write the code, you have to execute it in order to get the output
you want. To execute the code, go to the Run as button from the icons
menu and then to Python run and click OK. You should now see the
output printed at the bottom of the window. In our case the output should
1.2 Hello World in Python
21
#!/usr/local/bin/PythonDirectory
print("Hello, world")
The first line tells the interpreter where in your Linux machine the
Python installation directory is located. This line is often referred to as
the Shebang line. (Bonus: its fun to say Shebang!)
Youve just created your first program, congratulations! Weve kept it
simple to start off with, but you now have the basic knowledge of where to
write the code and how to run it in order to get your desired output. Youll
be writing more complicated programs as we move on through the next
chapters.
22
CHAPTER 2
The basiCs
ChapTer obJeCTiVes
number =100
In this example we have assigned the value of 100 to the variable
number. In other words, our container is now filled with the value of 100.
2.1 Getting Started with Variables
23
Note that the word number is just an arbitrary name we chose to give
to our variable. You have a lot of freedom when writing variable names.
However, there are a few things you should know about syntax rules of
writing variables. You will see that some variable names are not allowed.
The following examples
are correct variable
name declarations in
Python:
number
Number
Number_1
numberOne
_variableX
etc
1_number
+number
*number
As you can see, numbers and special characters (the only exception
being the underscore) are not allowed to begin a variable name. Besides
this important restriction, there is also a
Camel Casing
convention on Python variable names. The
convention suggests that you use the camel
Method
casing method. In camel casing, you start your
variable name with a lowercase letter and then you use capital letters if
your variable name is longer than one word. Here are some examples:
numberOne
thisIsAVariable
camelCasingWorks
Tip: While you have a lot of flexibility in how you name variables,
its important that you give the variables a name that has semantic
meaning. Name variables based on what they are representing.
If someone unfamiliar with your code were to read it, they should
have some idea of what a variable represents, just by the name.
24
number = 100
print (number)
We just assigned a value to the variable number and then we displayed
the variable value using the print command. After you run the code, you
should get the value of 100 displayed on the screen.
If we modify the above code a bit, you will see a different result.
When you see parentheses in Python code, work from the inside of
the parentheses outward to interpret the code. In this case, we have
embedded the type() function inside the print command and sent the
value of the number variable as an argument to the function.
number = 100
print (type (number))
Running this code, you should get this result:
<class 'int'>
The result is declaring that the value of the variable is of the type integer.
You will learn more about different data types in the next chapter.
Tip: Variable names in Python are case-sensitive. The variable
named number, written in all lowercase letters, will be different
from the variable named Number, which has the first letter
capitalized. If you assign a value of 100 to number and then try to
retrieve that value from Number, you will get an error.
25
number = 100.1
print (type (number))
Running this code, you should get this result:
In contrast to the value of 100 which was of type integer, in this case we
are dealing with a float type. Float is an approximation of real numbers
but does not include integers into its set. It is easiest to think of floats
(floating point numbers) as numbers with a decimal value at the end.
Float type values have a greater deal of precision than integers.
In Python it is possible to convert between different data types. This
conversion process is frequently called casting. Examine the following
code:
number = int(100.1)
print (type (number))
The result you get would be:
<class 'int'>
Look at the original assignment to the variable number. Before the value
26
number = int(100.1)
print (number)
The value displayed on the screen when the program is run is 100 instead
of 100.1. If we want to make the previous code more compact and have it
display both the converted value and its type at the same time, we would
write:
number = int(100.1)
print (type(number),number)
When run, this code would yield the following result:
a = "This is a string"
print (type(a),a)
The output would be:
27
a = """ This is
a string """
print (a)
or, alternatively:
a = "Hello"
b = "%s world" % a
print (b)
28
Hello world
%s and % are both reserved words. %s is a container that is waiting to be
filled with a value. Then, the character % indicates that the container %s
should be filled with the value of variable a. You will realize later that
these containers will come to be very useful when formatting complex
strings. If you are familiar with C style languages, you have likely seen
this concept before where character sequences such as %s are used to
output variable values.
We could also create the same output in another way:
a = "Hello"
b = "{} world".format(a)
print (b)
In the code above, we assign the string value to variable a in the first
line. Then, in the second line we are dealing with a string method which
is str.format(). This method replaces the {} part with the value assigned to
a. The output is then printed in the last line.
So far, we have worked numbers (integers and floats) and strings in
terms of data types. Now, we are going to learn two other important data
types: tuples and lists.
This would be a tuple:
X = (1,2,3)
and this would be a list:
Y = [1,2,3]
To get the types of X and Y, you can use the type() function similar to how
you used it with numbers and strings:
type(X)
type(Y)
2.2 Data Types
29
Lists:
mutable
Tuples:
immutable
Y = [1,2,3]
Y.append(4)
print (Y)
If you run this short program, the result you will get is:
[1,2,3,4]
If you were to try the append() function with the tuple in the same way,
you would get an error:
Figure 2.2: Python responds with an error when the append() method is applied to a tuple
The append method tries to mutate the tuplewhich is not allowed since
tuples are by definition immutable.
In addition to using append() to modify a list, you might also want to
access certain elements within a list or a tuple. Lets say we want to print
30
X = [1,2,3]
print (X[2])
Executing the code above, you would display the value 3 because it is the
third member of the list. X[2], within the print() function picks the third
element of the list. You might expect X[3] to select the third member of
the list, however, in Python, indexing begins at zero. This means any
object that holds a list of subsequent values will enumerate the first
value as zero. So, if we wanted to display the first element from the list,
we would write:
X = [1,2,3]
print (X[0])
We can use the same notation to extract a range of numbers within
the list, for example, if we wanted to extract the third, fourth, and fifth
values we could write the following code:
X = ["a","b","c","d","e","f"]
print (X[2:5])
When executed, this code would yield the result:
['c','d','e']
These are the elements with index 2, 3, and 4, respectively. Notice that
when we request the list values 2:5, we dont receive the fifth value. The
return stops before the second value in the request. 5:7 would return
elements with indexes 5 and 6. Similarly, just as we just did with lists,
we can access elements from tuples:
Y = (1,2,3,4,5,6)
print (X[2:5])
Now that you understand a bit about lists and tuples, we are going to
2.2 Data Types
31
D["Tom"]
We would get Toms phone number displayed on the screen. In addition
to the curly bracket syntax that you saw in the first example, dictionaries
can also be declared in another way:
Freedom = True
print (type (Freedom))
What you get as a result is this:
<class 'bool'>
32
Booleans
a, b = 0, 1
if a == b:
print (True)
else:
print (False)
In the first line of code above, we are assigning a value of zero for
variable a, and a value of 1 for variable b. The remaining block of code is
a conditional expression where we test if a is equal to b. If they are equal,
True will be displayed on the screen, otherwise False will be displayed. In
this case, the result would be:
False
The double equal sign == is a comparison operator that means
equivalency.
Tip: A common mistake made by those learning to program is
to confuse the = and the == operator. (Just be thankful Python
doesnt have a === operator, like Javascript does!) Remember that
= is the assignment operator used to assign a value to a variable.
The == operator is a comparison operator used to compare two
values.
==
Assignment Operator
Comparison Operator
Try to carefully observe the syntax and the structure of the code block.
Besides the usage of columns which are easily visible, you can also
see that we have shifted two of the lines to the right. This is called
indentation and it is very important in Python. Statements such as
print should be indented in the code when being used inside blocks
such as conditionals. You will learn more about indentation in the next
chapters.
33
Figure 2.3: The Python interpreter inside the Command Prompt in Windows
1+2
You just wrote and ran a line of code at the same time using only a few
clicks. However, notice that we are not saving the code inside a file as we
did in Eclipse, meaning that this method is just for testing purposes.
34
1*2
division:
1/2
Or exponentiation:
1**2
Try to understand what the following code does by observing its output:
round (3/4)
The program first divides four by three, and then rounds up the output
value to the nearest integer. To make things a bit more complex, try this
other expression which involves the modulus operator (%). The modulus
operator returns the remainder of the division.
round (0.75 * 1)
or:
round (0.75)
and the result would be zero in all three cases.
2.3 Arithmetic Operators
35
1-2*3
Some would expect that the first operator (-) is executed first and
therefore, the output would be a value of 3, but this is not true. As in
mathematics, the multiplication would be the first to be executed. If you
want the subtraction operator as the first operator, then you would have
to write:
(1-2) * 3
To sum it up, if you dont use brackets, the default operation order will be
applied to your expression, which is: exponents and roots, multiplication
and division (performing whichever operation appears first from left to
right), and last addition and subtraction (again, performing whichever
comes first from left to right).
36
2.5 CommenTs
So far we have written code that is executable, meaning that the code
does something and gives an output while being run. We can also write
code or descriptive text that we dont want to be executed, but instead
be ignored. This kind of text is referred to as comments. Comments can
serve either as descriptive text, as code that we dont want to execute,
or as code we want to execute at some later point. Try this example in
Eclipse and see what output you get:
Executable Code
Comments Code
Nonexecutable descriptions
2.5 Comments
37
def f(x):
y = x**2
print y
print f(3)
print y
print x
In this code we create a function that calculates and prints out the square
of a number. Two variables (x and y) are declared inside the function.
Both are local variables. In line 4 we are printing out the output of the
function when the input is equal to 3.
If we try to access these variables outside the function, as we are doing
in the previous code in the two last lines with the print commands, we
will be prompted that these objects are not defined and not recognized
as variables by Python. You will learn more about variables and the
usefulness of functions as we move on.
38
39
lab soluTion
a
u
v
t
=
=
=
=
0
0
25
10
a = (v - u) / t
print(a)
40
ChapTer 2 summary
In this chapter you were introduced to variables and we discussed
how to write them and how to assign values to them.
You learned the concept of data types and what data types are
available. You were also introduced to the basic syntax of assigning
values of different data types to variables.
Together with variables and data types, you were provided with
examples of basic mathematical operators and the rules of writing
them in the correct order.
You should been able to understand the usefulness of writing
comments and how to insert them into your code. You should now
know that comments can be written either for documenting your
code or for creating code that is to be executed at a later point.
Lastly, you gained a basic understanding of the variable scope
concept. You learned that the scope of the variables is either local
or global and you should understand what each of those terms
mean.
In chapter 3, you will be introduced to conditionals which are a
very important part of every programming language and allow
the performance of multiple actions depending on a wide range of
conditions.
41
42
CHAPTER 3
Chapter 3: Conditionals
ConDiTionals
ChapTer obJeCTiVes
You will be able to use conditionals including if, elif, else and inlineif
statements.
You will learn which statement to use depending on the scenario.
You will learn a workaround of switch statements.
You will be able to write conditionals on only one line using the inline
if statements.
3.1 if sTaTemenTs
In this chapter you will be learning about conditionals which are used
widely in every programming language.
Conditionals are statements that perform actions depending
on whether a condition evaluates as true or false. Here is an
example of a conditional statement:
a, b = 0, 1
if a == b:
print (True)
In the previous example, we are first assigning 0 and 1 to a and b,
respectively, and then we write the condition statement in the second line
(i.e. if a is equal to b). The third line contains the action to be performed
if the condition in the second line is met. You will not get any result from
this code because in this case, the condition is not meta is not equal to
b. So, nothing will happen. If we instead write:
a, b = 0, 1
if not a == b:
print (True)
3.1 If Statements
43
a, b = 0, 1
if a <= b:
print ("Yes, a is equal or less than b")
This would give:
Notice how the action to be performed (i.e. the print function) is indented.
How much it is indented it does not matter, but it should not be at the
same vertical alignment with the condition above.
Indentation
Indentation is an integral part of conditional
blocks. You should always indent the code that
comes under the conditional statements, just as we did in the previous
code. Keeping this in mind, lets try some more complex conditions. We
will write the previous code in another way and still get the same result
by using a bitwise operator.
Bitwise operators allow the evaluation and manipulation of
two or more input and are often used together with
conditionals. Or is an example of a bitwise operator.
Or
It is used to evaluate if at least one input is true.
44
Chapter 3: Conditionals
Here is an example:
a, b = 0, 1
if a < b or a == b:
print ("Yes, a is equal or less than b")
We could translate the second and the third lines into common language
in this way: if a is either less than or equal to b, then print out the text
Yes, a is equal to or less than b, which is actually true in our case.
Therefore, the output would be:
And
a, b = 0, 1
if a < b and a == b:
print ("Yes, a is equal or less than b")
We would read the code this way: if a is at the same time less than and
equal to b, then print out the text Yes, a is equal to or less than b, which
is not true in our case. Therefore, nothing would be printed out this time.
Please note the difference between the assign operator = and
the equal operator ==. The former is used to assign values to
variables, while the latter is usually used for testing if something
is equal to something else.
Bitwise Operators:
Or
And
3.1 If Statements
45
a, b = 0, 1
if a == b:
print (True)
Nothing happened, nothing was printed out. This is because the condition
in the second line was not meta was not equal to b. We might
find it useful to also trigger an action when the condition is not
Else
met. This is done through the else statement which is written
in the same structure inside the block as the if statement:
a, b = 0, 1
if a == b:
print (True)
else:
print (False)
In this case we would get False printed out:
The else statement and its consequent action are properly indented and
aligned with the upper part of the conditional block, similar to the if
statement. Notice that the indentation before the first and the second
print has to be in the same amount. For example, if you used a four
space indentation for the first print command, you have to use the same
amount for the second one.
46
Chapter 3: Conditionals
a, b = 0, 1
if a == b:
print ("a is equal to b")
elif a < b:
print ("a is less than b")
elif a > b:
print ("a is less than b")
else:
print ("a is greater than b")
You can include as many elif statements as you need inside the
conditional block depending on your needs. In the previous code, the text
that will be printed out is the one that meets the condition (i.e. a < b):
Try to play around by changing the values of a and b in the first line and
see what output you get. For example, if we assign 1 to both a and b:
a, b = 1, 1
if a == b:
print ("a is equal to b")
3.3 Elif Statements
47
elif a < b:
print ("a is less than b")
elif a > b:
print ("a is less than b")
else:
print ("a is greater than b")
We would get the first condition returned as true and therefore the
following text printed out:
Also keep in mind that if none of the if or elif conditions are met, the
action under else will be the one that is performed.
48
Chapter 3: Conditionals
Switch
a = dict (
one = 1,
two = 2,
three = 3
)
var = "two"
print (a[var])
The output of this code would be:
This is because 2 is the value that is tied to key two which is assigned to
the variable var. If you assign four to the variable, you will get an error
because there is no four key in the dictionary.
Another slightly different workaround to the switch method is
to use the built-in get function: This function returns a value
for a given key.
Get
a = dict (
one = 1,
two = 2,
three = 3
3.4 Switch Statements Workaround
49
)
var = "two"
print (a.get(var, "default"))
This code would print out the value that the key assigned to variable
var holds in the case when this key exists in the dictionary. Otherwise,
default will be printed out. In this case, we would get:
a = dict (
one = 1,
two = 2,
three = 3
)
var = "six"
print (a.get(var, "default"))
we would get:
Figure 3.9: default is printed out, as six does not exist in the dictionary
There is a lot of freedom for you to choose between working with elif
statements or using the switch statement workaround. However, these
were two examples that can be used as quick workarounds for the switch
method in Python in case you dont want to use elif statements.
50
Chapter 3: Conditionals
3.5 inline if
In addition to the conditional blocks we previously learned, there is also
another quicker way of writing conditions. This is known as inline if. In
this case, the condition and the action are both written in
Inline If
one line:
a, b = 0, 1
print (True if a == b else False)
This means that True will be printed if a is equal to b, otherwise False
will be displayed. In this case, the output would be:
Figure 3.10: True is printed out as part of the if clause inside the inline if statement
Similarly, you can include other types of expressions inside the inline if
and even assign the whole line to a variable:
a, b = 0, 1
var = "This is true" if a == b else "This
is not true"
print (var)
The output of this is:
Figure 3.11: Text is printed out as part of the else clause inside the inline if statement
The last code is a very commonly used case of the inline if functionality
as it allows variables to be assigned values depending on the conditions.
However, the inline if conditionals are restricted, meaning that they
cannot be used in complex expressions. When complex expressions are
3.5 Inline If
51
concerned, the standard if, else and elif statements, which you learned
in the previous sections, should be used. The multiline structure of the
standard conditionals allows us to write more advanced programs that
have conditional aspects at the core.
Chapter 3: Conditionals
You can see that the only place where two true
statements get passed is 1 and 1. This is the only
output which is true, the rest being false.
In this case I would utilize the and operator in Python to show you
exactly what is happening behind the scenes for the or truth table.
Python also has this built-in using the or operator. We can use this
functionality later on to save us from having to write unnecessary code.
53
NOT
|--------|
|A|Q|
|--------|
|1 |0 |
|0 |1 |
|--------|
Now for the real challenge! Try to write the code for the following truth
table.
The equation for this truth table is as follows:
A and not B or C = Q
The equation is read from left to right and would appear like this if
written in mathematical terms:
((A&~B)|C) = Q
Using the above tables, create a program that will give you the correct
output for the following table:
|----------------|
|A|B|C|Q|
|---------------|
|1|1 |1| |
|1|0 |1| |
|1|1 |0| |
|1|0 |0| |
|0|1 |0| |
|0|0 |1| |
|0|0 |0| |
|0|1|1| |
|--------------|
Good luck!
Note: The creation of the main challenge will involve using more
variables to store the current details in than shown above.
54
Chapter 3: Conditionals
lab soluTion
# anD TruTh Table:
a = 1
b = 0
if (a == 1 and b == 1):
print('1')
elif ((a == 1 and b == 0) or (a == 0 and b
== 1)):
print('0')
elif (a == 0 and b ==0):
print('0')
else:
print('Invalid Input')
# or TruTh Table:
a = 1
b = 0
if (a == 1 and b == 1):
print('1')
elif ((a == 1 and b == 0) or (a == 0 and b
== 1)):
print('1')
elif (a == 0 and b ==0):
print('0')
else:
print('Invalid Input')
55
# main Challenge:
a = 1
b = 0
c = 1
if(b == 1):
bHolder = 0
elif(b==0):
bHolder = 1
if(a == 1 and bHolder == 1):
else:
print('Q = 1')
else:
print('Q = 0')
56
Chapter 3: Conditionals
ChapTer 3 summary
In this chapter you were introduced to conditionals, which are a
very important part of every programming language as they allow
conditioned programming.
We discussed how useful the if statement is when you want to
perform an action that is dependent on a certain condition. Along
with the if statement, you learned that the code block preceding
the if statement should be properly indented.
You experimented with the else statement and understood that it
can be used as an alternative condition when the if statement is
not satisfied.
You performed multiple actions that were dependent on multiple
conditions made possible by the elif statement.
We also discussed an alternative workaround of the switch
statements used in other programming languages. You should
know that the switch workaround is also an alternative to the elif
statements.
Lastly, you worked out another quick way of building if statements
using the inline if alternative which, even though it is more
restricted in terms of the complexity of actions it can perform, can
be a quicker solution on certain occasions.
In the next chapter you will be introduced to the looping concept.
Looping is crucial when working with large amounts of data.
Basically, looping is used to run repetitive actions until a condition
is specified. It has a number of methods which you will learn
throughout the chapter.
57
58
CHAPTER 4
Chapter 2: Looping
ChapTer obJeCTiVes
looping
a = 0
while a < 100:
print (a)
a += 1
Tip: += in the fourth line of the sample code above is known as the
Add and Assignment operator. It will add 1 to the current value
of a and then replace a with this new value.
Try to run the previous code in Eclipse. You will get a list of numbers
from zero to 99, partially shown in the following output screenshot:
59
Figure 4.1: Generated numbers from zero to 99 (shown up to five in the screenshot)
Step
60
a = 0
while a < 100:
print ("Hello, world")
a +=1
Chapter 2: Looping
This time we are repeatedly printing out some text until it reaches the
value of 100:
Figure 4.2: Text printed out 99 times until the loop is exhausted.
a = 0
while a < 100:
print ("Hello, world")
a +=1
print ("The end")
61
a=0
a +=1
print loop block
Figure 4.3: The bottom of the output showing that The end is printed out after the while
loop output
62
Chapter 2: Looping
for i in [0,1,2,3,4,5]:
print (i)
This code iterates through all the elements of the list and prints them out
one by one:
Lets try to use the for loop for writing the sample code we wrote in the
while loop section:
for i in range(0,100):
print (i)
Even though it looks like a list is missing in the previous code, this is
not completely true. The list is generated via the range
function. The range function here builds a list from zero to
Range
100. Then the print function prints out every value of the
list. Again, numbers from zero to 99 would be printed out
line by line just as they were in the while loop example.
63
Even though the results between the examples of the while loop and the
example of the for loop are the same, you can see that the for loop has a
different structure. For loops are primarily used when you want to iterate
through lists, tuples or strings as in the following example:
for i in "Hello":
print (i)
In this case of string iteration we would get this output:
Figure 4.6: Printing out elements that have an even index inside the string
64
Chapter 2: Looping
The variable key fetches the index of every string while the variable i
fetches the strings itself. Both are variables. Notice that we also have
a function called enumerate in the first line. This function makes
possible the extraction of the indices and their
assignment to variable key. Then, in the second
Enumerate
line, the condition filters only the even index
values fetched by variable key. Notice that
the way we filter the even numbers is by using an if statement. The
% character here is a modulus operator that returns the remainder
of a number. If the remainder of a number divided by two is zero, that
number is an even number.
The third line under the if statement prints out some text written by us,
together with the elements of the Hello string that have an even index
value. Notice that the string elements are being printed using the str.
format() utility which we have gone through before. The previous code is
a good example of how different functionalities (i.e. for loop, if statement,
and str.format() can be integrated together for more complex and useful
programs.
Similarly to the previous example, you could try fetching the letters that
have an odd index number. The only line you would have to change would
be the if statement. This time we would go for a remainder of one, as that
is what odd numbers yield:
for key,i
in enumerate("Hello"):
if key % 2 == 1:
print ("The letter {} is in an even
location ".format(i))
Figure 4.7: Printing out elements that have an odd index inside the string
Similarly as you looped through lists and strings, you would also do it
with dictionaries but with some crucial differences that stand on the keyvalue structure of the dictionaries:
4.2 For Loops
65
a = {"one":1,"two":2,"three":3}
for i in a:
print (i, " corresponds to ", a[i])
In the first line, we declare the dictionary. Then in the second line
we start the for loop block. The variable i will fetch the keys of the
dictionaries. Remember that the key is the first element of a dictionary
pair. Then in the third line we repeatedly print out the value of i that is
the key. We also print out the phrase corresponds to and the value of the
dictionary. Remember that a value is the second element of a dictionary
pair. The output of this would be:
Figure 4.8: Printing out dictionary elements together with some text in between
As you can see, for loops and looping in general can be integrated into
different scenarios where different types of data are encountered.
66
Chapter 2: Looping
tuple = (1,2,3,4)
tuple.append(5)
for i in tuple:
print (i)
In the previous code, we are trying to append an element to the tuple, but
we know that tuples are immutable. Therefore, if you run the code, you
will get an error:
This error states that the object tuple has no attribute append.
Tip: Strictly speaking, append is a method and not an attribute.
However, to simplify error handling procedures, accessing a nonexistent method or attribute is lumped under an AttributeError
exception as shown in the text in red in Figure 4.9.
These errors are encountered during execution and they are
called exceptions. There is a way of handling exceptions and
this is done through the try and except functionality.
67
tuple = (1,2,3,4)
try:
tuple.append(5)
for i in tuple:
print (i)
except:
print ("This is an error")
This code would give this result:
In the previous code, after the program reads the first line where a tuple
is declared, it then executes the line under try. If the code of that line is
correct and does not contain any errors, it will be normally executed and
the line under except will be skipped. Otherwise, an exception will be
raised and the program will execute only the line under except instead of
the one under try.
There are different types of occurring errors. In the previous example you
were introduced to an attribute error, which inside the Python language
is known as an AttributeError.
An AttributeError occurs when the wrong attribute or method
is tied to an object. In the previous example, the append
method was tied to a tuple, but the tuple does not acknowledge
it as its method.
There might also be different types of errors such as an
IOError. An IOError is an error that occurs when the
68
Chapter 2: Looping
tuple = (1,2,3,4,5)
try:
tuple.append(5)
for i in tuple:
print(i)
except AttributeError as e:
print('Error formed: ' , e)
except IOError as e:
print('File not found:', e)
As appending elements to a tuple causes an attribute error, in the
previous example, the line under the first exception will be executed and
the result would be:
Notice that the second exception inside the previous code was ignored
because the tuple appending error was not an IOError. The exception to
be executed was the first one. This is because the first exception conducts
an attribute error. Therefore, the execution of the first exception clause
printed out the custom message Error formed and an internal error
message embedded inside variable e. This error message is embedded
inside variable e using the as command.
Finally
Besides try and except, there is also a finally clause.
A finally clause is always executed before leaving the
try statement, whether an exception has occurred or not. The clause is
4.3 Try, Except, Finally
69
tuple = (1,2,3,4,5)
try:
tuple.append(5)
for i in tuple:
print(i)
except AttributeError as e:
print('Error formed: ' , e)
except IOError as e:
print('File not found:', e)
print('The end')
In this case, the output of this code would be similar to the output of the
previous code but with the The end phrase added in the end. Here is the
output:
Figure 4.12: The output of the finally clause is added after the exception error message
These examples should give you a good start in handling different types
of errors. Using this try, except, and finally syntax, you will be able to
write more constructive and communicative code that can also be read
and used by other users.
70
Chapter 2: Looping
list = [1,2,3,4,5,6,7,8,9]
for i in list:
if i == 7:
break
else:
print (i)
The output of this would be:
Figure 4.13: List element printed up to element six as break sets it.
As you can see from the output, the printing out of the list elements ends
at element six because we are telling the program to stop the execution
when the for loop reaches the element seven. We do this using the
break statement. In case there was no element seven in the list, the else
statement would be executed.
A break statement can also be used in the same way inside a while loop.
Here is an advanced example of its usage:
var = 10
while var > 0:
print ("Current value :", var)
var -= 1
4.4 Break, Continue, and Else
71
if var == 5:
break
Tip: -= in the fourth line of the sample code above is the Subtract
and Assignment operator. It will subtract 1 from the current
value of var and then assign this new calculated value to var.
Notice that here we are using a decrementing while loop that starts at 10
and ends at zero. The loop block prints out some text together with the
value of variable var for each iteration. Normally, the printing out would
go from 10 down to zero and then stop if there was no break clause inside
the loop, but in this case, this is not true. The break clause will terminate
the printing out at element six. Here is the output:
Figure 4.14: Numbers printed out from 10 down to six where the break clause terminates
the loop
On the other hand, the continue statement is used to return the control
to the beginning of the while loop. The continue statement rejects all the
remaining statements in the current iteration of
the loop and moves the control back to the top
Continue
of the loop. Simply put, the continue statement
continues the execution of the block. Here is the example:
list = [1,2,3,4,5,6,7,8,9]
for i in list:
if i == 7:
continue
else:
print (i)
else:
print ("default ")
72
Chapter 2: Looping
In this case we are telling the program to continue the expression even if
the enumeration reaches the element seven. The output of the previous
code would be:
Figure 4.15: Elements printed out from the for loop block
The else statement itself has its own role inside a loop. When else is used
inside a for loop, it is executed when the loop has exhausted iterating
through the list. When else is used inside a while loop, the else statement
is executed when the condition becomes false.
Both break and continue are useful functionalities that give more control
to the work flow.
73
a = 0
while a < 100:
print (a)
a += 2
a. Print out numbers from zero to 100.
b. Print out zero and two.
c. Print out even numbers that fall between zero and 100.
d. Display an error message.
2. What does the range functionality do?
a. Generates a list.
b. Defines the looping method.
c. Generates a tuple.
d. None of the above.
3. The for loop is commonly used to:
a. Print out elements.
b. Execute some code until a condition is met.
c. Iterate through lists, tuples and strings.
d. Iterate through integers.
4. What is true about try and except?
a. The expression under try is executed when there is an exception.
b. The expression under except is executed when the expression under
try experiences an error.
c. Neither of the expressions under try or except are executed when an
IOError occurs.
d. All above are false.
5. What happens when the condition above the break code line is not met?
a. The continue part is executed.
b. The line under break is not executed.
c. The line under break is executed.
d. The whole program breaks.
74
Chapter 2: Looping
Fn = Fn 2 + Fn -1
with initial values of F0 = 0 and F1 = 1
This sequence is truly something amazing, and is found throughout
nature. By definition, the first two numbers in the Fibonacci sequence
are 0 and 1, and each subsequent number is the sum of the previous
two. There is also a geometrical representation of the sequence through
a spiral. The area of each of the squares is equal to a number of the
sequence.
75
lab soluTion
f0 = 0
f1 = 1
set = False
while True:
fn = f0 + f1
f0 = f1
f1 = fn
if (fn > 100):
set = True
else:
set = False
print(fn)
if (set == True):
break
76
Chapter 2: Looping
The above code was input and executed in Eclipse as file fibonacci22.py.
This is how the code and its output would look:
Figure 4.17: Lab solution (upper part) and the generated Fibonacci Sequence output
77
ChapTer 4 summary
In this chapter you were introduced to the looping functionality.
We discussed how looping comes to be very important due to its
abilities to repeatedly execute multiple statements dependent on
some conditions.
We explained both the while and the for loop. You should know
that the for loop is specifically used when iterating through
elements of lists, tuples, or strings. The while loop is more
condition-oriented and less explicit in terms of the element it
iterates.
We also went further and learned about error handling in Python
in the sense of how to give better control to the encountered errors
via the try and except functionality.
Furthermore, you were introduced to the break and continue tools
that are used to better control the flow of the looping.
In the next chapter we will be talking about lists more in-depth.
We will discuss list manipulation issues such as modifying,
deleting, adding and sorting list elements and we will perform
actions between different lists. You will get a better overall
understanding of the usefulness of lists.
78
CHAPTER 5
Chapter 5: Lists
ChapTer obJeCTiVes:
lisTs
a = ["a","b","c","d","e","f","g","h",
"i","j","k"]
print (a[2])
You would get the element c printed out because the index of c is 2:
Try to print out element j using its index. You will probably write this
code:
a = ["a","b","c","d","e","f","g","h",
"i","j","k"]
print (a[9])
5.1 A Closer Look at Lists
79
This is correct, but not very efficient. You had to count the long way from
left to right in order to get the index of element j. Dont worrythere is
a solution that is offered by negative indexing. Negative indexing starts
by accessing list elements from right to left or from the last to the first,
beginning at -1 and going backward. In our example, the k would be
indexed with -1, j with -2, and so on. To print out the element j
using negative indexing, we would write:
a = ["a","b","c","d","e","f","g","h",
"i","j","k"]
print (a[-2])
You will get:
You got the same output as you did previously, but this time you didnt
have to count the long way.
While working with lists and programming in general, you will probably
come across tasks where you have to handle big lists. Counting their
elements would be an exhaustive task. Therefore, knowing
Len
how many elements there are in a list can be very useful. The
len built-in function will return the number of the elements
that a list contains. Len stands for length. To find the length of list a, we
would write:
80
Chapter 5: Lists
a = ["a","b","c","d","e","f","g","h",
"i","j","k"]
print (len(a))
The output would be:
This means that the list has 11 elements. Here is a more practical
example:
a = ["a","b","c","d","e","f","g","h",
"i","j","k"]
print (a[len(a)-1])
The output would be:
As the length of the list is equal to 11, the len(a)-1 will be equal to 10
which is the index representing element k.
Besides accessing single elements from a list, you also learned how to
access a range of elements:
a = ["a","b","c","d","e","f","g","h",
"i","j","k"]
print (a[3:8])
81
You may want to print elements by iterating through indices with a step
other than one, for example two:
a = ["a","b","c","d","e","f","g","h",
"i","j","k"]
print (a[3:8:2])
In this case, you are ignoring index four and six which correspond to
elements e and g. The output of this would be:
82
Chapter 5: Lists
a = ["a","b","c","d","e","f","g","h",
"i","j","k"]
a.append("l")
print (a)
Append
Notice that a new element (l) has been added to the list.
This was done through the append method.
Sometimes, you might want to not just add one element
to a list, but an entire new list to a list- we can also refer
to this as merging lists. This merging or extending can be
done via the extend() method:
Extend
a = ["a","b","c","d","e"]
b = ["f","g","h","i","j"]
a.extend(b)
print (a)
83
List a
List b
You learned how to append an element to the end of the list and how
to extend a list by appending another list to it. You might have asked
yourself how one would add an element somewhere between the elements
of the list. The answer is the insert method. The insert
Insert
method adds an element to a specified position in the list.
Here is the example:
a = ["a","b","c","d","e"]
a.insert(3,"pause")
print(a)
You can see that the insert method takes two arguments (3 and
pause). The first argument defines the position index where the element
is to be inserted while the second argument is the inserted element itself.
The output of the previous code would be:
As you can see, the element pause is the new element inserted in list a
at index 3. The other elements beginning at index 3 have been pushed to
the right. Sometimes, you might want to change the value of an element
of your list. This is done easily, again by utilizing the indexing utility:
a = ["a","b","c","d","e"]
a[1]="x"
84
Chapter 5: Lists
print(a)
The output would be:
a = [10,20,30,40,50]
a[1] = a[1]*5
print(a)
In the previous code, we are changing element 20 by multiplying it by
five.
The output is:
85
a = [10,20,30,40,50]
del a[1]
print (a)
The output would be:
If the deletion of only one element is not enough, we can also delete more
than just one:
a = [10,20,30,40,50]
del a[1:4]
print (a)
In this case, the output would be:
Figure 5.14: Altered list after a range of elements has been deleted
The range 1:4 is the one that determines that the deleted items will be
the one with index 1, 2, and 3.
While the del method deletes elements based on their index, it does not
look at their value. If you were to delete an item whose index you dont
know, instead of del, you would use the remove method:
a = [10,20,30,40,50]
a.remove(30)
print (a)
86
Chapter 5: Lists
Reverse
a = [10,20,30,40,50]
a.reverse()
print (a)
Here is the output:
All these methods are continuously used when working with lists. They
are commonly used in integration with looping, especially with for
loops. This combination makes the data manipulation and processing a
powerful tool of the programming language.
87
You can see that list a has changed. Sometimes, you might want to retain
your original list. In this case we would assign the sorted list to a new
variable. This time we will use the sorted() method instead of sort():
88
Chapter 5: Lists
Except this time the sorted list resulted from printing out list b.
You might have been thinking of a way to also sort the list from greatest
to the least. The reverse method, which we worked out in the previous
section, is the one that comes in handy:
You could also sort strings using the exact same methods. Here is an
example:
89
Tip: Notice that even though the elements of the last list, based
on our perception, look like numbers, for the program they are
just strings. Everything inside quotes is a string and is therefore
treated as a string. You cannot perform mathematical operations
with strings, no matter if the characters are letters, symbols or
numbers. Eventually, the elements will be sorted as strings.
Sorting can become very useful when storing data in lists. An example
would be a list of peoples names.
90
Chapter 5: Lists
if len(["a","b","c"]) == len(["abc"]):
print (True)
else:
print (False)
a. Nothing.
b. Print out True.
c. Print out False.
d. Print out the length of the lists.
3. How would you delete an element with index a from list b?
a. b.remove(a)
b. b.delete(a)
c. del b[a]
d. remove b(a)
4. Number 3 is missing from list a = [1,2,4,5] we need to add it again.
There are different methods of adding number 3 to its proper position
(after number 2) inside the list. Which of these methods would be an
incorrect method of adding the number in its proper position?
a. a.append(3)
a.sort()
b. a.insert(2,3)
c. a.insert(-2,3)
d. a.insert(3)
a.sort()
91
8 7 12 4 9 6 5
You will be dealing with nested loops here, so be careful with indenting.
The proposed steps for the exercise are:
1.
2.
3.
4.
92
Creating the list with the elements in the order given previously.
Assigning the number of elements to a variable N.
Consider assigning a Boolean value to a variable.
Use the while loop for the rest of the exercise.
Chapter 5: Lists
lab soluTion
data = [8,7,12,4,9,6,5]
N = len(data)
swapped = True
while (swapped == True or N != 1):
swapped = False
position = 0
while (position < N - 1):
if (data[position] > data[position
+ 1]):
temp = data[position]
data[position] = data[position
+ 1]
data[position + 1] = temp
swapped = True
position = position + 1
N = N - 1
print(data)
93
This is how the solution and its output would look in Eclipse:
Figure 5.21: Lab solution (upper part) script and the rearranged list (bottom part) after the
script is run
94
Chapter 5: Lists
ChapTer summary
Even though you were already introduced to lists in the
previous chapters, in this chapter you were able to expand your
understanding of how to work with lists. You worked on accessing
list elements using efficient methods such as negative indexing.
Besides accessing single elements, we also discussed how to extract
ranges of elements from a list.
You learned how to modify list elements by adding, deleting
and editing them. To accomplish these modifying tasks, you
were introduced to the append, insert, remove, and del methods.
Furthermore, we discussed the extend method which is used to
merge lists.
We also looked at the sorting aspect of the list elements. We went
through the different approaches to sorting: the sort(), sorted(), and
reverse() methods.
So far, you have encountered only static output that is read-only
and does not allow its reader to perform any action. In chapter 6
you will be learning about user input, how to receive it and how to
perform actions depending on it. You will see that input capability
creates a sense of interaction between the end user and the
program.
95
96
CHAPTER 6
reCeiVing inpuTs
ChapTer obJeCTiVes:
print('Hello!')
input('Press any key to continue')
print('Thank you')
As you can see here, the first line will print out some text, and then we
prompt the user with a message (Press any key to continue) via the
second line. The text inside the input() parentheses is the message that
will be displayed to the user. You can write anything you want inside
those parentheses. After the message is displayed, program execution will
be suspended and will only resume when the user presses a key. When
the user presses a key, program execution will resume on the third line
which will print out some text. The first execution of the code will give
this output:
97
Notice that the third line was not executed because the input() method
suspends program execution at the second line and waits for the user to
resume by pressing a key on the keyboard. Besides pressing one or more
keys, you should also hit the return key to signal to the program that
you have finished pressing keys. After you press the return button, you
should get this updated output:
Notice that a third
line has been added to
the output. This third
line shows that
the user has
interacted
with the
program
by allowing
its full execution.
Figure 6.2: Output generated after the user has pressed a key
Tip: Notice that in the first example of this chapter we did not use
double quotes () but single ones (). This is just a matter of style
and there is no technical reason for choosing either way, as both of
the quote types play the same role.
However, there is a scenario where you would have to use proper
quotes. This is when your string contains quotes that have to be
part of the string. If the string contains single quote characters,
you would have to wrap it with double quotes and vice-versa.
An example of single quotes enclosed in double quotes:
The boy cried Foul! when he realized he had been cheated.
98
a = 1
Besides this, there are also implicit assignments such as:
Tip: Notice that the addition operator does not work only with
numbersit also works with strings, lists, tuples, and dictionaries.
However, when used with data types other than numbers,
the operator does not work as an addition operator but as a
concatenator. In other words, it merges strings with strings, lists
with lists, and so on.
Through the print function we are printing some text (Hello) together
with whatever the variable a contains.
When you first execute this block of code, you will be asked for your
name:
6.2 Data Input
99
After you type in your name and press the return key, an updated
output will be displayed, depending on what text you typed in.
Figure 6.4: Output generated after the user has entered a name
By following these steps, you have been able to write a program that can
communicate with the user. However, there is still more you can do.
Now, lets write a program that not only prints out the user input but also
processes it before displaying. Here is the example:
100
Notice that in the third part (str(b)), we are again converting the value of
b, which is a number, to a string. This is because we want to concatenate
it with the first two parts which are strings. The output of this code after
you have typed in a number (e.g. five) would be:
Figure 6.5: Output generated after the user has entered a number
As you progress with Python, you will come upon many use cases of
the input() method and better understand its power in user interaction
scenarios.
101
list = [1,2,3]
a = input('Add a number to the list: ')
list.append(a)
print (list)
the user is prompted to type in a number. If the user types in 4, what
would the program generate?
a. 4
b. [1, 2, 3, 4]
c. [1, 2, 3]
d. [1, 2, 3, 4]
2. When running the following code:
list = [1,2,3]
a = input('Add a number to the list: ')
list.append(int(a))
print (list)
the user is prompted to type in a number. If the user types in 4, what
would the program generate?
a. 4
b. [1, 2, 3, 4]
c. [1, 2, 3]
d. [1, 2, 3, 4]
3. Which of the following is true?
a. The two generated lists from question 1 and 2 were exactly the same.
b. The generated list in question 1 contains only string elements.
c. The generated list in question 2 contains only number elements.
d. The generated list in question 2 contains mixed element types.
.
102
lab soluTion
while True:
gender = input('Gender: ')
if(gender == 'M' or gender == 'm' or
gender == 'f' or gender == 'F'):
break
else :
print('Please try again')
print('You are: ',gender)
103
This is how the code and the solution would look in Eclipse:
Figure 6.8: Lab solution code (upper part) and the generated output together with the user
input (lower part)
ChapTer summary
In this chapter you learned how to make your programs interact
with the end user.
You were introduced to the receiving input functionality and you
learned how to make the program execution dependent on the user
action by using the input() function.
You expanded your understanding of the input() function by
learning how to use the user input inside your program and how to
manipulate it.
In the next chapter you will be learning ways of manipulating
strings. These string manipulation procedures are referred to as
string formatting in Python.
104
CHAPTER 7
You will learn how to use strings as objects by applying methods that
alter them.
You will learn how to access a full list of methods for every type of
object in Python.
You will learn to split string objects into parts and vice-versa.
105
As you can see, the string object has been divided into single objects that
are its elements.
Here is a more complicated example that you have encountered when
working with lists in the previous chapters:
a = "This is a string"
print (a[0:4:2])
Elements Picked
Start
End
SLICE PARAMETERS
Notice that we are using the same square bracket slicing syntax that we
use with lists. In the first line, we are assigning a string value to variable
a while in the second line we are printing a slice from the string. The
first parameter inside the square brackets indicates the first element
of the slice while the second indicates where the slicing ends. The third
parameter is the step that the slicing uses to pick elements of the string.
106
To come up with this output, the code first picked the element with an
index of zero from the string, which is the character T. Then it stepped
to the element with an index of two, which is the i character. Then it
would step to index four, but the syntax 0:4 defines that the range stops
at index four without including the element with index four. Therefore,
the elements picked out from the strings were T and i.
Lets have a look at methods used with stringsstring methods.
Methods are functions that are applied to objects such as
strings and that consequently alter or just use them for
different processing purposes.
Suppose we need to count how many occurrences of an element there are
in a string. There is a method that would come in handy in this case:
a = "This is a string"
c = a.count("s")
print (c)
You may have already guessed the answer:
Simply enough, we use the count() method to get the number of a certain
character inside a string. In this case, we counted how
many s characters our string contained.
count()
107
a = "this is a string"
c = a.capitalize()
print(c)
The capitalize() method is used to capitalize the
first character of the string. Here is the output:
capitalize()
Figure 7.4: The string after its first character has been capitalized
a = "this is a string"
c = a.title()
print(c)
108
Figure 7.5: The string after the characters of every word have been capitalized
Figure 7.6: A list of all methods associated with a string object pops up after the
programmer types in a period after the object instance name.
In the same way as described in Figure 7.6, you can access all the
methods of every object.
109
foldersAndFiles = ["C:","Folder/Subfolder",
"picture.jpeg"]
As shown in the previous code, our list contains our computer drive name,
our folder path, and the name of the file that we need to access. Suppose
that the file picture.jpeg is contained inside the path generated by the
folder names. We now need to generate a full correct path that can be
used later to access the file. We need to get together all the list elements
and join them with a slash character (/). Here is the code that would do
that:
foldersAndFiles = ["C:","Folder/Subfolder",
"picture.jpeg"]
path = "/".join(foldersAndFiles)
print(path)
The output you get is a string:
110
This way, we have the whole path of the file named picture.jpeg. In the
next chapters when we discuss file handling, you will understand that
this path is used to access and process files that are identified with it.
Now, lets look at the split() method which does the opposite of join().
The split() method will separate the string at each occurrence of a given
character.
Here is an example to illustrate what we are talking about:
print("This$text$contains$unwanted$symbols"
.split("$"))
Notice that the parameter that the split() method
takes is the character we want to split the text at.
This is the output:
Figure 7.8: List generated by splitting a string using the split() method
Notice that the output of the split() method is a list that contains the split
strings. If your intention was to clean up the text from the unwanted
characters without having a list output, we could extend our code like
this:
splitting =
"This$text$contains$unwanted$symbols".
split("$")
joining = " ".join(splitting)
print (joining)
7.2 Splitting and Joining Strings
111
In the previous code, we are first splitting the string by removing the
$ character from it and automatically converting the string to a list.
Then we generate spaces between the words where the $ was residing
using the join() method and automatically convert the list to a string.
Eventually you will get this output:
Figure 7.9: Text cleaned up after the split() and the join() methods have been applied to the
string
Sometimes, you may want to split only a part of the string and leave the
rest as it is. You can do this by using a second parameter inside the split()
method:
print("This$text$contains$unwanted$symbols"
.split("$",2))
The second parameter indicates how many splits will be done starting
from left to right. A parameter of two, as given in the previous code,
would mean that only the first two occurrences will be split. This is what
the output would look like:
The split() and the join() methods can be considered simple but very
important string methods.
112
"String".title()
a. object.method()
b. method().object
c. object.title()
d. object.operator
2. What does the second line of the following code do?
a = "this is a string"
c = a.capitalize()
a. It changes the value of variable a.
b. It assigns the value of variable a to variable c.
c. It capitalizes the letter a.
d. It assigns the altered value of variable a to variable c.
3. What does the split() method return?
a. A split string.
b. Several strings.
c. A list.
d. A split tuple.
4. What does the join() method return?
a. A list.
b. A string.
c. Several joined strings.
d. A tuple.
113
114
lab soluTion
passed = '82914656273523:a4edFea2786DGex'
data = passed.split(':')
id = data[0]
key = data[1]
if(id.isdigit()):
# Number is numeric.
if(len(id) == 14):
#Length of 14
if(len(key) > 10 and len(key) <
20):
print('ID and Key are valid')
else:
print('Key Length isn\'t
valid')
else:
print('ID wrong length')
else:
print('ID isn\'t a digit')
115
The solution and the output would look like this in Eclipse:
Figure 7.11: Code that validates some text (upper part) and prints out the validation result
(lower part)
ChapTer summary
In this chapter you were introduced to strings as objects
by learning how to apply methods that altered or extracted
information from them.
You were introduced to some of the methods applied to strings such
as count(), capitalize() and title().
You learned how to look for a full list of methods inside the Eclipse
platform, not only for string objects but for every type of object.
You worked with the join() and split() methods and you should
have an idea of their importance when working with tasks such as
file handling.
In the next chapter you will learn how to write your own functions
that return an output.
116
CHAPTER 8
CusTom funCTions
ChapTer obJeCTiVes:
def
117
actions you want to perform. These can be any type of actions such as
mathematical operations, printing out text, manipulating
return
objects, etc. The last line contains the return statement
which passes the output that the function yields and also
notes the end of the function. To illustrate the model, we are going to
write a function that converts kilometers to miles using the convention
that one kilometer is equal to 0.621371 miles:
def dist_convertor(km):
miles = km * 0.621371
return miles
This is a function with one parameter. The parameter is the
input value given to the function. It is given inside parentheses
after the function name.
In this case we have only one parameterthe local variable km. In the
second line we are declaring another local variable, miles. The second
line is the action that the function performs, which in this case is
multiplication. Then, in the third line, we are returning the value of the
miles variable.
However, you may be disappointed when running this block of code
because you would get no output out of it. This is because that code
merely defines a function.
To get the output we will need to call the function. Calling
a function means executing it by inputting some values as
parameters.
Here is how we call the function we defined in the previous code:
print(dist_convertor(10))
118
parameter
defined (def)
returned
called
Figure 8.1: Defining, calling and returning the output of a custom function
119
def printing():
print ("This function simply prints out
some text")
printing()
Here the function is defined in the first and the second line, while
the third line is where we call it. In this case we dont need to call the
function by using the print() built-in function because print() is contained
inside the action of the function. Executing the previous code gives this
output:
Now, after having worked out a function with one parameter and another
one with no parameter, lets have an example of a function with multiple
parameters. Calculating the travel distance of a vehicle that moves at a
certain velocity and acceleration at a given time would require a distance
function with three parameters: velocity v, acceleration a, and time t. The
formula that calculates the travel distance using these three variables is:
d = vt + (1/2)at2
Tip: You can easily write the formula directly in Python without
having to put it inside a function. However, you would have to do
extra work every time you wanted to calculate it using different
input values. Putting the formula inside a function has long-term
benefitsit allows you to reuse that formula very easily by just
calling the function.
120
Here is the function we would create to work out the distance formula:
def distance(v,a,t):
d = v*t + 0.5*a*t**2
return d
As you can see, we start the function using the def syntax and then we
write a name for the function and the three parameters separated by
commas inside the parentheses. The second line contains the formula,
while the last line indicates the value the function will return after it has
been called. So, lets call it by adding this line under the function:
Figure 8.3: Printed text together with the returned value of the function
Notice that the returned value of the function is 1600.0. The function
can also be utilized for further operations inside your code. Here is an
example:
print(distance(30,5,20) - 600)
121
Figure 8.4: The returned value after an operation with the function output
As you see, the function here acted as a variable by using its underlying
value which is the value that the function returns as output. You will
learn more about this in the next section.
Tip: While dealing with functions, do not forget the variable
scope issues that we discussed in previous chapters. You should
remember that any variable that is defined inside a function is
a local variable and cannot be used outside that function. Global
variables are those variables that are defined outside a function
and can be used both inside and outside functions.
122
def triangle_area(base,height):
return base*height/2
if triangle_area(10,3) >= 100:
print ("Great triangle")
else:
print ("Small triangle")
Here, we are first defining a function in the first two lines. Then, in the
following lines we are using the returned value of the function inside a
conditional block. In case the returned value of the function is greater
than 100 area units, a message will be displayed. If the returned value
of the function is less than 100 area units, another message will be
displayed. In case you didnt notice, our function behaved just like a
variable inside the conditional block. This is made possible by the use of
the return syntax when defining the function.
You also know that if you want to print out the returned value of the
function, you can just add a line at the bottom of the previous code, like
so:
def triangle_area(base,height):
return base*height/2
8.3 More on Returns
123
Figure 8.6: Conditional output using the function returned value also printed out on the
second line
Now, try to write the same code as before but instead of using return, use
the print() function as shown here.
def triangle_area(base,height):
print (base*height/2)
if triangle_area(10,3) >= 100:
else:
print ("Small triangle")
The output you will get is this:
Figure 8.7: Program causing an error because the function output is not a number
This is because the function is just printing out the output as text, and
not returning its actual value, which is a number. Using the print()
function can be a quick way to merely print out the output, but when you
124
want to use the output of the function in other operations as we did with
the conditional block, the return value is the standard way to go.
125
lab soluTion
def checkDataType(string):
myString = str(string)
if(myString.isdigit()):
return 'String is numeric'
elif(myString.isalnum()) and not
myString=="True" and not myString=="False":
return 'String is alphanumeric'
elif(myString == "True" or myString ==
"False"):
else:
return 'unknown string type'
print(checkDataType("Sample"))
print(checkDataType(True))
print(checkDataType(960))
126
Notice that in the last line we are testing the function by calling it with a
sample data type that is the string Sample. This is how the code and its
output would look in Eclipse:
Figure 8.8: Lab solution (upper part) where the function is defined and called and the
output (lower part)
127
ChapTer summary
In this chapter you were introduced to custom functions and you
learned how to define them. Going through examples, you practiced
writing functions with a different number of parameters.
You also learned how to call functions you have already defined by
inputting values as function parameters.
We discussed how functions can behave like variables and how
their values are used for further operations inside your script. You
should now know the difference between using the return and the
print statements.
You were also reminded of the variable scope concept which is
tightly related to the custom functions learned in this chapter.
In the next chapter, you will learn about classes, another critical
functionality of every programming language.
128
CHAPTER 9
Chapter 9: Classes
Classes
ChapTer obJeCTiVes:
Class variable
Data member
Instance variable
Inheritance
Instantiation
Method
Object
A class variable is a variable defined inside a class of which a
single copy exists, regardless of how many instances of the class
will occur.
9.1 Overview of Classes and Objects
129
130
Chapter 9: Classes
class Person:
def __init__(self,gender,name):
self.Gender = gender
self.Name = name
def display(self):
print("You're a ",self.Gender,", and your
name is ", self.Name)
Notice that this code is just the class creation part. As with functions, you
will not get any output if you run this code. You need to call an instance
of the class to get some results. Calling a class instance would be to run
the class by passing some attribute values to it. Before we do that, lets
first go through the code and explain it.
We intentionally used the term class in the title of this section. Just
like the def keyword which we used to start writing a function, the class
keyword is used to start writing a class. This is what we do in the first
line of the code. Here, we decided to name this class Person.
The second line of the code block is also a routine when defining a class.
It is where the class is initialized through the __init__
method and where the class attributes are given. The self
_init_
attribute is obligatory and it is always given to the class.
The other two attributes, gender and name, are given by
us.
Tip: Even though the self parameter is given any time a class is
defined, it is not a keyword in Pythonyou can use any name for
it. However, self is a strong convention among programmers and
we suggest you use the same word.
131
In the third and fourth lines of the previous code block we are connecting
all the attributes to self. In these lines, self is an object and Gender and
Name are variables within that object. We are capitalizing Gender and
Name here to make it visible that they are actually not the attributes we
passed to the __init__ method. Instead, they are local variables.
Then in the fifth and sixth lines, we define a custom method and call it
display. We pass self to this method. Because self now contains all the
attributes of the class, we can use them within the method. In this case,
we are printing out some text along with the attributes that will be given
to the class when being called.
To get an understanding of what this class does, we need to call an
instance of it. To do that, you need to add the following line under the
class you created:
Person("male","Me").display()
As you see here, you are calling an instance of the class using male as
gender and Me as name. In this case we are running the display method
contained within the class. Here is the output you will get:
Figure 9.1: Displayed text from the display method after the custom class has been called
Notice the syntax used to call the class. First, we wrote the class name
and two attribute instances inside the parentheses. Then, we called one
of the methods defined inside the class, which in this case is the function
display() which prints out some text along with the attributes of the class.
132
Chapter 9: Classes
Lab Activity
Consider the previous class example:
class Person:
def __init__(self,gender,name):
self.Gender = gender
self.Name = name
def display(self):
print("You're a ",self.Gender,", and your
name is ", self.Name)
Add another attribute to this class such as age, incorporate it inside the
display() method, and call an instance of the class.
133
lab soluTion
class Person:
def __init__(self,gender,name,age):
self.Gender = gender
self.Name = name
self.Age = age
def display(self):
print("You're a ",self.
Gender,", your name is ", self.Name, ", and
you are ", self.Age," year old")
Person("male","Me",25).display()
Here is how the solution and the output look in Eclipse:
134
Chapter 9: Classes
class Person:
def __init__(self,gender,name):
self.Gender = gender
self.Name = name
def display(self):
print("You're a ",self.Gender,", and your
name is ", self.Name)
What we have here is a class that has two methods. The first is the builtin __init__ method which is used to initialize the class. More specifically,
we can refer to __init__ as a constructor when an instance of the class is
created. The second method of our Person class is the display method
which we created for printing out some text.
Once the class and its methods have been created, you can access them
using the object.method() syntax:
Person("male","Me").display()
In this example, the part before the period is the object, and the part after
that is the method. The period itself is used after the object to indicate
that a method of the object is to be applied.
Notice that when we defined the display method, we used some variables
such as self.Gender and self.Name within the body of the method.
However, these two variables were not included as parameters of the
display method. The key here is the use of the self variable and the __
init__ method. Using the __init__ method you can define all the variables
you want to use within the methods of a class.
Though, you are not restricted to adding new variables to the methods
you define after the __init__ method. Here is an example where we add
9.3 Using Methods
135
class Person:
def __init__(self,gender,name):
self.Gender = gender
self.Name = name
def display(self,lastName):
print("You're a ",self.Gender,",
and your name is ", self.Name, lastName)
Notice that this time we are inputting a parameter to the display method.
To call an instance of this class, we would have to add the following line
under the previous code:
Person("male","Me").display("Pyto")
Here is how this example would look in Eclipse:
Chapter 9: Classes
class Person:
def __init__(self,gender,name):
self.Gender = gender
self.Name = name
def display(self,lastName):
print("You're a",self.Gender, "and
your name is",self.Name, lastName)
Person1=Person("male","Me")
Person2=Person("female","Anne")
Person3=Person("female","Frida")
Person1.display("Pyto")
Person2.display("Pyto")
Person3.display("Pyto")
Here is how the last example would look in Eclipse:
Figure 9.4: Defining a class: assigning class instances to global variables and running the
class associated methods.
137
This way, we can call the same method, but with different
variables by getting different outputs. In programming, this is
called encapsulation.
Lab Activity
Modify the previous example:
class Person:
def __init__(self,gender,name):
self.Gender = gender
self.Name = name
def display(self,lastName):
print("You're a ",self.Gender,",
and your name is ", self.Name, lastName)
By including all the three attributes (i.e. gender, name, and lastName)
inside the __init__ method, we leave the display() method with only the
self default attribute. We then call an instance of the class. The output
has to be identical to the output of the original code.
138
Chapter 9: Classes
lab soluTion
class Person:
def __init__
(self,gender,name,lastName):
self.Gender = gender
self.Name = name
self.lastName = lastName
def display(self):
print("You're a ",self.Gender,\
", and your name is ", self.
Name, self.lastName)
Person("male","Me","Pyto").display()
This is how the solution and the output would look in Eclipse:
Figure 9.5: Class Person having all the attributes inside the __init__ method.
139
class Example:
def __init__(self, **kwargs):
self.variables = kwargs
In the very first line, we define the name of our class, which is Example.
The __init__ method consists of the single third line which initializes the
class. Here is also where we write the variables. We have the self default
variable and another variable called **kwargs.
Like self, **kwargs is also not just a user-defined
Keyword
variable. In Python, kwargs is referred to as a
Argument
keyword argument. Any parameter that you pass
to the __init__ method will be stored in a dictionary
named kwargs. If there is only one asterisk placed before kwargs (such as
*kwargs) the parameters would be passed in the form of a tuple. In the
last line of the code, we are assigning the dictionary to a variable inside
our class. There is no need to use asterisks in this assignment statement.
Lets write the next part of the class. Paying attention to the indentation
aspect, you will have to add these lines under the previous code:
def set_vars(self,k,v):
self.variables[k] = v
Here we are creating another method which we have named set_vars.
This method will populate the kwargs dictionary with keys and values.
In this case, the k variable will hold the keys and v will hold the values.
In the first line, the parameters (self, k and v) of the set_vars method
are defined. The second line should be familiar to you. It is where the
dictionary is being populated with keys and values. In this case, self.
140
Chapter 9: Classes
def get_vars(self,k):
return self.variables.get(k, None)
This method will return the data of the dictionary based on the key we
pass in. In the first line, we start defining the method and pass the self
and k variables as arguments.
Then, in the second line we use the predefined function get
which is a dictionary method used to return dictionary values
based on their corresponding key.
When we call this method later, using a key instance that does exist
inside the dictionary, we will get the corresponding value; otherwise,
if the key instance is not contained within the dictionary, we will get
None.
Putting all the previous parts together wraps up the creation of the class
Example:
class Example:
def __init__(self, **kwargs):
self.variables = kwargs
def set_vars(self,k,v):
self.variables[k] = v
def get_vars(self,k):
return self.variables.get(k, None)
Now we can call some class instances. To do that, you need to add other
lines of code under the class you defined and showed previously:
141
In the first line here, we are assigning an instance of the class to variable
var. This class instance is passed with two parameters that are the two
key-value pairs that will populate the dictionary.
Then, in the second line we populate the dictionary with one more pair
of key and value. At this point, the dictionary within the class has three
pairs.
In the last two lines of code, we are calling the get_vars() method which
returns the corresponding value of a given key. In the first case, the
given key is name and in the second one the key is age. If these keys
are within the dictionary of our class, their corresponding values will be
displayed, otherwise None will be printed out.
The following figure gives the big picture of the whole example that we
used throughout this section:
Figure 9.6: Defining a class that fetches the values of the keys from a dictionary.
This is how you use the data stored inside an object created and stored
inside a custom class. This class can be used inside the program
whenever you need it.
142
Chapter 9: Classes
Lab Activity
Modify the previous code example:
class Example:
def __init__(self, **kwargs):
self.variables = kwargs
def set_vars(self,k,v):
self.variables[k] = v
def get_vars(self,k):
return self.variables.get(k, None)
var = Example(age=25, location='AL')
var.set_vars('name','Me')
print(var.get_vars('name'))
print(var.get_vars('age'))
so that you get this output:
Figure 9.7: The expected output after the original code has been modified.
143
lab soluTion
class Example:
def __init__(self, **kwargs):
self.variables = kwargs
def set_vars(self,k,v):
self.variables[k] = v
def get_vars(self,k):
return self.variables.get(k, None)
var = Example(age=25, location='AL')
var.set_vars('name','Me')
print(var.get_vars('Name'))
print(var.get_vars('Age'))
Note: As you can see, one solution would be to simply look for two
keys that do not exist in the dictionary such as Name and Age.
We populated our dictionary with the keys age and name and
because strings are case-sensitive in Python, the program could
not match the given keys Name and Age with the ones that the
dictionary contained.
Here is the solution and the output as shown in Eclipse:
Figure 9.8: Class that fetches values from a dictionary and an instance of it returning no
matched keys.
144
Chapter 9: Classes
9.5 inheriTanCe
As we already defined, inheritance is a transfer of the attributes of a class
to another class that was derived from it. Inheritance makes it possible to
use the methods of a class within another class. This way, you dont have
to define the same methods again in another class when writing large
programs. To illustrate inheritance, we are going to use two different
classes: the animals class and the dogs class. Animals share some
similar actions such as eating, breathing, and sleeping. A dog is part
of the animal kingdom and performs the same actions that an animal
does. Therefore, the dogs class can inherit the
actions from the animals class. The class that the
Superclass
methods are inherited from is called a superclass.
In our example, the superclass will be animals.
Lets write the superclass:
class animals:
def eat(self):
print ("I can eat.")
def breath(self):
print ("I can breathe.")
def sleep(self):
print ("I can sleep.")
What we have here is a class with three simple methods that simply print
out some text. Now we want to create another class that summarizes
what a dog can do. Instead of rewriting the list of actions that animals
perform, we can just inherit them:
class dogs(animals):
def bark(self):
print("I can bark.")
def guard(self):
print("I can guard.")
The first line of the code block is where the class dog is declared to be
inherited from the class animals. This means that the class dog has
now all the same methods that the class animals has. This is simply
done by putting the superclass animals inside the parentheses. The
9.5 Inheritance
145
next lines are other normal methods that are appropriate for the dogs
class. These methods are contained only by the class dog. Try to add the
following lines to see the output:
animals().eat()
dogs().sleep()
inherited class
superclass
Notice that even though the sleep method was not explicitly defined
inside the dogs class, it is a method of that class. Here is what the
complete code example would look like in Eclipse:
Figure 9.9: Defining a superclass and an inherited class, and calling their methods.
146
Chapter 9: Classes
Lab Activity
Add another class called hound to the previous code example:
class animals:
def eat(self):
print ("I can eat.")
def breath(self):
print ("I can breathe.")
def sleep(self):
print ("I can sleep.")
class dogs(animals):
def bark(self):
The hound
print("I can bark.")
class will represent
def guard(self):
the hound type
of dog which can
print("I can guard.")
animals().eat()
dogs().sleep()
147
lab soluTion
class animals:
def eat(self):
print ("I can eat.")
def breath(self):
print ("I can breathe.")
def sleep(self):
print ("I can sleep.")
class dogs(animals):
def bark(self):
print("I can bark.")
def guard(self):
print("I can guard.")
class hound(dogs):
def hunt(self):
print ("I can hunt")
animals().eat()
dogs().sleep()
hound().hunt()
148
Chapter 9: Classes
9.5 Inheritance
149
lab soluTion
class Payroll:
def __init__(self, name):
self.name = name
self.hours = 0
self.overHours = 0
self.wage = 0
def setEarnings(self, wage):
self.wage = wage
def setHours(self,hours):
self.hours = hours
def setOvertime(self,hours = 0):
self.overHours = hours
def calculate(self):
print(self.name , ' worked:')
print(self.hours , ' normal hours @
' , self.wage , ' for $' , self.hours *
self.wage)
print(self.overHours , ' overtime
hours @ ' , self.wage * 1.5 , ' for $' ,
self.overHours * 1.5 * self.wage)
print('Totaling: $' , ((self.
wage*1.5*self.overHours)+ (self.wage*self.
150
Chapter 9: Classes
Figure 9.11: The output shows the name of the person and the normal and overtime hours
worked and their respective rates together with the total.
151
ChapTer summary
In this chapter you were introduced to classes and the concepts
related to them.
You learned the syntax of defining a class and you defined your
own class samples and ran them using different instances.
You now know that methods are at the core of a class structure
and you know how to access class methods after a class has been
defined.
You should have an understanding of the use of keyword
arguments and how to store and return data from objects such as
dictionaries or tuples within classes.
You learned the inheritance concept and you should now know
that inheritance is the functionality you need to use when defining
classes that are inherited from larger classes.
In the next chapter, you will learn about file handling by learning
how to open, read, and write files that reside in your computer
using Python scripting.
152
CHAPTER 10
file hanDling
ChapTer obJeCTiVes:
You will learn how to open the content of a text file inside the Python
programming environment.
You will learn how to read and write the content of a text file into
another text file.
You will learn how to read and write the content of bigger text files.
You will learn how to read and write different types of files in
addition to text files.
Open
Before we go through some examples to see how the open
function works, we need to create a sample file in our
computer. For this, lets create a new text file. In my case, I created a
text file and inserted the section titles of this chapter and saved it in a
folder. You are free to save it in any folder you want, but be sure to keep
track of the folder path because that is crucial for Python to locate the
file. Another thing you need to keep note of is the file name. Here is a
screenshot of my file and its location:
153
Figure 10.1: Sample text file located in a folder in Windows operating system
Now we will try to open (read) the text contained inside the file in
Python. Here is the code that does that:
print (line)
What the function open does, is fetch the data contained inside a file. This
fetched data is then assigned to a variable. This is exactly what we do in
the first line of our code blockwe are assigning the data of the Section.
txt file to our variable named file. Notice that you should specify the
complete path directory of your file so that Python can locate it.
Tip: If the file you are trying to open resides in the same directory
with the Python script you are writing, you do not have to declare
the whole path of the directory. In this case, only the file name
would be enough for Python to locate the file.
154
Then, in the second and the third line, we use the print function via a for
loop to display the data contained inside our text file. Notice that we are
using the print function in the same manner we used to print out lines
from an array. The output of the previous code would be this one:
Figure 10.2: Displayed data from an opened text file using the open function.
The code we wrote was very basic without having any advanced
functionality. You may have noticed that the text lines we displayed are
separated by empty lines. To remove these empty lines, we
End
would add an end parameter to the print function, like this:
Figure 10.3: The spaces between the text lines are removed using the end parameter.
The end parameter specifies how the lines contained inside the text file
will be separated when displayed via the print function. In this case, we
set that the lines will not be separated by blank lines. You could put any
character you want inside the quotes and the lines will be separated by
that character. In this case we did not input any character separator.
10.1 Opening Files
155
input = open("C:/FileHandling/Sections.
txt","r")
output = open("C:/FileHandling/New.
txt","w")
for line in input:
In the first line we are fetching the text from Sections.txt and assigning it
to the variable input. The parameter r indicates that we are reading the
content of the file. This is the same thing we did in the examples of the
previous section. The use of r is optional. The default action that the open
function does when used with one parameter is reading the file. However,
in this case we decided to use the r parameter as just a matter of style.
You do not have this freedom when you want to write inside a file. In
this case you have to use the w parameter to let the program know
what you want to write inside the file. This is exactly what we do in the
second line of our code. Then, in the third and fourth lines we complete
the writing process. Notice the similarity of these lines with the lines we
used to print out the text in the examples from the previous section. The
crucial difference here is the insertion of another parameter inside the
156
print function, which is file = output. This parameter tells the program
to insert the content inside a file. This file is represented by the variable
output which contains the New.txt file path location. After running this
code, go to the folder where your New.txt file resides and open it to see if
the content has been written inside. You will have something similar to
this:
Figure 10.4: Text file after the content has been written using
the open function with the w parameter.
Tip: If you want to add the content of a text file below some
existing content of another text file, you must use the a parameter
instead of w. The a parameter stands for append and it will append
the content instead of overwriting it.
In the example we just used, we had to deal with only three lines of text
and the code we used does the job perfectly. However, if the number of
text lines inside the text file was significantly higher, our code would
have trouble processing it because the for loop we are using would have
to go through every line one by one. If you were to handle bigger text
files having a considerable amount of lines, we would suggest another
approach. Lets go through this and handle a real life text file that
contains more than 30 thousand lines of text. This is how a part of the file
looks:
Figure 10.5: A big text file that has to be read and written using a buffer
157
You can create your own big text file by simply copying some big text
inside an empty text file. Give a name such as BigFile.txt and save it in a
folder. You do not need to create an empty new file (where the text will be
written) manually because this will be created by the code.
To work with this big file in Python, this time we will be using a buffer
instead of the for loop. A buffer provides a faster way to
read and write a text file because it reads and writes the
Buffer
data by big groups of text. This technique works on a
byte basisit reads and writes the content of the file by
accessing groups of bytes. In our case, the code we would use to write all
the text from one file to another is:
buffersize = 1000000
txt','r')
output = open('C:/FileHandling/New.txt',
'w')
buffer = input.read(buffersize)
while len(buffer):
output.write(buffer)
print('.', end='')
buffer = input.read(buffersize)
First, we create a variable and assign it the number of bytes that the
reading algorithm will be stepping through. In this case, the algorithm
will access groups of 1 million bytes of data. The whole file has a size of
9,351,168 bytes.
Then, in the second and third lines, we create one file input and one file
output variable with the respective read and write capabilities. In the
fourth line, we create a buffer object that will store the output based on
the buffer size we specified previously.
Then we move on to the next block which is a while loop. This loop
will iterate through text buffers and write them to the output file. As
the writing continues, we are printing out some dots where every dot
represents a written buffersize of 1,000,000 bytes:
158
Figure 10.6: Reading and writing a text file using a buffer and a while loop
159
buffersize = 1000000
input = open('C:/
FileHandling/Python.jpg','rb')
output = open('C:/FileHandling/NewPython.
jpg', 'wb')
buffer = input.read(buffersize)
while len(buffer):
output.write(buffer)
print('.', end='')
buffer = input.read(buffersize)
Here, again we are using a buffer size of one million bytes. So, the
reading and writing will be done every one million bytes. In the second
and third lines we set the input location and file name. Notice here that
we are using the rb and wb parameters where rb stands for read binary
and wb for write binary. These are the parameters to be used when
the files are not text files. The while block is the same block we used in
the example of section 10.2. So, the only conceptual difference of this
code from the previous one we used with text files, is the use of binary
parameters for the open function rb and wb.
160
print (i)
a. Prints out the i character contained inside the Sections.txt file.
b. Prints out the content of Sections.txt on a line by line basis.
c. Creates a file called Sections.txt.
d. The code will not work due to syntax errors.
2. Why do we set a big buffer size number?
a. To have the code run more quickly.
b. To have a big number of iterations.
c. To have a consistent number of lines.
d. To have the bytes printed out correctly.
3. What is not true about the buffer technique?
a. It is used to have a quicker execution of the code.
b. It works with all types of files.
c. It accesses the content on a byte basis.
d. It works better with text files.
161
lab soluTion
class LogMessage:
def read(self):
lines = f.readlines()
for each in lines:
print(each, end='')
def write(self,message):
f.write(message)
log = LogMessage('test.txt')
log.write('Testing' + '\n')
log.write('test123' + '\n')
log.read()
162
Figure 10.8: Lab solution with the output after the sample file has been processed.
163
ChapTer summary
In this chapter you were introduced to the concepts of file handling.
You learned how to access text files from the Python programming
environment.
You worked with reading and writing text files using the open
function and the for loop by accessing the content line by line.
You also worked with the while loop by accessing the content on a
byte basis and you understood when to use the for loop and when
to use the while loop.
We discussed the buffer technique and you learned how to read
and write file types that are not text files and you should now know
how to use the proper parameters for reading and writing binary
files.
In the next chapter, you will learn about database handling, which
is a similar file handling.
164
CHAPTER 11
DaTabase hanDling
ChapTer obJeCTiVes:
You will learn how to interact with a database from within Python
by creating database files, database tables, and building table
structures.
You will learn how to insert and update records in database tables.
You will learn how to query database data by retrieving records and
using their values for various operations in Python.
You will learn how to delete existing table records.
import SQLite3
db = SQLite3.connect('database1.db')
First, we need to import the SQLite3 library in Python. This is done using
the import command along with the name of the library. Once we import
it inside our program, we can use the library and its builtin functions as many times as we want. In the second line
import
we make a connection to a database. In this example, the
name of the database is database1.db. If this database
11.1 Creating the Database
165
All we did so far was create an empty database file and established a
connection with it. Now, we are going to create a table inside the created
database that is constructed by fields. To do that, we need to write some
code inside Python, using the SQL language.
SQL is a programming language designed to manage data held
in databases. Through the slqlite3 library, Python allows SQL
code to be written inside its environment.
Here is the complete code that creates two tables with three fields each:
import SQLite3
db = SQLite3.connect('database.db')
text, secondname text, age int)')
db.execute('create table book (title text,
author text, genre text)')
Notice that the first two lines remain the same. Then, in the second and
the third lines we create the tables person and book respectively. The key
tool to create the tables here is the execute() method which is attached
after the database object (db) we created earlier. The execute() method
executes SQL code inside Python. Therefore, all the code
we write inside the parenthesis following execute() is SQL
execute()
code.
Lets take a closer look at the first SQL statement contained within the
execute() method:
166
import SQLite3
db = SQLite3.connect('database1.db')
db.execute('drop table if exists person')
text, secondname text, age int)')
db.execute('drop table if exists book')
text, secondname text, age int)')
The lines we added will overwrite the existing tables within the database
file with the new ones as created by the code. In the next section, we will
populate the tables with sample data.
167
Lab Activity
Create a new table within the existing database. Name the table
triangle, and add three fields, type, area and rightTriangle. Try to
assign the appropriate types for each of the fields.
lab soluTion
import SQLite3
db = SQLite3.connect('database1.db')
db.execute('create table triangle (type
168
import SQLite3
db = SQLite3.connect('database1.db')
secondname, age) values ("John",
"Smith",25)')
db.commit()
Running this, a first record will be inserted inside the database1.db file.
You should be familiar with the first two lines which are identical to the
code example from the previous section. Then, in the third line, we have
the execute() method with its SQL code arguments inside its parentheses.
In this line we insert the values John in the firstname field, Smith
in the secondname field, and 25 in the age field. To execute the whole
process, you need to add a commit() method at the end of the code. If
you now open the database1.db file, you should see that some values
have been added. To have a structured view, you would need a database
management software which is specialized to handle database files.
169
You might come across scenarios where you want to alter some particular
records. Here is an example where we change the age of John Smith from
25 to 35:
import SQLite3
db = SQLite3.connect('database1.db')
db.execute('update person set age = 35
where secondname = "Smith"')
db.commit()
Notice how the argument inside the execute() method changes. In this
case, we used the update SQL keyword instead of insert. We may have
many records within a table, therefore, we have to include a reference
of the record we want to update. In this case the reference is the
secondname field. That means we are updating only the record where the
secondname field is equal to John.
In the same way, you can insert and update other records from any
existing table that resides inside your database file. In the next section,
you will be learning querying operations such as retrieving and deleting
records.
170
Lab Activity
Insert a new record inside the existing table book using the information
from your favorite book.
lab soluTion
import SQLite3
db = SQLite3.connect('database1.db')
db.execute('insert into book (title,
author, genre) values ("Gulliver\'s
Travels", "Jonathan Swift","Fantasy")')
db.commit()
171
import SQLite3
db = SQLite3.connect('database1.db')
table = db.execute('select * from person')
for i in table:
print(i)
Again, whenever we need to interact with a database, the appropriate
library has to be called using the import command. Then, a connection
with the database is established. In the third line, we
create a variable called table that will hold the table data.
cursor
This is called a cursor object and it holds data that has
a database format. As with the previous examples, inside
the execute() method, we had to write SQL code. This time using SQL we
select all (*) the data from table person.
At this point, we have fetched that data and stored it inside the table
variable. Now, we can do whatever we want with it. In this case, we are
printing it out using a for loop. The for loop will access the data on a
record basisit will print out the records one by one. When you run this
code, you shall get this result:
This way, we have retrieved the data from a database and used it within
Python. In this example we retrieved all the data, but sometimes you
might want to select only the records of some specific fields within a table
172
such as firstname and secondname for example, and not the age. In this
case, you would not use the asterisk (*) symbol:
import SQLite3
db = SQLite3.connect('database1.db')
secondname from person')
for i in table:
print(i)
Notice that this time we explicitly declared what fields we want to fetch
the records from. Here is the result:
Sometimes, you might want to have the table field names attached to
every record value. In this case, we would go for a dictionary approach in
Python. To do that, you need to activate row_factory which is a function
of slqite3 that enables the retrieval of the data in
form of a dictionary. Here is the code that fetches
row_factory
and displays the records with their field names
attached in a dictionary format:
import SQLite3
db = SQLite3.connect('database1.db')
db.row_factory = SQLite3.Row
table = db.execute('select * from person')
for i in table:
print(dict(i))
173
delete
import SQLite3
db = SQLite3.connect('database1.db')
table = db.execute('delete from person
where secondname = "Smith"')
db.commit()
for i in table:
print(i)
Notice that the code is mostly the same as the previous ones. The only
thing that changes is the SQL part. Here we are telling the program
to delete the row that meets the criteria after the where clause, which
consists of the record where the second name is Smith.
Learning these commands enables you to have a clear understanding of
the interaction between Python and a database.
Lab Activity
Retrieve and print out the record you inserted into table book in the lab
activity from section 11.2.
lab soluTion
import SQLite3
db = SQLite3.connect('database1.db')
table = db.execute('select * from book')
for i in table:
print(i)
In my case, the result would look like this in Eclipse:
175
lab soluTion
import SQLite3
class LogMessage:
def __init__(self,dbname):
self.dbname = dbname
db = SQLite3.connect(self.dbname)
db.execute('create table if not
exists LogMessage (message)')
db.commit()
db.close()
def read(self):
db = SQLite3.connect(self.dbname)
data = db.execute('select * from
LogMessage')
for each in data:
print(each)
db.close()
def write(self,message):
db = SQLite3.connect(self.dbname)
db.execute('insert into LogMessage
176
177
ChapTer summary
In this chapter, you learned how to interact with a database from
within Python and how to create a database file where database
structured data can be stored.
Using examples, you practiced creating new tables within the
database and structured those tables with new fields with
appropriate data types, while also learning how to insert new
records inside an existing table and also how to update existing
records inside a table.
You were introduced to the technique of retrieving data from a
database table in order to use them within Python. You were able
to store these data within various Python data types such as tuples
and dictionaries.
You also learned how to delete existing records from a table.
In the next chapter, you will learn about modules, how to use and
create them.
178
CHAPTER 12
moDules
ChapTer obJeCTiVes:
with your other data. Here is the code that would provide the date and
time of every given moment:
import datetime
dt = datetime.datetime.now()
print (dt)
As you already know, in the first line, we first have to import the library
in order to use its functionality. Then, in the second line we create a
variable called dt. The dt variable contains the output
now()
value of the now() function which is the function that
generates the current date and time. Function now() is
contained inside a class called datetime. Therefore, the way we call this
function is datetime.now(). The datetime class itself is contained within
the datetime library. So, the complete expression is datetime.datetime.
now(). To sum it up we can say that function now() belongs to the
datetime class which belongs to the datetime library.
Here is the expected result:
Figure 12.1: Current (at the time of the code execution) date and time
Notice that the timestamp you get back is very precise. This may come
in handy sometimes. A very general example of the time functionality,
no matter what kind of program you are building, would be when you
want to test different blocks of your code to see which runs slower than it
should.
Suppose you had a big program that takes a lot of time to run and you
want to know which part of it is causing the delay. In this case, the
datetime library functionality would become very useful.
In such a case, you would wrap blocks of your code within current time
functions and calculate the difference from the time the block of code
starts running to the time the running ends. Suppose one of the code
blocks inside your program is a while loop. In this case, we would use the
current time function like this:
180
import datetime
i=0
start = datetime.datetime.now()
while i<1000000:
i=i+1
end = datetime.datetime.now()
print (end-start)
Tip: Remember that the code in Python is executed starting from
the top of the script and going down to the bottom line, executing
every line one by one.
In our code, we start by importing the datetime library. We also create a
variable with an initial value of zero. Then, we create another variable
that will store the current time which coincides with the time the while
loop block will be executed. The next two lines are the while loop block.
The action that the while loop will perform is adding one to variable i
starting from zero and up to one million. Immediately after the while loop
execution ends, another variable called end will store the current time,
which is the time the while loop execution finishes. Then we just need to
print out the difference between the end and the start time to see how
much time it took for the while loop to finish its action.
Depending on your computer parameters, you might get a different value
than mine:
In my case, the time interval was around 0.31 seconds. You can try to
experiment and test the execution time of other codes you have learned
throughout this book.
181
import sys
print (sys.path)
First we import the library and then we access one of its functions path
by printing out its output. Simple enough, right?
In my case, I get this result:
You might use this function when you need to know or use the directory
of your project or the modules.
These were just a few standard library functions. As you program with
Python, new needs may arise for other functions. In that case, the
standard library list under http://docs.python.org/2/library/ is a good
place to look for information.
182
Lab Activity
Try to print out the day of the week using the datetime library.
Hint: Use the weekday() function and be aware that the days in
Python are defined with numbers starting from zero for Monday, to
six for Sunday.
lab soluTion
import datetime
dt = datetime.datetime.now()
print (datetime.datetime.weekday(dt))
Here is the output I received from it:
Figure 12.4: Three printed out indicating that the day of the week is Thursday.
183
def greeting():
print (Hello, this is a module
function)
x = This is a module variable
You should be able to easily understand this code. We have just written
a function that prints out some text when called, and we have assigned a
string to a variable.
Save the SampleModule.py file and open the other Python file you
created. You can name this file SampleModuleTest.py. In this empty
file, you can now import the new module whose name is defined by the
script name, SampleModule. Then you are free to use all its functionality.
In this example we can use its variable and function:
import SampleModule
SampleModule.greeting()
print(SampleModule.x)
First, we imported the module, and then in the second line we called its
function. In the third line we print out the value held by variable x.
The result of the execution would be:
184
SampleModule.greeting()
a. It executes the module SampleModule.greeting().
b. It creates the function greeting() within the module.
c. It creates an instance of the greeting() function.
d. It calls the function greeting() contained in SampleModule.
Lab Activity
While in an empty string, import all the components of the module
SampleModule in such a way that you will not have to reference the
module name any time you want to call an object.
Tip: Make use of an asterisk. (*)
lab soluTion
from SampleModule import *
greeting()
print(x)
185
Figure 12.6: Calling all module components waives the need to reference the module name
every time.
186
classname
That will import the relevant class and will allow you to use the class as
it is written inside the script. If you need to use the other class, you can
simply change classname to the other class, and the database name to the
filename, and everything should work.
To test this, create the module LogMessage and then import it into a
previous lab exercise and test them both out. They should both work.
lab soluTion
import sqlite3
def __init__(self,dbname):
self.dbname = dbname
db = sqlite3.connect(self.dbname)
db.execute(create table if not
exists LogMessage (message))
db.commit()
db.close()
def read(self):
db = sqlite3.connect(self.dbname)
data = db.execute(select * from
LogMessage)
for each in data:
print(each)
187
db.close()
def write(self,message):
db = sqlite3.connect(self.dbname)
db.execute(insert into LogMessage
(message) values (?), (message,))
db.commit()
db.close()
class LogMessageFile:
def read(self):
lines = f.readlines()
for each in lines:
print(each, end=)
def write(self,message):
f.write(message)
ChapTer summary
In this chapter, you were introduced to standard libraries that
Python offers to expand the programming functionality. You
now know that when you need extended functionality beyond the
built-in modules that Python offers by default, you should look for
standard libraries and import them inside your program.
You worked with the datetime library and learned how to use it
to test the execution time of your programs allowing you to find
delaying obstacles inside your big programs.
You learned about the sys library which provided information
about directory paths.
You created your own module and used its functionality inside
script files.
In the next chapter you will learn about debugging your programs.
188
CHAPTER 13
Debugging
ChapTer obJeCTiVes:
You will learn how to detect syntax errors and be able to understand
where they occur in the script.
You will learn how to debug detected errors and free your code from
them.
You will learn how to detect errors at run time that suspend the
program from completely executing and debug them for getting the
expected output.
name = 'John'
if name = 'John'
print('Your name is John')
i = 5
j = 15
k = ((i*j) + (j+i)
print(k)
189
First we assign the string John to the variable name and then we make
a test using the if statement to see if the variables value is equal to
John and print out some text if the test succeeds. Then, we create two
variables, i and j, assign values to them, do some math operations and
print out the returned output.
However, running this code returns an error:
invalid syntax
Figure 13.1: A syntax error detected at the second line around the assignment operator.
Read the issued error carefully. In the first line of the error (displayed in
blue), the interpreter lets you know that there is an error in the second
line of your code. This corresponds to the line if name = John. Moreover,
you notice an arrow marker (^) which is pointing towards the assignment
sign (=). This arrow means that you should review your code at that part.
The job of the interpreter ends here, and now it is your turn to look at the
part of the code as guided by the interpreter.
If you remember from previous chapters, the assignment operator (=)
is actually used to assign a value to a variableit is not an equal sign.
If you want to test whether something is equal to something else, you
should use the equal sign (==) which is a like a double assignment
operator. Keeping this in mind, we correct our code as follows:
name = 'John'
if name == 'John'
print('Your name is John')
i = 5
j = 15
k = ((i*j) + (j+i)
print(k)
190
Even though we corrected the error that was pointed out, we still get
another error when we run this code:
Figure 13.2: A syntax error is detected at the end of the second line.
Notice that we still have an error at the second line, but this time at
the end of it. The interpreter does its best and gives us the approximate
location of the error. Now, you need to take another cautious look at the
code, and you should be able to realize that a colon (:) meant to be at the
end of an if statement is missing. After you add the colon, the code should
look like this:
name = 'John'
if name == 'John':
print('Your name is John')
i = 5
j = 15
k = ((i*j) + (j+i)
print(k)
Running the code again, you will come across another syntax problem:
Figure 13.3: A syntax error is detected at the ninth line around the print function.
191
This time, the error occurred at the ninth line. Here is where you have
to be more cautious because this time the interpreter is giving a rough
estimationthe error is not exactly on the line where the arrow marker
is pointing. This time, you should look at the expression that comes before
the print command. This corresponds to this line:
k = ((i*j) + (j+i)
Notice that a bracket is missing at the end of the line. Go ahead and add
it:
name = 'John'
if name == 'John':
print('Your name is John')
i = 5
j = 15
k = ((i*j) + (j+i))
print(k)
Once you have added the missing bracket and
ran the code, you should get this result:
unexpected
indents
Figure 13.4: An indentation error is detected at the last line before the print command.
and finally you have managed to correct the whole block which looks as
follows.
name = 'John'
if name == 'John':
print('Your name is John')
i = 5
j = 15
k = ((i*j) + (j+i))
print(k)
Finally, we get an output free of errors:
At this point, you have made sure that the code doesnt have any syntax
errors.
Tip: An output that is generated without errors is an indication
that there are no syntax error in the code. However, there may be
a different kind of errors that cannot be detected by computers, but
instead need to be noticed by a human being.
193
Lab Activity
The following code is supposed to print all the elements of the string
John one by one:
lab soluTion
for i in "John":
print(i)
And here is the output:
Figure 13.6: String elements printed out after the code has been debugged.
194
second = 2
third = 3
more = input("What is the extra value? ")
print(total)
In this code, we are assigning some number values to the first three
variables. Then we create another user input variable that gets whatever
values the user inputs when the program runs. In the last line, we
calculate the sum of all the four values and print it out.
At first sight, the code looks correct. Even if you run it, everything will
look in place and you will get this initial output:
At this point the last two lines of the code have not been run yet because
the program is waiting for the user to input a value. We are still at run
time. If we input a number value after the question, we are going to get
an error:
195
NameError
second = 2
third = 3
more = input("What is the extra value? ")
print(total)
You will again be prompted to input the extra value. After you do so, you
will get another run time error:
Figure 13.9: Error occurring at run time highlighting an unsupported operand type.
TypeError
second = 2
third = 3
more = int(input("What is the extra value?
"))
print(total)
Notice that we added the int() function before input(). This will convert
any number input to an integer. If you run the code this time, you will get
a result that is free of errors:
Figure 13.10: Generated output after all run time errors have been debugged.
As you see, this time you got what you were looking for. After you input 4,
the program returned the total sum of (1+2+3+4) which is 10.
At this point, assisted by the interpreter, you have debugged all the run
time errors that occurred as you were running your code.
197
Lab Activity
The following code is supposed to ask the user for their first and last
names. Then it will store that data into a dictionary and print out the
dictionary content. However, the code contains run time errors that
prevent it from running successfully. Try to debug it.
names = {}
last = input("Enter your last name: ")
print (names)
198
lab soluTion
names = {}
last = input("Enter your last name: ")
print (names)
And this is the output:
Figure 13.11: Data stored successfully inside the dictionary after the code has been
debugged.
199
#create_database.py
import sqlite3
db = sqlite3.connect('guestbook.db')
db.execute('create table users (id INTEGER
PRIMARY KEY autoincrement, username text,
password text, date_joined int)')
db.execute('create table posts (id INTEGER
PRIMARY KEY autoincrement, poster_id int, title
text, body text, time_posted int)')
db.commit()
db.close()
import users
def display_menu():
print('1: Login')
print('2: Register')
if users.is_logged_in == True:
print('3: Post Comment')
print('9: Exit')
200
201
encrypted.update(password)
newpass = encrypted.hexdigest()
currenttime = int(time.time())
db.execute('insert into users
(username, password, date_joined) values
(?,?,?)',(username,newpass, currenttime))
db.commit()
print('You have been added to the user
database')
return True
else:
print('Unfortunately, that username is
already taken. Please try again')
register()
def login():
username = input('Please enter your
username: ')
if username_available(username) == False:
#if it is taken, then it must exist.
import hashlib
password = input('Please enter your
password: ').encode('utf_8')
encrypted = hashlib.sha256()
encrypted.update(password)
newpass = encrypted.hexdigest()
db.row_factory = sqlite3.Row
row = db.execute('select id from
users where username = ? and password = ?',
(username, newpass))
if row is None:
print('Sorry, that password doesn\'
match the username')
else:
user_id = row.fetchone()['id']
is_logged_in = True
else:
print('That user doesn\'t exist.
Register it?')
def logout():
202
pass
def username_available(username):
db.row_factory = sqlite3.Row
row = db.execute('select id from users
WHERE username = ?',(username,))
if row.fetchone() is None:
return True
else:
return False
Lab Solution
The debugged and corrected code for the three
scripts is as follows:
#create_database.py
import sqlite3
db = sqlite3.connect('guestbook.db')
db.execute('create table if not exists users
(id INTEGER PRIMARY KEY autoincrement, username
text, password text, date_joined int)')
db.execute('create table if not exists posts
(id INTEGER PRIMARY KEY autoincrement, poster_
id int, title text, body text, time_posted
int)')
db.commit()
db.close()
#guestbook.py
import users
def display_menu():
print('1: Login')
print('2: Register')
if users.is_logged_in == True:
print('3: Post Comment')
print('9: Exit')
choice = input('Enter the number of where
Final Lab Exercises
203
newpass = encrypted.hexdigest()
currenttime = int(time.time())
db.execute('insert into users
(username, password, date_joined) values
(?,?,?)',(username,newpass, currenttime))
db.commit()
print('You have been added to the user
database')
return True
else:
print('Unfortunately, that username is
already taken. Please try again')
register()
def login():
username = input('Please enter your
username: ')
if username_available(username) == False:
#if it is taken, then it must exist.
import hashlib
password = input('Please enter your
password: ').encode('utf_8')
encrypted = hashlib.sha256()
encrypted.update(password)
newpass = encrypted.hexdigest()
db.row_factory = sqlite3.Row
row = db.execute('select id from
users where username = ? and password = ?',
(username, newpass))
if row is None:
print('Sorry, that password doesn\'
match the username')
else:
user_id = row.fetchone()['id']
is_logged_in = True
else:
print('That user doesn\'t exist.
Register it?')
def logout():
pass
Final Lab Exercises
205
def username_available(username):
db.row_factory = sqlite3.Row
row = db.execute('select id from users
WHERE username = ?',(username,))
if row.fetchone() is None:
return True
else:
return False
After you run the correct code, by executing create_database.py first,
and then guestbook.py, you will get this output:
Figure 13.12: Output after running the corrected code of create_database.py and
guestbook.py.
ChapTer summary
In this chapter you learned how to detect syntax errors, how to
find their exact or approximate location in the lines of code of the
script, and how to correct the errors using the interpreter hints as
a guide.
You were introduced to run time errors, when and where they
occur and how to free your code of them.
This brings you to the end of our Python for Beginners book. If
before reading this book, you had never programmed before in
206
your life, you should now feel confident enough to do so. With some
effort, you can start building your own programs that go beyond
the examples and the exercises we have gone through this book in
terms of size and complexity.
If before reading this book, you were an already experienced
programmer who wanted to expand your programming skills
with Python, you should now understand the advantages of this
language as compared to other languages. Compared to other
languages, Python code is much more readable, mainly boosted
by its indentation feature. This readability is complemented by
Pythons brevity. Python requires fewer lines of code to solve a
programming problem than other languages.
There are many ways you can use Python. Python can be used
in web development along with frameworks like Django and
TurboGears, to name a few.
Python can be used as a tool to access databases such as MySQL,
Oracle, and PostgreSQL.
Even though in this chapter we learned only scripting, it is worth
mentioning that you can build your own graphical user interface
program using Python libraries such as the built-in Tkinter. With
a bit of learning you can easily associate your scripts with buttons,
text boxes and other tools of desktop graphical programs.
Its powerful scripting capabilities make Python a widely used
language for scientific calculations in areas such as physics and
bioinformatics. Python also provides support for low-level network
programming via Twisted Python, a network programming
framework designed to work with Python.
Python is also often used as a support language for software
developers, for build control and management, testing, and in
many other ways. Gaming is not left behind. Through PyGame or
PyKyra frameworks, you can create many types of commercial and
hobby games.
No matter what the area of your interest is, you should now be able
to kick-start your own real program using the skills you learned in
this book.
Chapter 13 Summary
207
209
210
Answer Key
211
Chapter 3: Conditionals
1. Which of the following is a correctly written expression?
Answer: b. if a == b:
Print(Yes)
2. What is not true about elif?
Answer: b. Elif is a substitute of the switch function.
3. What happens when none of the conditions are true in a conditional
block?
Answer: a. The action under else is executed.
4. How would you write a code that prints Greater if a is greater than
b, and Less or equal if a is less than or equal to b, using the inline if
statement?
Answer: c. a, b = 10,20
print (Less or equal if a <= b else Greater)
Chapter 4: Looping
1. What would the following code do when executed?
Answer: c. Print out even numbers that fall between zero and 100.
2. What does the range functionality do?
Answer: a. Generates a list.
3. The for loop is commonly used to:
Answer: c. Iterate through lists, tuples and strings.
4. What is true about try and except?
Answer: b. The expression under except is executed when the
expression under try experiences an error.
5. What happens when the condition above the break code line is not
met?
Answer: b. The line under break is not executed.
Chapter 5: Lists
1. What is true about negative indexing?
Answer: a. It provides an easy method to enumerate list elements
starting from the end.
212
Answer Key
213
214
Answer Key
216
Answer Key
217
218
Answer Key
219
Appendix
Appendix
Terminology
Description
API
Append()
Argument
AttributeError
Bitwise
operator
Break
Boolean
Buffer
Casting
Class
class
Class variable
220
Terminology
Description
Collection
Command
prompt
Comment
Conditional
connect()
Constructor
container
continue
Cursor
Data member
Database
datetime
Debug
def
221
Appendix
Terminology
Description
Dictionary
Dictionary key
Dictionary
value
Django
Encapsulation
Eclipse
Elif
Else
Enumerate
except
execute()
Exception
finally
Float
For loop
Function
getattr()
Terminology
Description
hashable
If
import
Indentation
Inheritance
Initiation
Inline if
input()
int()
Instance
Instance
variable
Integer
Interpreter
223
Appendix
Terminology
Description
IOError
iterable
Iteration
Indentation
error
Java Runtime
Environment
join()
Keyword
kwargs
len
Library
Linux
List
Local variable
Loop
224
Terminology
Description
Mapping
Method
Module
MySQL
NameError
Negative
indexing
now()
Object
open()
Operand
Oracle
Database
Parameter
path
Positive
indexing
225
Appendix
Terminology
Description
PostgreSQL
PyDev
PyGame
PyKyra
Python
range
record
return
row
row_factory
Run
Runtime
self
226
Terminology
Description
sequence
slice notation
split()
SQL
sqlite3
Statement
Step (iteration)
str()
String
String
formatting
Superclass
227
Appendix
Terminology
Description
Syntax
Syntax error
sys
Terminal
Tkinter
Truth table
try
Tuple
(databases)
Tuple (Python)
Turbo Gears
Twisted
Python
TypeError
Variable
Variable scope
While loop
__init__
228
229
Youve Read the Book Now Take the Online Course From the Author
50%
DISCOUNT
To all of our readers, were offering our LearnToProgram
courses at 50% off. These are courses that include hours
of video instruction, various code samples and applicable
lab exercises. Youll watch as the author develops the code right in front
of you while you gain skills you can immediately apply to your projects.
All courses are available at: https://academy.learntoprogram.tv/directory/.
To apply your Readers Discount, go to any course of your choosing, click
to enroll and then select Redeem Coupon.
Direct Link:
https://academy.learntoprogram.tv/ ...
AJAX Development
course/ajax-tutorial-training/
course/android-programmingdevelopment-for-beginners/
course/learn-c-programming/
course/learn-css-development/
course/photoshop-cs6-training-for-coders/
course/html5-mobile-app-developmentphonegap/
course/ios-iphone-ipad-development-forbeginners/
course/javascript-for-beginners/
course/learn-jquery-for-beginners/
course/objective-c-for-beginners/
course/photoshop-cs6-training-for-coders/
course/learn-php-mysql-for-beginners/
course/python-for-beginners/
course/sql-database-for-beginners/
course/user-experience-designfundamentals/