Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (3 votes)
26 views

Buy ebook (Ebook) Python: The Complete Manual - The essential handbook for Python users - Master Python today! First Edition by Unknown ISBN 9781785462689, 1785462687 cheap price

The document promotes various Python-related ebooks available for download at ebooknice.com, including 'Python: The Complete Manual' and other titles focused on Python programming. It highlights Python's versatility and beginner-friendly nature, providing insights into programming projects and applications. The content also includes a brief introduction to Python programming concepts, such as variables, data types, and creating simple programs.

Uploaded by

homodevinc11
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
26 views

Buy ebook (Ebook) Python: The Complete Manual - The essential handbook for Python users - Master Python today! First Edition by Unknown ISBN 9781785462689, 1785462687 cheap price

The document promotes various Python-related ebooks available for download at ebooknice.com, including 'Python: The Complete Manual' and other titles focused on Python programming. It highlights Python's versatility and beginner-friendly nature, providing insights into programming projects and applications. The content also includes a brief introduction to Python programming concepts, such as variables, data types, and creating simple programs.

Uploaded by

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

Visit https://ebooknice.

com to download the full version and


explore more ebooks

(Ebook) Python: The Complete Manual - The essential


handbook for Python users - Master Python today!
First Edition by Unknown ISBN 9781785462689,
1785462687
_____ Click the link below to download _____
https://ebooknice.com/product/python-the-complete-
manual-the-essential-handbook-for-python-users-master-
python-today-first-edition-43159702

Explore and download more ebooks at ebooknice.com


Here are some recommended products that might interest you.
You can download now and explore!

(Ebook) Python The Complete Manual: The Essential Handbook for Python
Users by Mehedi Hzn Press Publications

https://ebooknice.com/product/python-the-complete-manual-the-
essential-handbook-for-python-users-34099554

ebooknice.com

(Ebook) The Complete C++ & Python Manual by The Complete Manual Series

https://ebooknice.com/product/the-complete-c-python-manual-43690082

ebooknice.com

(Ebook) The Complete Python Coding Manual - 18th Edition, 2023 by


,,,,,

https://ebooknice.com/product/the-complete-python-coding-manual-18th-
edition-2023-50584730

ebooknice.com

(Ebook) The Complete Python & C++ Manual - 9th Edition 2022 by ,,,,

https://ebooknice.com/product/the-complete-python-c-manual-9th-
edition-2022-42004584

ebooknice.com
(Ebook) Python Developer's Handbook by Unknown

https://ebooknice.com/product/python-developer-s-handbook-56966628

ebooknice.com

(Ebook) Python The Complete Manual by coll. ISBN 9781785464409,


178546440X

https://ebooknice.com/product/python-the-complete-manual-5701248

ebooknice.com

(Ebook) C++ & Python for Beginners – 11th Edition 2022 by Unknown

https://ebooknice.com/product/c-python-for-beginners-11th-
edition-2022-44890860

ebooknice.com

(Ebook) Maya Python for Games and Film: A Complete Reference for Maya
Python and the Maya Python API by Adam Mechtley; Ryan Trowbridge ISBN
9780123785787, 0123785782

https://ebooknice.com/product/maya-python-for-games-and-film-a-
complete-reference-for-maya-python-and-the-maya-python-api-42933770

ebooknice.com

(Ebook) Python Playground Geeky Projects for the Curious Programmer by


unknown

https://ebooknice.com/product/python-playground-geeky-projects-for-
the-curious-programmer-55377902

ebooknice.com
The Complete Manual
The essential handbook for Python users
Master
Python
today!
Welcome to
Python The Complete Manual
Python is a versatile language and its rise in popularity is
certainly no surprise. Its similarity to everyday language has
made it a perfect companion for the Raspberry Pi, which
is often a irst step into practical programming. But don’t
be fooled by its beginner-friendly credentials – Python has
plenty of more advanced functions. In this bookazine, you
will learn how to program in Python, discover amazing
projects to improve your understanding, and ind ways
to use Python to enhance your experience of computing.
You’ll also create fun projects including programming
a quadcopter drone and sending text messages from
Raspberry Pi. Let’s get coding!
Python The Complete Manual
Imagine Publishing Ltd
Richmond House
33 Richmond Hill
Bournemouth
Dorset BH2 6EZ
 +44 (0) 1202 586200
Website: www.imagine-publishing.co.uk
Twitter: @Books_Imagine
Facebook: www.facebook.com/ImagineBookazines

Publishing Director
Aaron Asadi

Head of Design
Ross Andrews

Production Editor
Alex Hoskins

Senior Art Editor


Greg Whitaker

Designer
Perry Wardell-Wicks

Photographer
James Sheppard

Printed by
William Gibbons, 26 Planetary Road, Willenhall, West Midlands, WV13 3XT

Distributed in the UK, Eire & the Rest of the World by


Marketforce, 5 Churchill Place, Canary Wharf, London, E14 5HU
Tel 0203 787 9060 www.marketforce.co.uk

Distributed in Australia by
Network Services (a division of Bauer Media Group), Level 21 Civic Tower, 66-68 Goulburn Street,
Sydney, New South Wales 2000, Australia, Tel +61 2 8667 5288

Disclaimer
The publisher cannot accept responsibility for any unsolicited material lost or damaged in the
post. All text and layout is the copyright of Imagine Publishing Ltd. Nothing in this bookazine may
be reproduced in whole or part without the written permission of the publisher. All copyrights are
recognised and used specifically for the purpose of criticism and review. Although the bookazine has
endeavoured to ensure all information is correct at time of print, prices and availability may change.
This bookazine is fully independent and not affiliated in any way with the companies mentioned herein.

Python is a trademark of Python Inc., registered in the U.S. and other countries.
Python © 2016 Python Inc

Python The Complete Manual First Edition © 2016 Imagine Publishing Ltd

ISBN 978 1785 462 689

Part of the

bookazine series
Contents
What you can ind inside the bookazine

Code
& create
with
Python!

6
Get started
with
Python 8 Masterclass
Discover the basics of Python

Introducing Python Create with Python Use Python with Pi

26 Make web apps 80 Tic-tac-toe with Kivy 104 Using Python on Pi


Master this starter project Program a simple game Optimise your code
86 Make a Pong clone 110 Send an SMS
Enhance your game skills Combine Twilio and
Raspberry Pi
114 Voice synthesizer
Use the eSpeak library
32 Build an app for Android
116 Program a quadcopter
Take your apps on the move
Make a drone with Pi
40 50 Python tips 88 Program a Space
Invaders clone 122 Code a Twitter bot
A selection of handy tips
Have fun with Pivaders Retweet automatically
Work with Python 98 Make a visual novel 124 Control an LED
Tell a story using Python Use GPIO for lights
50 Replace your shell
Say goodbye to Bash
58 Scientific computing
Discover NumPy’s power
64 Python for system admins
How to tweak your settings
72 Scrape Wikipedia
Start using Beautiful Soup

7
Always wanted to have a go at programming? No more
excuses, because Python is the perfect way to get started!
Python is a great programming language for both beginners and experts. It
is designed with code readability in mind, making it an excellent choice for
beginners who are still getting used to various programming concepts.
The language is popular and has plenty of libraries available, allowing
programmers to get a lot done with relatively little code.
You can make all kinds of applications in Python: you could use the
Pygame framework to write simple 2D games, you could use the GTK
libraries to create a windowed application, or you could try something
a little more ambitious like an app such as creating one using Python’s
Bluetooth and Input libraries to capture the input from a USB keyboard and
relay the input events to an Android phone.
For this tutorial we’re going to be using Python 2.x since that is the
version that is most likely to be installed on your Linux distribution.
In the following tutorials, you’ll learn how to create popular games using
Python programming. We’ll also show you how to add sound and AI to
these games.

8
Get started with Python Getting started

9
Hello World
Let’s get stuck in, and what better way than with the programmer’s
best friend, the ‘Hello World’ application! Start by opening a terminal.
Its current working directory will be your home directory. It’s probably
a good idea to make a directory for the iles that we’ll be creating in
this tutorial, rather than having them loose in your home directory.
You can create a directory called Python using the command mkdir
Python. You’ll then want to change into that directory using the
command cd Python.
The next step is to create an empty ile using the command ‘touch’
followed by the ilename. Our expert used the command touch
hello_world.py. The inal and most important part of setting up the
ile is making it executable. This allows us to run code inside the hello_
world.py ile. We do this with the command chmod +x hello_world.
py. Now that we have our ile set up, we can go ahead and open it up
in nano, or alternatively any text editor of your choice. Gedit is a great
editor with syntax highlighting support that should be available on any
distribution. You’ll be able to install it using your package manager if
you don’t have it already.

[liam@liam-laptop ~]$ mkdir Python


[liam@liam-laptop ~]$ cd Python/
[liam@liam-laptop Python]$ touch hello_world.py
[liam@liam-laptop Python]$ chmod +x hello_world.py
[liam@liam-laptop Python]$ nano hello_world.py

Our Hello World program is very simple, it only needs two lines.
The irst line begins with a ‘shebang’ (the symbol #! – also known

10
Get started with Python Getting started

as a hashbang) followed by the path to the Python interpreter. The


program loader uses this line to work out what the rest of the lines Tip
need to be interpreted with. If you’re running this in an IDE like IDLE, If you were using a graphical
you don’t necessarily need to do this. editor such as gedit, then you
would only have to do the
The code that is actually read by the Python interpreter is only a last step of making the ile
single line. We’re passing the value Hello World to the print function by executable. You should only have
to mark the ile as executable
placing it in brackets immediately after we’ve called the print function. once. You can freely edit the ile
Hello World is enclosed in quotation marks to indicate that it is a literal once it is executable.
value and should not be interpreted as source code. As we would
expect, the print function in Python prints any value that gets passed
to it from the console.
You can save the changes you’ve just made to the ile in nano using
the key combination Ctrl+O, followed by Enter. Use Ctrl+X to exit nano.

#!/usr/bin/env python2
print(“Hello World”)

You can run the Hello World program by preixing


its ilename with ./ – in this case you’d type:
./hello_world.py.

[liam@liam-laptop Python]$ ./hello_world.py


Hello World

Variables and data types


A variable is a name in source code that is associated with an area in
memory that you can use to store data, which is then called upon
throughout the code. The data can be one of many types, including:

Integer Stores whole numbers


Float Stores decimal numbers
Boolean Can have a value of True or False
String Stores a collection of characters. “Hello World” is a
string

“A variable is associated with an area in


memory that you can use to store data”
11
Getting started Get started with Python

As well as these main data types, there are sequence types (technically,
Tip a string is a sequence type but is so commonly used we’ve classed it
At this point, it’s worth explaining as a main data type):
that any text in a Python ile
that follows a # character will be
ignored by the interpreter. This List Contains a collection of data in a speciic order
is so you can write comments in
your code. Tuple Contains a collection immutable data in a speciic
order

A tuple would be used for something like a co-ordinate, containing


an x and y value stored as a single variable, whereas a list is typically
used to store larger collections. The data stored in a tuple is immutable
because you aren’t able to change values of individual elements in a
tuple. However, you can do so in a list.
It will also be useful to know about Python’s dictionary type. A
dictionary is a mapped data type. It stores data in key-value pairs.
This means that you access values stored in the dictionary using that
value’s corresponding key, which is diferent to how you would do it
with a list. In a list, you would access an element of the list using that
element’s index (a number representing where the element is placed
in the list).
Let’s work on a program we can use to demonstrate how to use
variables and diferent data types. It’s worth noting at this point that
you don’t always have to specify data types in Python. Feel free to
create this ile in any editor you like. Everything will work just ine as
long as you remember to make the ile executable. We’re going to call
ours variables.py.

Interpreted vs compiled languages

An interpreted language compiled language such as


such as Python is one C, where the source code is
where the source code only converted to machine
is converted to machine code once – the resulting
code and then executed machine code is then
each time the program executed each time the
runs. This is diferent from a program runs.

12
Get started with Python Getting started

Full code listing


#!/usr/bin/env python2

# We create a variable by writing the name of the


The following line creates variable we want followed# by an equals sign,
an integer variable called which is followed by the value we want to store
hello_int with the # in the# variable. For example, the following line
value of 21. Notice how creates a variable called# hello_str, containing the
it doesn’t need to go in string Hello World.
quotation marks hello_str = “Hello World”

The same principal is hello_int = 21


true of Boolean values
hello_bool = True
We create a tuple in
the following way hello_tuple = (21, 32)

hello_list = [“Hello,”, “this”, “is”,


And a list in this way “a”, “list”]

# This list now contains 5 strings. Notice that


there are no spaces# between these strings so if
you were to join them up so make a sentence #
you’d have to add a space between each element.

You could
hello_list = list()
also create the
hello_list.append(“Hello,”)
same list in the
hello_list.append(“this”)
following way
hello_list.append(“is”)
hello_list.append(“a”)
hello_list.append(“list”)

# The irst line creates an empty list and the


following lines use the append# function
of the list type to add elements to the
list. This way of using a# list isn’t
really very useful when working
with strings you know of in
# advance, but it can be
useful when working with
dynamic data such as
user# input. This list
will overwrite the
irst list without
any warning

13
Getting started Get started with Python

We might as well as we# are using the same variable name as the
create a dictionary previous list.
while we’re at it.
Notice how we’ve hello_dict = { “first_name” : “Liam”,
aligned the colons “last_name” :
below to make the “Fraser”,
code tidy “eye_colour” : “Blue” }

# Let’s access some elements inside our


collections# We’ll start by changing the value
of the last string in our hello_list and# add an
exclamation mark to the end. The “list” string is
the 5th element # in the list. However, indexes
in Python are zero-based, which means the
# irst element has an index of 0.
Notice that there
print(hello_list[4])
will now be two
hello_list[4] += “!”
exclamation marks
# The above line is the same as
present when we
hello_list[4] = hello_list[4] + “!”
print the element
print(hello_list[4])

Remember
that tuples are print(str(hello_tuple[0]))
immutable, # We can’t change the value of those elements
although we like we just did with the list
can access the # Notice the use of the str function above to
elements of them explicitly convert the integer
like so # value inside the tuple to a string before
printing it.
Let’s create a
sentence using
the data in our print(hello_dict[“irst_name”] + “ “ + hello_
hello_dict dict[“last_name”] + “ has “ +
hello_dict[“eye_colour”] + “ eyes.”)
A much tidier way
of doing this would
be to use Python’s print(“{0} {1} has {2} eyes.”.format(hello_
string formatter dict[“irst_name”],
hello_dict[“last_name”],
hello_dict[“eye_colour”]))

14
Get started with Python Getting started

Indentation in detail

As previously mentioned, essential to use a consistent


the level of indentation indentation style. Four
dictates which statement a spaces are typically used to
block of code belongs to. represent a single level of
Indentation is mandatory indentation in Python. You
in Python, whereas in other can use tabs, but tabs are
languages, sets of braces not well deined, especially if
are used to organise code you open a ile in more than
blocks. For this reason, it is one editor.

Control structures
In programming, a control structure is any kind of statement that can
change the path that the code execution takes. For example, a control
structure that decided to end the program if a number was less than 5
would look something like this:

#!/usr/bin/env python2
import sys # Used for the sys.exit function
int_condition = 5
if int_condition < 6:
sys.exit(“int_condition must be >= 6”)
else:
print(“int_condition was >= 6 - continuing”)

The path that the code takes will depend on the value of
the integer int_condition. The code in the ‘if’ block will only be
executed if the condition is true. The import statement is used to
load the Python system library; the latter provides the exit function,
allowing you to exit the program, printing an error message. Notice
that indentation (in this case four spaces per indent) is used to indicate
which statement a block of code belongs to. ‘If’ statements are
probably the most commonly used control structures. Other control

“The path the code takes will depend on


the value of the integer int_condition”
15
Getting started (FUTUBSUFEXJUI1ZUIPO

structures include: the following items which you should be aware of


when using Python:
t'PSTUBUFNFOUT XIJDIBMMPXZPVUPJUFSBUFPWFSJUFNTJO
DPMMFDUJPOT PSUPSFQFBUBQJFDFPGDPEFBHBJOBDFSUBJOOVNCFS
PGUJNFT
t8IJMFTUBUFNFOUT BMPPQUIBUDPOUJOVFTXIJMFUIFDPOEJUJPO
JTUSVF
We’re going to write a program that accepts user input from the
user to demonstrate how control structures work. We’re calling it
construct.py. The ‘for’ loop is using a local copy of the current value,
which means any changes inside the loop won’t make any changes
afecting the list. On the other hand however, the ‘while’ loop is
directly accessing elements in the list, so you could change the list
there should you want to do so. We will talk about variable scope in
some more detail later on in the article. The output from the above
program is as follows:

[liam@liam-laptop Python]$ ./
construct.py
How many integers? acd
You must enter an integer

[liam@liam-laptop Python]$ ./
construct.py
How many integers? 3
Please enter integer 1: t
You must enter an integer
Please enter integer 1: 5
Please enter integer 2: 2
Please enter integer 3: 6
Using a for loop
5
2
6
Using a while loop
5
2
6

“The ‘for‘ loop uses a local copy, so


changes in the loop won’t afect the list”
16
Get started with Python Getting started

Full code listing

#!/usr/bin/env python2

# We’re going to write a program that will ask the


user to input an arbitrary
# number of integers, store them in a collection,
and then demonstrate how the
The number of
# collection would be used with various control
integers we want
in the list structures.

import sys # Used for the sys.exit


function

target_int = raw_input(“How many


integers? “)

# By now, the variable target_int contains a string


representation of
# whatever the user typed. We need to try and
convert that to an integer but
# be ready to # deal with the error if it’s not.
Otherwise the program will
# crash.
try:
A list to store the target_int = int(target_int)
integers except ValueError:
sys.exit(“You must enter an
integer”)

ints = list()
These are used
to keep track
count = 0
of how many
integers we
currently have

17
Getting started Get started with Python

# Keep asking for an integer until we have the


required number
while count < target_int:
new_int = raw_input(“Please enter
If the above integer {0}: “.format(count + 1))
succeeds then isint = False
isint will be set try:
to true: isint new_int = int(new_int)
=True
except:
print(“You must enter an
integer”)

# Only carry on if we have an integer. If not,


we’ll loop again
# Notice below I use ==, which is diferent from
=. The single equals is an
# assignment operator whereas the double
equals is a comparison operator.

if isint == True:
# Add the integer to the collection
ints.append(new_int)
# Increment the count by 1
By now, the
user has given count += 1
up or we have
a list filled with
integers. We can
print(“Using a for loop”)
loop through
for value in ints:
these in a couple
print(str(value))
of ways. The first
is with a for loop
# Or with a while loop:
print(“Using a while loop”)
# We already have the total above, but knowing

18
Get started with Python Getting started

the len function is very


# useful.
total = len(ints)
count = 0
while count < total:
print(str(ints[count]))
count += 1

More about a Python list

A Python list is similar to an we recommend that you


array in other languages. A only store data of the same
list (or tuple) in Python can type in a list. This should
contain data of multiple almost always be the case
types, which is not usually anyway due to the nature of
the case with arrays in other the way data in a list would
languages. For this reason, be processed.

Functions and variable scope


Functions are used in programming to break processes down
into smaller chunks. This often makes code much easier to read.
Functions can also be reusable if designed in a certain way. Functions
can have variables passed to them. Variables in Python are always
passed by value, which means that a copy of the variable is passed
to the function that is only valid in the scope of the function. Any
changes made to the original variable inside the function will be
discarded. However, functions can also return values, so this isn’t an
issue. Functions are deined with the keyword def, followed by the
name of the function. Any variables that can be passed through are
put in brackets following the function’s name. Multiple variables are
separated by commas. The names given to the variables in these
brackets are the ones that they will have in the scope of the function,
regardless of what the variable that’s passed to the function is called.
Let’s see this in action. The output from the program opposite is
as follows:

“Functions are deined with the keyword


def, then the name of the function”
19
Getting started Get started with Python

#!/usr/bin/env python2 # Below is a function


called modify_string, which accepts a variable
# that will be called original in the scope of the
function. Anything # indented with 4 spaces
under the function deinition is in the
# scope.
def modify_string(original):
original += “ that has been
modified.”
# At the moment, only the local copy of this
string has been modiied

def modify_string_return(original):
original += “ that has been
modified.”
# However, we can return our local copy to the
We are now outside caller. The function# ends as soon as the return
of the scope of statement is used, regardless of where it # is in
the modify_string the function.
function, as we have
return original
reduced the level of
indentation
test_string = “This is a test string”
The test string
won’t be changed modify_string(test_string)
in this code print(test_string)

test_string = modify_string_
return(test_string)
print(test_string)

# The function’s return value is stored in the


However, we
variable test string, # overwriting the original and
can call the
therefore changing the value that is # printed.
function like this

[liam@liam-laptop Python]$ ./functions_and_


scope.py
This is a test string
This is a test string that has been modiied.

Scope is an important thing to get the hang of, otherwise it can


get you into some bad habits. Let’s write a quick program to
demonstrate this. It’s going to have a Boolean variable called cont,
which will decide if a number will be assigned to a variable in an if
statement. However, the variable hasn’t been deined anywhere
apart from in the scope of the if statement. We’ll inish of by trying
to print the variable.
20
Get started with Python Getting started

#!/usr/bin/env python2
cont = False
if cont:
var = 1234
print(var)

In the section of code above, Python will convert the integer to a string
before printing it. However, it’s always a good idea to explicitly convert
things to strings – especially when it comes to concatenating strings
together. If you try to use the + operator on a string and an integer,
there will be an error because it’s not explicitly clear what needs to
happen. The + operator would usually add two integers together.
Having said that, Python’s string formatter that we demonstrated
earlier is a cleaner way of doing that. Can you see the problem? Var has
only been deined in the scope of the if statement. This means that we
get a very nasty error when we try to access var.

[liam@liam-laptop Python]$ ./scope.py


Traceback (most recent call last):
File “./scope.py”, line 8, in <module>
print var
NameError: name ‘var’ is not deined

If cont is set to True, then the variable will be created and we can
access it just ine. However, this is a bad way to do things. The correct
way is to initialise the variable outside of the scope of the if statement.

#!/usr/bin/env python2

cont = False

var = 0
if cont:
var = 1234

if var != 0:
print(var)

21
Getting started Get started with Python

The variable var is deined in a wider scope than the if statement,


Tip and can still be accessed by the if statement. Any changes made to
You can deine defaults for var inside the if statement are changing the variable deined in the
variables if you want to be able to larger scope. This example doesn’t really do anything useful apart
call the function without passing
any variables through at all. You from illustrate the potential problem, but the worst-case scenario has
do this by putting an equals gone from the program crashing to printing a zero. Even that doesn’t
sign after the variable name. For
example, you can do: happen because we’ve added an extra construct to test the value of
def modify_string (original=” var before printing it.
Default String”)

“Google, or any other search engine,


is very helpful. If you are stuck with
anything, or have an error message you
can’t work out how to ix”

Comparison operators
The common comparison operators available in Python include:
< strictly less than
<= less than or equal
> strictly greater than
>= greater than or equal
== equal
!= not equal

22
Get started with Python Getting started

Coding style
It’s worth taking a little time to talk about coding style. It’s simple to
write tidy code. The key is consistency. For example, you should always
name your variables in the same manner. It doesn’t matter if you want
to use camelCase or use underscores as we have. One crucial thing is
to use self-documenting identiiers for variables. You shouldn’t have
to guess what a variable does. The other thing that goes with this is to
always comment your code. This will help anyone else who reads your
code, and yourself in the future. It’s also useful to put a brief summary
at the top of a code ile describing what the application does, or a part
of the application if it’s made up of multiple iles.

Summary
This article should have introduced you to the basics of programming
in Python. Hopefully you are getting used to the syntax, indentation
and general look and feel of a Python program. The next step is
to learn how to come up with a problem that you want to solve,
and break it down into small steps that you can implement in a
programming language. Google, or any other search engine, is very
helpful. If you are stuck with anything, or have an error message you
can’t work out how to ix, stick it into Google and you should be a lot
closer to solving your problem. For example, if we Google ‘play mp3
ile with python’, the irst link takes us to a Stack Overlow thread with
a bunch of useful replies. Don’t be afraid to get stuck in – the real fun
of programming is solving problems one manageable chunk at a time.

23
Introducing Python Python essentials

Introducing
Python
Now that you’ve taken the irst steps with Python, it’s time
to begin using that knowledge to get coding. In this section,
you’ll ind out how to begin coding apps for Android operating
systems (p.32) and the worldwide web (p.26). These easy-to-
follow tutorials will help you to cement the Python language
that you’ve learned, while developing a skill that is very helpful
in the current technology market. We’ll inish up by giving you
50 essential Python tips (p.40) to increase your knowledge and
ability in no time.

24
Python essentials Introducing Python

25
Introducing Python Make web apps with Python

What you’ll need…

Python 2.7:
https://www.python.org/download/
Make web
apps with
releases/2.7/

Django version 1.4:


https://www.djangoproject.com/

Python
Python provides quick and easy way to build
applications, including web apps. Find out how to
use it to build a feature-complete web app
Python is known for its simplicity and capabilities. At this point it is
so advanced that there is nothing you cannot do with Python, and
conquering the web is one of the possibilities. When you are using
Python for web development you get access to a huge catalogue
of modules and community support – make the most of them.
Web development in Python can be done in many diferent
ways, right from using the plain old CGI modules to utilising fully
groomed web frameworks. Using the latter is the most popular
method of building web applications with Python, since it allows
you to build applications without worrying about all that low-level
implementation stuf. There are many web frameworks available for
Python, such as Django, TurboGears and Web2Py. For this tutorial
we will be using our current preferred option, Django.

The Django Project portable and can be integrated with


other Django sites with very little effort.
magazine issue tracker $ django-admin.py startproject
ludIssueTracker

01 The django-admin.py file is used


to create new Django projects.
Let’s create one for our issue tracker
A project directory will be created.
This will also act as the root of your
development web server that comes
project here… with Django. Under the project
In Django, a project represents the directory you will find the following
site and its settings. An application, on items…
the other hand, represents a specific manage.py: Python script to work with
feature of the site, like blogging or your project.
tagging. The benefit of this approach is ludIssueTracker: A python package
that your Django application becomes (a directory with __init__.py file) for

26
Make web apps with Python Introducing Python

your project. This package is the one dirname(__file__)), *x) ludissues


containing your project’s settings and Now update the path options:
configuration data. @code We will need to enable this app in the
ludIssueTracker/settings.py: This file TEMPLATE_DIRS = ( config file as well:
contains all the configuration options getabspath(‘templates’) INSTALLED_APPS = (
for the project. ) .............
ludIssueTracker/urls.py: This file MEDIA_ROOT = ‘django.contrib.admin’,
contains various URL mappings. getabspath(‘media’) ‘ludissues’,
wsgi.py: An entry-point for WSGI- MEDIA_URL = ‘/media/’ )
compatible web servers to serve your
project. Only useful when you are Now we will need to enable the
deploying your project. For this tutorial admin interface for our Django Creating the data model
we won’t be needing it. site. This is a neat feature of Django

Configuring the
which allows automatic creation of
an admin interface of the site based
on the data model. The admin
04 This is the part where we
define the data model
for our app. Please see the inline
Django project
interface can be used to add and comments to understand what is
manage content for a Django site. happening here.

02 Before we start working


on the application, let’s
configure the Django project
Uncomment the following line:

INSTALLED_APPS = (
From django.db import models:
# We are importing the
user authentication module so
as per our requirements. that we use the built
Edit ludIssueTracker/settings.py # in authentication model
as follows (only parts requiring ‘django.contrib.auth’, in this app
modification are shown): ‘django.contrib. from django.contrib.auth.
Database Settings: We will be contenttypes’, models import User
using SQLite3 as our database ‘django.contrib.sessions’, # We would also create an
system here. ‘django.contrib.sites’, admin interface for our app
NOTE: Red text indicates new ‘django.contrib.messages’, from django.contrib import
code or ‘django.contrib. admin
updated code. staticfiles’,
‘default’: { ‘django.contrib.admin’, # A Tuple to hold the
‘ENGINE’: # ‘django.contrib. multi choice char fields.
‘django.db.backends. admindocs’, # First represents the
sqlite3’, ) field name the second one
‘NAME’: ‘ludsite. repersents the display name
db3, Creating ludissues app ISSUE_STATUS_CHOICES = (
(‘new’, ‘New’),
(‘accepted’,’Accepted’),
Path settings
Django requires an absolute 03 In this step we will create the
primary app for our site, called
ludissues. To do that, we will use the
(‘reviewed’,’Reviewed’),
(‘started’,’Started’),
path for directory settings. (‘closed’,’Closed’),
But we want to be able to manage.py script:
)
pass in the relative directory $ python manage.py startapp
references. In order to do that
we will add a helper Python
function. Insert the following
code at the top of the settings.
py file: “When you are using Python for web
import os
def getabspath(*x):
development you get access to a huge
return os.path.join(os. catalogue of modules and support”
path.abspath(os.path.

27
Introducing Python Make web apps with Python

class Issue(models.Model): register(Issue,IssueAdmin) that you created while you were


# owner will be a To have the created data model syncing the database.
foreign key to the User reflected in the database, run the
model which is already built- following command:
in Django $ python manage.py syncdb
owner = models.ForeignKe You’ll be also asked to create a
y(User,null=True,blank=True) superuser for it:
# multichoice with You just installed Django’s auth
defaulting to “new” system, which means you don’t
status = models. have any superusers defined.
CharField(max_ Would you like to create one
length=25,choices=ISSUE_ now? (yes/no): yes After logging in, you will notice that
STATUS_CHOICES,default=’new’) all the apps installed in your project are
summary = models. available here. We are only interested in
TextField() Enabling the admin site the Auth and LudIssues app.
# date time field which You can click the +Add to add a
will be set to the date time record. Click the Add button next to
when the record is created
opened_on = models.
05 The admin site is already
enabled, but we need to enable
it in the urls.py file – this contains
Users and add a few users to the site.
Once you have the users inside the
DateTimeField(‘date opened’, system, you can now add a few issues
the regex-based URL mapping from to the system.
auto_now_add=True) model to view. Update the urls.py file
modified_on = models. as follows:
DateTimeField(‘date modified’, from django.conf.urls import
auto_now=True) patterns, include, url
from django.contrib import
def name(self): admin
return self.summary. admin.autodiscover()
split(‘\n’,1)[0]
urlpatterns = patterns(‘’,
# Admin front end for the url(r’^admin/’,
app. We are also configuring include(admin.site.urls)),
some of the )
# built in attributes for
the admin interface on
# how to display the list, Starting the Django
Click the Add button next to Issues.
how it will be sorted web server Here you will notice that you can enter
# what are the search
Owner, Status and Summary for the
fields etc.
class IssueAdmin(admin.
ModelAdmin):
06 Django includes a built-in
web server which is very
handy to debug and test Django
issue. But what about the opened_on
and modified_on field that we
date_hierarchy = applications. Let’s start it to see how
‘opened_on’ our admin interface works…
list_filter =
(‘status’,’owner’)
To start the web server: “It’s great that
$ python manage.py
list_display = (‘id’,’n runserver the owner ield
ame’,’status’,’owner’,’modifi
ed_on’) If you do not have any errors in your
is automatically
search_fields =
[‘description’,’status’]
code, the server should be available populated with
on port 8000. To launch the admin
interface, navigate your browser to details of the users
# register our site with
the Django admin interface
http://localhost:8000/admin.
You will be asked to log in here.
inside the site”
admin.site. Enter the username and password

28
Make web apps with Python Introducing Python

defined while modelling the app? Creating the public user include(admin.site.urls)),
They are not here because they are interface for ludissues )
not supposed to be entered by the This ensures that all the requests will be
user. opened_on will automatically processed by ludissues.urls first.
set to the date time it is created and
modified_on will automatically set
07 At this point, the admin
interface is working. But
we need a way to display the Creating ludissues.url
to the date time on which an issue data that we have added using
is modified. the admin interface. But there is
Another cool thing is that
the owner field is automatically
no public interface. Let’s create
it now.
08 Create a urls.py file in the
app directory (ludissues/urls.
py) with the following content:
populated with all the users inside We will have to begin by
from django.conf.urls
the site. editing the main
import patterns, include, url
We have defined our list view to urls.py (ludIssueTracker/urls.py).
# use ludissues model
show ID, name, status, owner and urlpatterns = patterns(‘’,
from models import
‘modified on’ in the model. You
ludissues
can get to this view by navigating (r’^’,include(‘ludissues.
to http://localhost:8000/admin/ urls’)),
# dictionary with all the
ludissues/issue/. (r’^admin/’,

29
Introducing Python Make web apps with Python

objects in ludissues Which translates to ludIssueTracker/ In Django, we start with the


info = { ludIssueTracker/templates/. Since ludIssueTracker/ludIssueTracker/
‘queryset’:ludissues. we will be accessing the templates templates/base.html template. Think of
objects.all(), from the ludissues app, the it as the master template which can be
} complete directory path would be inherited by slave ones.
ludIssueTracker/ludIssueTracker/ ludIssueTracker/ludIssueTracker/
# To save us writing lots of templates/ludissues. Create these templates/base.html
python code folders in your project folder. <!DOCTYPE html PUBLIC “-//
# we are using the list_ Also, create the directory W3C//DTD XHTML Strict//EN”
detail generic view ludIssueTracker/ludIssueTracker/media/ “ HYPERLINK “http://www.
for holding the CSS file. Copy the style. w3.org/TR/xhtml1/DTD/xhtml1-
#list detail is the name of css file from the resources directory strict.dtd” http://www.w3.org/TR/
view we are using of the code folder. To serve files from xhtml1/DTD/xhtml1-strict.dtd”>
urlpatterns = this folder, make it available publicly. <html>
patterns(‘django.views.generic. Open settings.py and add these lines in <head>
list_detail’, ludIssueTracker/ludIssueTracker/urls.py: <title>{% block title
#issue-list and issue-detail %}{% endblock %}LUD Issues</
are the template names from django.conf.urls import title>
#which will be looked in the patterns, include, url <link rel=”stylesheet”
default template from django.conf import href=”{{ MEDIA_URL }}style.css”
#directories settings type=”text/css” media=”screen”
url(r’^$’,’object_ # Uncomment the next two />
list’,info,name=’issue-list’), lines to enable the admin: </head>
url(r’^(?P<object_ from django.contrib import <body>
id>\d+)/$’,’object_ admin <div id=”hd”>
detail’,info,name=’issue-detail’), admin.autodiscover() <h1>LUD
Issue Tracker</span></h1>
) urlpatterns = patterns(‘’, </div>
(r’^’,include(‘ludissues. <div id=”mn”>
To display an issue list and details, urls’)), <ul>
we are using a Django feature called (r’^admin/’, include(admin.
generic views. In this case we are site.urls)), <li><a href=”{% url issue-list
using views called list and details. This (r’^media/ %}” class=”sel”>View Issues</
allow us to create an issue list view (?P<path>.*)$’,’django.views. a></li>
and issue detail view. These views are static.serve’,
then applied using the issue_list.html {‘document_root’:settings. <li><a href=”/admin/”>Admin
and issue_detail.html template. In MEDIA_ROOT}) Site</a></li>
the following steps we will create the ) </ul>
template files. </div>
Creating the template files <div id=”bd”>
{% block
Setting up template and content %}{% endblock %}
media directories
10 Templates will be loaded
from the ludIssueTracker/
ludIssueTracker/templates directory.
</body>
</div>

09 In this step we will create the


template and media directories.
We have already mentioned the
</html>

template directory as
TEMPLATE_DIRS = ( “To display an issue list and details here,
)
getabspath(‘templates’)
we are using a Django feature called
generic views”
30
Make web apps with Python Introducing Python

{{ variablename }} represents a issue.name }}</a></td> h2>


Django variable. <td>{{ issue.status <div class=”date”>
(% block title %} represents blocks. }}</td> <p class=”cr”>Opened
Contents of a block are evaluated <td>{{ issue. {{ object.opened_on }} ago</p>
by Django and are displayed. These owner}}</td> <p class=”up”>Last
blocks can be replaced by the child </tr> modified {{ object.modified_on
templates. {% endfor %} }} ago</p>
Now we need to create the issue_list. </table> </div>
html template. This template is {% endblock %} <div
responsible for displaying all the class=”clear”>&nbsp;</div>
issues available in the system. Here we are inheriting the base. <div class=”block
ludIssueTracker/ludIssueTracker/ html file that we created earlier. {% w49 right”>
templates/ludissues/issue_list.html for issue in object_list %} runs on the <p class=”ass
{% extends ‘base.html’ %} object sent by the urls.py. Then we title”>Owner</p>
{% block title %}View Issues - are iterating on the object_list for <p class=”ass”>{{
{% endblock %} issue.id and issue.name. object.owner }}</p>
{% block content %} Now we will create issue_detail. </div>
<table cellspacing=”0” html. This template is responsible for <div
class=”column-options”> displaying the detail view of a case. class=”clear”>&nbsp;</div>
<tr> ludIssueTracker/ludIssueTracker/ <div class=”block”>
<th>Issue</th> templates/ludissues/issue_detail. <p class=”des
<th>Description</th> html title”>Summary</p>
<th>Status</th> {% extends ‘base.html’ %} <p class=”des”>{{
<th>Owner</th> {% block title %}Issue #{{ object.summary }}</p>
</tr> object.id }} - {% endblock %} </div>
{% for issue in object_list {% block content %} </div>
%} <h2>Issue #{{ object.id }} {% endblock %}
<tr> <span>{{ object.status }}</
<td><a href=”{% url span></h2> And that’s everything! The issue
issue-detail issue.id %}”>{{ <div class=”issue”> tracker app is now complete and
issue.id }}</a></td> <h2>Information</ ready to use. You can now point your
<td><a href=”{% url browser at localhost:8000 to start
issue-detail issue.id %}”>{{ using the app.

31
Introducing Python Build an app for Android with Python

Build an app for


Android with Python
Master Kivy, the excellent cross-platform application
framework to make your irst Android app…
behaviour, the ModalView with
a pop-up behaviour as used
last time, and the FloatLayout
as we will explain later. Kivy has
many other pre-built widgets for
creating GUIs, but this time we’re
going to focus on drawing the
whole GUI from scratch using
Kivy's graphics instructions. These
The great thing about Kivy is to make any sort of program comprise either vertex instructions
there are loads of directions you like. to create shapes (including
we could take it in to do some Once you’ve mastered Kivy, rectangles, lines, meshes, and
pretty fancy things. But, we’re your imagination is the only so on) or contextual graphics
going to make a beeline for one limit. If you’re pretty new to Kivy, changes (such as translation,
of Kivy’s coolest features - the don’t worry, we won’t assume rotation, scaling, etc), and are able
ability it afords you to easily run that you have any pre-existing to be drawn anywhere on your
your programs on Android. knowledge. As long as you have screen and on any widget type.
We’ll approach this by irst mastered some of the Python Before we can do any of this
showing how to make a new in this book so far, and have a we'll need a class for each kind of
app, this time a dynamic fairly good understanding of the game object, which we’re going
Breakout-style game. We’ll then language, you shouldn’t have to pre-populate with some of
be able to compile this straight any problems following along the properties that we'll need
to an Android APK that you can with this. later to control them. Remember
use just like any other. from last time, Kivy properties are
Of course, once you have Before anything else, let's special attributes declared at class
mastered the basic techniques throw together a basic Kivy app level, which (among other things)
you aren’t limited to using any (Fig. 01). We've pre-imported can be modiied via kv language
particular kind of app, as even on the widget types we'll be using, and dispatch events when they
Android you can make use of all which this time are just three: are modiied. The Game class will
your favourite Python libraries the basic Widget with no special be one big widget containing

32
Build an app for Android with Python Introducing Python

the entire game. We've speciically the widget canvas, which we diferent properties that can be
made it a subclass of FloatLayout can use here to draw each of our set, like the pos and size of the
because this special layout is able widget shapes: rectangle, and you can check the
to position and size its children <Player>: Kivy documentation online for
in proportion to its own position canvas: all the diferent possibilities. The
Color:
and size – so no matter where we biggest advantage is that although
rgba: 1, 1, 1, 1
run it or how much we resize the Rectangle: we still declare simple canvas
window, it will place all the game pos: self.pos instructions, kv language is able
objects appropriately. size: self.size to detect what Kivy properties we
Next we can use Kivy's graphics have referred to and automatically
instructions to draw various <Ball>: track them, so when they are
shapes on our widgets. We'll just canvas: updated (the widget moves or is
Color:
demonstrate simple rectangles to resized) the canvas instructions
rgb: 1, 0.55, 0
show their locations, though there Rectangle: move to follow this!
are many more advanced options pos: self.pos
you might like to investigate. In size: self.size Fig 01
a Python ile we can apply any
instruction by declaring it on the <Block>: from kivy.app import App
canvas: from kivy.uix.widget import
canvas of any widget, an example
Color: Widget
of which is shown in Fig. 03. from kivy.uix.floatlayout
rgb: self.colour
This would draw a red rectangle # A property we import FloatLayout
with the same position and size predefined above from kivy.uix.modalview
as the player at its moment of Rectangle: import ModalView
instantiation – but this presents a pos: self.pos
problem, unfortunately, because size: self.size __version__ = '0.1' #
Color: Used later during Android
the drawing is static. When we
rgb: 0.1, 0.1, 0.1 compilation
later go on to move the player
Line:
widget, the red rectangle will class BreakoutApp(App):
rectangle:
stay in the same place, while the [self.x, self.y, pass
widget will be invisible when it is self.width, self.
in its real position. height] BreakoutApp().run()
We could ix this by keeping
references to our canvas The canvas declaration is special,
instructions and repeatedly underneath it we can write any Fig 02
updating their properties to track canvas instructions we like. Don't
from kivy.properties
the player, but there's actually an get confused, canvas is not a
import (ListProperty,
easier way to do all of this - we widget and nor are graphics
NumericProperty,
can use the Kivy language we instructions like Line. This is just
introduced last time. It has a a special syntax that is unique to O bje c t Pr o p e r t y,
special syntax for drawing on the canvas. Instructions all have StringProperty)

33
Introducing Python Build an app for Android with Python

class Game(FloatLayout): def __init__(self, jump,


# Will contain everything **kwargs): 'y': 0.05 + 0.09*y_
blocks = ListProperty([]) super(Player, jump})
player = ObjectProperty() self).__init__(**kwargs) self.blocks.
# The game's Player instance with self. append(block)
ball = ObjectProperty() # canvas: self.add_
The game's Ball instance Color(1, 0, widget(block)
0, 1) # r, g, b, a -> red class BreakoutApp(App):
class Player(Widget): # A def build(self):
Rectangle(pos=self.pos, g = Game()
moving paddle
size=self.size) g.setup_blocks()
position =
# or without return g
NumericProperty(0.5)
the with syntax, self. Here we create the widgets we
direction =
canvas.add(...)
StringProperty('none') want then use add_widget to add
them to the graphics tree. Our
class Ball(Widget): # A root widget on the screen is an
bouncing ball instance of Game and every block
# pos_hints are for is added to that to be displayed.
proportional positioning, Above Running the app shows our coloured The only new thing in there is
blocks on the screen… but they all overlap! We
see below can fix that easily that every Block has been given
pos_hint_x =
You probably noticed we a pos_hint. All widgets have this
NumericProperty(0.5)
pos_hint_y = had one of the Block’s ‘Color’ special property, and it is used by
NumericProperty(0.3) instructions refer to its colour FloatLayouts like our Game to set
proper_size = property. This means that we can their position proportionately to
NumericProperty(0.) change the property any time to the layout.
velocity = update the colour of the block, or The dictionary is able to handle
ListProperty([0.1, 0.5]) in this case to give each block a various parameters, but in this
random colour (Fig. 04). case ‘x’and ‘y’ give x and y Block
class Block(Widget): # Now that each of our widgets position as a relative fraction of
Each coloured block to the parent width and height.
has a graphical representation,
destroy
let’s now tell our Game where You can run the app now, and
colour =
to place them, so that we can this time it will add 50 blocks to
ListProperty([1, 0, 0])
start up the app and actually see the Game before displaying it
Fig 03 something there. on the screen. Each should have
class Game(FloatLayout): one of the three possible random
from kivy.graphics.context_ def setup_blocks(self): colours and be positioned in a
instructions import Color for y_jump in range(5): grid, but you'll now notice their
from kivy.graphics. for x_jump in
vertex_instructions import sizes haven't been manually set so
range(10):
Rectangle they all overlap. We can ix this by
block = Block(pos_
hint={ setting their size_hint properties –
class Player(Widget): 'x': 0.05 + 0.09*x_ and let's also

34
Build an app for Android with Python Introducing Python

take this opportunity to do the positions and carrying out game if scancode == 275:
same for the other widgets as logic – in this case collisions with self.direction =
well (Fig. 05). the ball (Fig. 06). 'right'
This takes care of keeping all our The Clock can schedule elif scancode == 276:
self.direction = 'left'
game widgets positioned and any function at any time,
else:
sized in proportion to the Game either once or repeatedly. A self.direction = 'none'
containing them. Notice that the function scheduled at interval
Player and Ball use references to automatically receives the time def on_key_up(self, *args):
the properties we set earlier, so since its last call (dt here), which self.direction = 'none'
we'll be able to move them by we've passed through to the ball
just setting these properties and and player via the references we def update(self, dt):
dir_dict = {'right': 1,
letting kv language automatically created in kv language. It's good
'left': -1, 'none': 0}
update their positions. practice to scale the update (eg self.position += (0.5
The Ball also uses an extra ball distance moved) by this dt, * dt * dir_ dict[self.
property to remain square rather so things remain stable even if direction])
than rectangular, just because the something interrupts the clock These on_touch_ functions
alternative would likely look a little and updates don't meet the are Kivy's general method for
bit odd. regular 1/60s you want. interacting with touch or mouse
We've now almost inished At this point we have also input, they are automatically
the basic graphics of our app! All added the irst steps toward called when the input is detected
that remains is to add a Ball and a handling keyboard input, by and you can do anything you
Player widget to the Game. binding to the kivy Window to like in response to the touches
<Game>: call a method of the Player every you receive. In this case we set
ball: the_ball time a key is pressed. We can the Player's direction property
player: the_player then inish of the Player class by in response to either keyboard
Ball:
adding this key handler along and touch/mouse input, and
id: the_ball
Player: with touch/mouse input. use this direction to move the
id: the_player Player when its update method is
You can run the game again class Player(Widget): called. We can also add the right
def on_touch_down(self, behaviour for the ball (Fig. 07).
now, and should be able to see
touch):
all the graphics working properly. This makes the ball bounce of
self.direction = (
Nothing moves yet, but thanks to 'right' if touch.x > every wall by forcing its velocity
the FloatLayout everything should self.parent. center_x else to point back into the Game,
remain in proportion if you resize 'left') as well as bouncing from the
the game/window. player paddle – but with an extra
Now we just have to add the def on_touch_up(self, kick just to let the ball speed
touch): change. It doesn't yet handle any
game mechanics. For a game like
self.direction = 'none'
this you usually want to run some interaction with the blocks or
update function many times per def on_key_down(self, any win/lose conditions, but it
second, updating the widget keypress, scancode, *args): does try to call Game.lose() if the
35
Introducing Python Build an app for Android with Python

ball hits the bottom of the player's of your Android devices. You can size_hint: None, None
screen, so let's now add in some even access the normal Android proper_size:
game end code to handle all of this API to access hardware or OS min(0.03*self.parent.
height, 0.03*self.parent.width)
(Fig. 08). And then add the code in features such as vibration, sensors
size: self.proper_size,
Fig. 09 to your 'breakout.kv 'ile. or native notiications. self.proper_size
This should fully handle the We'll build for Android using # ... canvas part
loss or win, opening a pop-up the Buildozer tool, and a Kivy
with an appropriate message sister project wrapping other Fig 06
and providing a button to try build tools to create packages on from kivy.clock import
again. Finally, we have to handle diferent systems. This takes care Clock
destroying blocks when the ball of downloading and running from kivy.core.window
hits them (Fig. 10). the Android build tools (SDK, import Window
from kivy.utils import
This fully covers these last NDK, etc) and Kivy's Python-for- platform
conditions, checking collision Android tools that create the APK.
via Kivy's built-in collide_widget class Game(FloatLayout):
method that compares their Fig 04 def update(self, dt):
bounding boxes (pos and size). The self.ball.
import random update(dt) # Not defined yet
bounce direction will depend on self.player.
how far the ball has penetrated, as class Block(Widget): update(dt) # Not defined yet
this will tell us how it irst collided def __init__(self,
**kwargs): def start(self,
with the Block. super(Block,
So there we have it, you can *args):
self).__init__(**kwargs) Clock.schedule_
run the code to play your simple self.colour = interval(self.update, 1./60.)
Breakout game. Obviously it's very random.choice([
simple right now, but hopefully (0.78, 0.28, def stop(self):
0), )0.28, 0.63, 0.28), )0.25, Clock.
you can see lots of diferent ways 0.28, 0.78)])
to add whatever extra behaviour unschedule(self.update)
you like – you could add diferent Fig 05 def reset(self):
types of blocks and power-ups, a for block in
lives system, more sophisticated <Block>: self.blocks:
size_hint: 0.09, 0.05 self.remove_
paddle/ball interaction, or even
# ... canvas part widget(block)
build a full game interface with a
self.blocks = []
menu and settings screen as well. <Player>: self.setup_
We’re just going to inish size_hint: 0.1, 0.025 blocks()
showing one cool thing that you pos_hint: {'x': self. self.ball.velocity
can already do – compile your position, 'y': 0.1} = [random.random(), 0.5]
# ... canvas part self.player.
game for Android! Generally
position = 0.5
speaking you can take any Kivy <Ball>:
app and turn it straight into an pos_hint: {'x': self.pos_ class BreakoutApp(App):
Android APK that will run on any hint_x, 'y': self.pos_hint_y} def build(self):
36
Build an app for Android with Python Introducing Python

g = Game()
if platform() != def bounce_
Fig 09
'android': f r o m _ p l a y e r (s e lf,
Window. player): <GameEndPopup>:
bind(on_key_down=g.player. if self. size_hint: 0.8, 0.8
on_key_down) collide_widget(player): auto_dismiss: False
Window. self. # Don't close if player
bind(on_key_up=g.player.on_ velocity[1] = abs(self. clicks outside
key_up) velocity[1]) BoxLayout:
g.reset() orientation:
self.
Clock.schedule_ 'vertical'
velocity[0] += (
once(g.start, 0) Label:
return g 0.1
* ((self.center_x - text: root.
player.center_x) / message
Fig 07 font_size:
player.width)) 60
markup: True
class Ball(Widget)
def update(self, dt): halign:
Fig 08 'center'
self.pos_hint_x
+= self.velocity[0] * dt Button:
c l a s s size_hint_y:
self.pos_hint_y GameEndPopup(ModalView):
+= self.velocity[1] * dt None
message = height:
if self.right > StringProperty()
self.parent.right: # Bounce sp(80)
game = text: 'Play
from right
ObjectProperty() again?'
self.
velocity[0] = -1 * abs(self. font_size:
class Game(Widget): 60
velocity[0])
def lose(self): on_release:
if self.x < self.
parent.x: # Bounce from left self.stop() root.game.start(); root.
self. GameEndPopup( dismiss()
velocity[0] = abs(self. message='[color=#ff0000]You
lose![/color]', Here you will be needing
velocity[0]) some basic dependencies, which
if self.top
game=self).open() can be installed with ease just
> self.parent.top: # Bounce
from top by using your distro's normal
self. def win(self): # repositories. The main ones to use
velocity[1] = -1 * abs(self. Not called yet, but we'll are OpenJDK7, zlib, an up-to-date
velocity[1]) need it later Cython, and Git. If you are using
if self.y < self. self.stop() a 64-bit distro you will also be
parent.y: # Lose at bottom GameEndPopup(
in need of 32-bit compatibility
self.parent. message='[color=#00ff00]You
win![/color]', libraries for zlib, libstdc++, as well
lose() # Not implemented yet
self.bounce_from_ as libgcc. You can then go on and
player(self.parent.player) game=self).open() download and install Buildozer:

37
Introducing Python Build an app for Android with Python

Putting your APK “Check through the whole ile just to see
on the Play Store
what’s available, but most of the default
Find out how to digitally sign a
release APK and upload it to an settings will be ine”
app store of your choice

1Build
APK
and sign a release

Begin by creating a personal


git clone git://github.com/
When you irst run it, it will
digital key, then using it to sign kivy/buildozer
a special release version of the cd buildozer download both the Android SDK
APK. Run these commands, and sudo python2.7 setup.py and NDK, which are large (at least
follow the instructions.
install hundreds of megabytes) but vital
## Create your personal to the build. It will also take time
digital key ## When you’re done with that part to build these and to compile the
You can choose your own you can then go on and navigate Python components of your APK.
## keystore name, alias,
and passwords. to your Kivy app, and you’ll have A lot of this only needs to be
$ keytool -genkey -v to name the main code ile ‘main. done once, as future builds will
-keystore test- release- py’, this is the access point that the take a couple of minutes if you
key.keystore \
-alias test-alias Android APK will expect. Then: change the buildozer.spec, or
-keyalg RSA buildozer init just a few seconds if you've only
changed your code.
-keysize 2048 -validity This creates a ‘buildozer.spec’ ile,
10000 The APK produced is a debug
## Compile your app in a settings ile containing all the APK, and you can install and use
release mode information that Buildozer needs it. There are extra steps if you
$ buildozer android to create your APK, from the name
release want to digitally sign it so that it
## Sign the APK with your and version to the speciic Android can be posted on the Play store.
new key build options. We suggest that you This isn't hard, and Buildozer can
$ jarsigner -verbose check through the whole ile just
-sigalg do some of the work, but check
SHA1withRSA -digestalg to see what's available but most of the documentation online for
SHA1 \ the default settings will be ine, the full details.
-keystore ./test- only thing we suggest changing
release-key.keystore \ Assuming everything goes
./bin/KivyBreakout-0.1- is (Fig. 11). ine (it should!), your Android
release- There are various other options APK will be in a newly created
unsigned.apk test-alias you will often want to set, but
## Align the APK zip file 'bin' directory with the name
$ ~/.buildozer/android/ none are really all that vital right ‘KivyBreakout-0.1-debug.apk’.
platform/android- sdk-21/ now, so you’re able to immediately You can send it to your phone
tools/zipalign -v 4 \ tell Buildozer to build your APK and
./bin/KivyBreakout-0.1- any way you like (eg email),
release- get going! though you may need to
unsigned.apk \ buildozer android debug
enable application installation
./bin/KivyBreakout-0.1-
release.apk This will take some time, so be from unknown sources in your
patient and it will work out ine. Settings before you can install it.
38
Build an app for Android with Python Introducing Python

if len(self.
Fig 10 blocks) == 0:
self.
2Sign up as a Google Play
Developer
Visit https://play.google.com/
self.parent.do_ apps/publish/signup, and follow
win()
layout() the instructions. You'll need to
return # pay a one-of $25 charge, but
self.parent.destroy_
Only remove at most 1 block then you can upload as many
blocks(self) apps as you like.
per frame
class Game(FloatLayout):
def destroy_blocks(self, Fig 11 3Upload
store
your app to the

Click 'Add new application'


ball): to submit your app the store,
for i, block in title = Kivy Breakout # including uploading your APK
and adding description text.
enumerate(self.blocks): Displayed in your app drawer When everything is ready, simply
if ball. package.name = breakout # click Publish, and it should take
collide_widget(block): Just a unique identifying just a few hours for your app to
go live!
y_overlap string,
=( #
ball. along with the package.
top - block.y if ball. domain
velocity[1] > 0 fullscreen = 0 # This will
else mean the navbar is not
block.top - ball.y) / block. covered
size_hint_y log_level = 2 # Not vital,
x_overlap but this will print a lot
=( more debug
ball. # information
right - block.x if ball. and may be useful if
velocity[0] > 0 something
else # goes wrong
block.right - ball.x) /
block.size_hint_x
if x_
overlap < y_overlap:

ball.velocity[0] *=
-1

else:

ball.velocity[1] *=
-1

self.
remove_widget(block)
self.blocks. Above Your game should run on any modern
Android device… you can even build a release
pop(i) version and publish to an app store!

39
Introducing Python 50 Python tips

50 Python tips
Python is a programming language that lets you work more quickly and
integrate your systems more efectively. Today, Python is one of the most popular
programming languages in the open source space. Look around and you will
ind it running everywhere, from various coniguration tools to XML parsing. Here
is the collection of 50 gems to make your Python experience worthwhile…

at the Python prompt. assignment. Python does not

Basics It is also important to remember


that Python takes tabs very seriously
support inline assignment,
so there’s no chance of
– so if you are receiving any error that accidentally assigning the value
Running Python scripts mentions tabs, correct the tab spacing. when you actually want to
compare it.

01 On most of the UNIX systems,


you can run Python scripts from
the command line.
Dynamic typing Concatenating strings
$ python mypyprog.py
03 In Java, C++, and other statically
typed languages, you must
specify the data type of the function
06 You can use ‘+’ to concatenate
strings.
Running Python programs return value and each function
>>> print ‘kun’+’al’
kunal
from Python interpreter argument. On the other hand, Python
is a dynamically typed language. In
Python you will never have to explicitly
The __init__ method
02 The Python interactive
interpreter makes it easy to specify the data type of anything you
try your first steps in programming
and using all Python commands.
use. Based on what value you assign,
Python will automatically keep track of 07 The __init__ method is run as
soon as an object of a class is
instantiated. The method is useful to do
You just issue each command at the the data type internally.
command prompt (>>>), one by any initialization you want to do with
your object. The
one, and the answer is immediate. Python statements __init__ method is analogous to a
Python interpreter can
be started by issuing the constructor in C++, C# or Java.
command:
$ python
04 Python uses carriage returns
to separate statements, and
a colon and indentation to separate
Example:
class Person:
kunal@ubuntu:~$ python def __init__(self, name):
code blocks. Most of the compiled self.name = name
Python 2.6.2 (release26- programming languages, such as C
maint, Apr 19 2009, 01:56:41) def sayHi(self):
and C++, use semicolons to separate print ‘Hello, my name
[GCC 4.3.3] on linux2 statements and curly brackets to
Type “help”, “copyright”, is’, self.name
separate code blocks. p = Person(‘Kunal’)
“credits” or “license” for
more information. p.sayHi()
>>> <type commands here> == and = operators Output:
In this article, all the code [~/src/python $:] python
initmethod.py
starting at the
>>> symbol is meant to be given 05 Python uses ‘==’ for
comparison and ‘=’ for Hello, my name is Kunal

40
50 Python tips Introducing Python

Modules point number ‘eggs’]


This example returns the CPU time or >>> print ‘, ‘.join(mylist)
real time since the start of the process spam, ham, eggs
08 To keep your programs
manageable as they grow in
size you may want to make them into
or since the first call to clock(). This has
just as much precision as the system
2nd method:
>>> print ‘\n’.join(mylist)
several files. Python allows you to put records do. spam
multiple function definitions into a file ham
and use them as a module that can be Passing arguments eggs
imported. These files must have a .py to a Python script
extension however. Tab completion
Example: in Python interpreter
# file my_function.py
def minmax(a,b): 11 Python lets you access whatever
you have passed to a script
if a <= b:
min, max = a, b
else:
while calling it. The ‘command line’
content is stored in the sys.argv list.
import sys
15 You can achieve auto
completion inside Python
interpreter by adding these lines to
min, max = b, a print sys.argv your .pythonrc file (or your file for
return min, max Python to read on startup):
Module Usage Loading modules or import rlcompleter, readline
import my_function readline.parse_and_bind(‘tab:
commands at startup complete’)
This will make Python complete
Module defined names
12 You can load predefined
modules or
partially typed function, method and
variable names when you press the

09 Example:
The built-in function ‘dir()’ can
be used to find out which names a
commands at the startup of
any Python script by using
the environment variable
Tab key.

Python
module defines. It returns a sorted list $PYTHONSTARTUP. You can
of strings. set environment variable documentation tool
>>> import time $PYTHONSTARTUP to a file which
>>> dir(time)
[‘__doc__’, ‘__file__’,
‘__name__’, ‘__package__’,
contains the instructions load
necessary modules or commands . 16 You can pop up a graphical
interface for searching the
Python documentation using the
‘accept2dyear’, ‘altzone’, Converting a string command:
‘asctime’, ‘clock’, ‘ctime’, to date object $ pydoc -g
‘daylight’, ‘gmtime’, ‘localtime’, You will need python-tk package for
‘mktime’, ‘sleep’, ‘strftime’, this to work.
‘strptime’, ‘struct_time’,
‘time’, ‘timezone’, ‘tzname’,
13 You can use the function
‘DateTime’ to convert a string to a
date object.
‘tzset’]file’] Example:

Module internal
from DateTime import DateTime “Today, Python is
documentation
dateobj = DateTime(string)
certainly one of
Converting a string
the most popular
10 You can see the internal
documentation (if available) of to date object programming
a module name by looking at languages to be
.__doc__.
Example: 14 You can convert a list to string
in the following ways. found in the open
>>> import time
>>> print time.clock.__doc__
1st method:
>>> mylist = [‘spam’, ‘ham’,
source space”
clock() -> floating

41
Introducing Python 50 Python tips

Accessing the Python Converting from integer Detecting system


documentation server to binary and more platform

17 You can start an HTTP server


on the given port on the
local machine. This will give you a
20 Python provides easy-to-use
functions – bin(), hex() and
oct() – to convert from integer to binary,
24 To execute platform-specific
functions, it is very useful to
detect the platform on which the
nice-looking access to all Python decimal and octal format respectively. Python interpreter is running. You can
documentation, including third-party Example: use ‘sys.platform’ to find out the current
module documentation. >>> bin(24) platform.
$ pydoc -p <portNumber> ‘0b11000’ Example:
>>> hex(24) On Ubuntu Linux
Python development ‘0x18’ >>> import sys
>>> oct(24) >>> sys.platform
software ‘030’ ‘linux2’
On Mac OS X Snow Leopard
Converting any
18 There are plenty of tools to help
with Python development.
Here are a few important ones:
charset to UTF-8
>>> import sys
>>> sys.platform
‘darwin’
IDLE: The Python built-in IDE, with
autocompletion, function signature
popup help, and file editing.
IPython: Another enhanced Python
21 You can use the following
function to convert any charset
to UTF-8.
Disabling and enabling
garbage collection
shell with tab-completion and data.decode(“input_charset_
other features.
Eric3: A GUI Python IDE with
here”).encode(‘utf-8’)
25 Sometimes you may
want to enable or disable
autocompletion, class browser, built-in Removing the garbage collector function
shell and debugger. at runtime. You can use the ‘gc’
WingIDE: Commercial Python IDE
duplicates from lists module to enable or disable the
with free licence available to open- garbage collection.
source developers everywhere.
22 If you want to remove duplicates
from a list, just put every
element into a dict as a key (for
Example:
>>> import gc
>>> gc.enable
Built-in modules example with ‘none’ as value) and then <built-in function enable>
check dict.keys(). >>> gc.disable
Executing at Python from operator import setitem <built-in function
interpreter termination def distinct(l): disable>
d = {}
map(setitem, (d,)*len(l),
Using C-based modules
19 You can use ‘atexit’ module to
execute functions at the time of
Python interpreter termination.
l, [])
return d.keys()
for better performance
Example:
Do-while loops
def sum():
print(4+5) 26 Many Python modules
ship with counterpart
def message():
print(“Executing Now”)
import atexit
23 Since Python has no do-while
or do-until loop constructs (yet),
you can use the following method to
C modules. Using these C
modules will give a significant
performance boost in your
atexit.register(sum) achieve similar results: complex applications.
atexit.register(message) while True: Example:
Output: do_something() cPickle instead of
Executing Now if condition(): Pickle, cStringIO instead
9 break of StringIO .

42
50 Python tips Introducing Python

initializer]) capital letter


Calculating maximum, Once you have created an array Match!
minimum and sum object, say myarray, you can apply a >>> if re.search(“\d”, s):
bunch of methods to it. Here are a few print “Match!” # digits class

27 You can use the following built-


in functions.
max: Returns the largest element in
important ones:
myarray.count(x): Returns the
number of occurrences of x
...

Working with bzip2 (.bz2)


the list. in a. compression format
min: Returns the smallest element in myarray.extend(x): Appends x
the list. at the end of the array.
sum: This function returns the sum
of all elements in the list. It accepts an
optional second argument: the value
myarray.reverse(): Reverse the
order of the array. 33 You can use the module ‘bz2’
to read and write data using
the bzip2 compression algorithm.
to start with when summing (defaults Sorting items bz2.compress() : For bz2
to 0). compression
bz2.decompress() : For bz2
Representing
fractional numbers
31 The ‘bisect’ module makes
it very easy to keep lists in
any possible order. You can use the
decompression
Example:
# File: bz2-example.py
following functions to order lists. import bz2

28 Fraction instance can be


created in Python using the
following constructor:
bisect.insort(list, item [,
low [, high]])
Inserts item into list in sorted order. If
MESSAGE = “Kunal is a bad
boy”
compressed_message = bz2.
Fraction([numerator item is already in the list, the new entry compress(MESSAGE)
[,denominator]]) is inserted to the right of any existing decompressed_message = bz2.
entries there. decompress(compressed_message)
Performing bisect.insort_left(list, item print “original:”,
math operations [, low [, high]]) repr(MESSAGE)
Inserts item into list in sorted order. print “compressed message:”,
If item is already within the list, the repr(compressed_ message)

29 The ‘math’ module provides


a plethora of mathematical
functions. These functions work on
new entry is inserted to the left of any
existing entries.
print “decompressed message:”,
repr(decompressed_message)
Output:
integer and float numbers, except Using regular [~/src/python $:] python bz2-
complex numbers. For complex example.py
numbers, a separate module is used,
expression-based search original: ‘Kunal is a bad
called ‘cmath’. boy’
For example:
math.acos(x): Return arc
cosine of x.
32 The ‘re’ module makes it very
easy to use regxp-based
searches. You can use the function
compressed message:
‘BZh91AY&SY\xc4\x0fG\x98\ x00\
x00\x02\x15\x80@\x00\x00\x084%\
math.cos(x): Returns cosine ‘re.search()’ with a regexp-based x8a \x00”\x00\x0c\x84\r\x03C\
of x. expression. Check out the example xa2\xb0\xd6s\xa5\xb3\x19\x00\xf8\
math.factorial(x) : Returns x included below. xbb\x92)\xc2\x84\x86 z<\xc0’
factorial. Example: decompressed message: ‘Kunal
>>> import re is a bad boy’
>>> s = “Kunal is a bad boy”
Working with arrays >>> if re.search(“K”, s):
print “Match!” # char literal
“There are tools to
30 The ‘array’ module provides
an efficient way to use arrays
in your programs. The ‘array’ module
...
Match!
>>> if re.search(“[@A-Z]”, s):
help develop
defines the following type: print “Match!” # char class with Python”
array(typecode [, ... # match either at-sign or

43
Introducing Python 50 Python tips

Using SQLite database Using wildcards to search Executing UNIX


with Python for filenames commands from Python

34 SQLite is fast becoming a very


popular embedded database
because of the zero configuration that
36 You can use the module ‘glob’
to find all the pathnames
matching a pattern according to the
38 You can use module
commands to execute
UNIX commands. This is not
is needed, and its superior levels of rules used by the UNIX shell. *, ?, and available in Python 3 – instead,
performance. You can use the module character ranges expressed with [ ] will in this, you will need to use the
‘sqlite3’ in order to work with these be matched. module ‘subprocess’.
SQLite databases. Example: Example:
Example: >>> import glob >>> import commands
>>> import sqlite3 >>> glob.glob(‘./[0-9].*’) >>> commands.
>>> connection = sqlite. [‘./1.gif’, ‘./2.txt’] getoutput(‘ls’)
connect(‘test.db’) >>> glob.glob(‘*.gif’) ‘bz2-example.py\ntest.py’
>>> curs = connection. [‘1.gif’, ‘card.gif’]
cursor() >>> glob.glob(‘?.gif’) Reading environment
>>> curs.execute(‘’’create [‘1.gif’] variables
table item
... (id integer primary key, Performing basic file
itemno text unique,
... scancode text, descr text,
price real)’’’)
operations 39 You can use the module ‘os’
to gather up some operating-
system-specific information:
<sqlite3.Cursor object at
0x1004a2b30> 37 You can use the module ‘shutil’
to perform basic file operation
at a high level. This module works with
Example:
>>> import os
>>> os.path <module ‘posixpath’
your regular files and so will not work from ‘/usr/lib/python2.6/
Working with zip files with special files like named pipes, posixpath.pyc’>>>> os.environ
block devices, and so on. {‘LANG’: ‘en_IN’, ‘TERM’: ‘xterm-

35 You can use the module ‘zipfile’


to work with zip files.
zipfile.ZipFile(filename
shutil.copy(src,dst)
Copies the file src to the file or
directory dst.
color’, ‘SHELL’:
‘/bin/bash’, ‘LESSCLOSE’:
‘/usr/bin/lesspipe %s %s’,
[, mode [, compression shutil.copymode(src,dst) ‘XDG_SESSION_COOKIE’:
[,allowZip64]]]) Copies the file permissions from src ‘925c4644597c791c704656354adf56d6-
Open a zip file, where the file can be to dst. 1257673132.347986-1177792325’,
either a path to a file (a string) or a file- shutil.move(src,dst) ‘SHLVL’: ‘1’, ‘SSH_TTY’: ‘/dev/
like object. Moves a file or directory to dst. pts/2’, ‘PWD’: ‘/ home/kunal’,
zipfile.close()¶ shutil.copytree(src, dst, ‘LESSOPEN’: ‘| /usr/bin
Close the archive file. You must call symlinks [,ignore]]) lesspipe
‘close()’ before exiting your program or Recursively copy an entire directory ......}
essential records will not be written. at src. >>> os.name
zipfile.extract(member[, shutil.rmtree(path [, ignore_ ‘posix’
path[, pwd]]) errors [, onerror]]) >>> os.linesep
Extract a member from the archive Deletes an entire directory. ‘\n’
to the current working directory;
‘member’ must be its full name (or a
zipinfo object). Its file information is
extracted as accurately as possible.
‘path’ specifies a different directory to
“Look around and you will ind Python
extract to. ‘member’ can be a filename
or a zipinfo object. ‘pwd’ is the
everywhere, from various coniguration
password used for encrypted files. tools to XML parsing”
44
50 Python tips Introducing Python

Sending email FTP(host,username,password) ‘3d01e2f741000b0224084482f905e9b7b97


# Download the file 7a59b480990ea8355e2c0’
u = urllib2.urlopen (“ftp:// # sha256 Digest
40 You can use the module
‘smtplib’ to send email using
an SMTP (Simple Mail Transfer Protocol)
ftp.redhat.com/ pub/redhat/
linux/README”)
>>> hashlib.sha256(“MI6 Classified
Information 007”).hexdigest()
client interface. # Print the file contents ‘2fdde5733f5d47b672fcb39725991c89
smtplib.SMTP([host [, port]]) print (u.read()) b2550707cbf4c6403e fdb33b1c19825e’
Example (send an email using Output: # sha384 Digest
Google Mail SMTP server): [~/src/python $:] python >>> hashlib.sha384(“MI6 Classified
import smtplib ftpclient.py Information 007”).hexdigest()
# Use your own to and from Older versions of Red Hat Linux have ‘5c4914160f03dfbd19e14d3ec1e74bd8b99
email address been moved to the following location: dc192edc138aaf7682800982488daaf540be
fromaddr = ‘kunaldeo@gmail.com’ ftp://archive.download.redhat.com/ 9e0e50fc3d3a65c8b6353572d’
toaddrs = ‘toemail@gmail.com’ pub/redhat/linux/ # sha512 Digest
msg = ‘I am a Python geek. >>> hashlib.sha512(“MI6 Classified
Here is the proof.!’
Launching a webpage Information 007”).hexdigest()
# Credentials with the web browser ‘a704ac3dbef6e8234578482a31d5ad29d25
# Use your own Google Mail
credentials while running the 2c822d1f4973f49b850222edcc0a29bb89077
program
username = ‘kunaldeo@gmail.com’ 42 ‘The ‘webbrowser’ module
provides a convenient way to
launch webpages using the default
8aea807a0a48ee4ff8bb18566140667fbaf7
3a1dc1ff192febc713d2’
password = ‘xxxxxxxx’
# The actual mail send web browser. # MD5 Digest
server = smtplib.SMTP(‘smtp. Example (launch google.co.uk >>> hashlib.md5(“MI6 Classified
gmail.com:587’) with system’s default web Information 007”).hexdigest()
# Google Mail uses secure browser): ‘8e2f1c52ac146f1a999a670c826f7126’
connection for SMTP connections >>> import webbrowser
server.starttls() >>> webbrowser.open(‘http:// Seeding random numbers
server.login(username,password) google.co.uk’)
server.sendmail(fromaddr,
toaddrs, msg)
True
44 You can use the module
‘random’ to generate a wide
variety of random numbers. The
server.quit() Creating secure hashes
most used one is ‘random.seed([x])’. It
initialises the basic random number
Accessing FTP server
43 The ‘hashlib’ module
supports a plethora of
generator. If x is omitted or None,
the current system time is used; the

41 ‘ftplib’ is a fully fledged client


FTP module for Python. To
establish an FTP connection, you can
secure hash algorithms including
SHA1, SHA224, SHA256, SHA384,
SHA512 and MD5.
current system time is also used to
initialise the generator when the
module is first imported.
use the following function: Example (create hex digest of
smtplib.SMTP([host [, port]]) the given text):
Example (send an email using >>> import hashlib
Google Mail SMTP server): # sha1 Digest “Programming in
ftplib.FTP([host [, user [,
passwd [, acct [, timeout]]]]])
>>> hashlib.sha1(“MI6
Classified Information 007”). Python lets you
Example:
host = “ftp.redhat.com”
hexdigest()
‘e224b1543f229cc0cb935a1eb9593
work more quickly
username = “anonymous” 18ba1b20c85’ and integrate your
password = “kunaldeo@gmail.
com”
# sha224 Digest
>>> hashlib.sha224(“MI6 systems much
import ftplib
import urllib2
Classified
Information 007”).hexdigest()
more efectively”
ftp_serv = ftplib.

45
Random documents with unrelated
content Scribd suggests to you:
praise God, with a loud voice, for all the mighty works that they had
seen; saying, “Blessed be the King of Israel, that cometh in the
name of the Lord! Peace in heaven! Glory in the highest! Blessed be
the kingdom of our father David! Hosanna!” These acclamations
were raised by the disciples, and heartily joined in by the multitudes
who knew his wonderful works, and more especially those who were
acquainted with the very recent miracle of raising Lazarus. A great
sensation of wonder was created throughout the city, by such a burst
of shouts from a multitude, sweeping in a long, imposing train, with
palm branches in their hands, down the mountain, on which they
could have been seen all over Jerusalem. As he entered the gates,
all the city was moved to say, “Who is this?” And the rejoicing
multitude said, “This is Jesus, the prophet of Nazareth in Galilee.”
What scorn did not this reply awaken in many of the haughty
aristocrats of Jerusalem, to learn that all this solemn parade had
been got up for no better purpose than merely to honor a dweller of
that outcast region of mongrels, Galilee! And of all places, that this
prophet, so called, should have come from Nazareth! A prophet from
Galilee, indeed! Was it from this half-heathen district, that the
favored inhabitants of the capital of Judaism were to receive a
teacher of religion? Were the strict faith, and the rigid observances of
their learned and devout, to be displaced by the presumptuous
reformations of a self-taught prophet, from such a country? Swelling
with these feelings, the Pharisees could not repress a remonstrance
with Jesus, against these noisy proceedings. But he, evidently
affected with pleasure at the honest tribute thus wrung out in spite of
sectional feeling, forcibly asserted the propriety and justice of this
free offering of praise. “I tell you, that if these should hold their
peace, the stones would immediately cry out.”

With palm-branches in their hands.――This tree, the emblem of joy and triumph in every
part of the world where it is known, was the more readily adopted on this occasion, by those
who thronged to swell the triumphal train of Jesus of Nazareth, because the palm grew
along the way-side where they passed, and the whole mount was hardly less rich in this
than in the far famed olive from which it drew its name. A proof of the abundance of the
palm-trees on Olivet is found in the name of the village of Bethany, ‫בית חיני‬, (beth-hene,)
“house of dates,” which shows that the tree which bore this fruit must have been plentiful
there. The people, as they passed on with Jesus from this village whence he started to
enter the city, would therefore find this token of triumph hanging over their heads, and
shading their path every where within reach, and the emotions of joy at their approach to
the city of God in the company of this good and mighty prophet, prompted them at once to
use the expressive emblems which hung so near at hand; and which were alike within the
reach of those who journeyed with Jesus, and those who came forth from the city to meet
and escort him in. The presence of these triumphal signs would, of course, remind them at
once of the feast of the tabernacles, the day on which, in obedience to the Mosaic statute,
all the dwellers of the city were accustomed to go forth to the mount, and bring home these
branches with songs of joy. (Leviticus xxiii. 40, Nehemiah viii. 15, 16.) The remembrance of
this festival at once recalled also the beautifully appropriate words of the noble national and
religious hymn, which they always chanted in praise of the God of their fathers on that day,
(see Kuinoel, Rosenmueller, Wolf, &c.) and which was so peculiarly applicable to him who
now “came in the name of the Lord,” to honor and to bless his people. (Psalm cxviii. 26.)

The descent of the Mount of Olives.――To imagine this scene, with something of the
force of reality, it must be remembered that the Mount of Olives, so often mentioned in the
scenes of Christ’s life, rose on the eastern side of Jerusalem beyond the valley of the
Kedron, whose little stream flowed between this mountain and Mount Moriah, on which the
temple stood. Mount Olivet was much higher than any part of the city within the walls, and
the most commanding and satisfactory view of the holy city which modern travelers and
draughtsmen have been able to present to us in a picture, is that from the more than classic
summit of this mountain. The great northern road passing through Jericho, approaches
Jerusalem on its north-eastern side, and comes directly over the top of Olivet, and as it
mounts the ridge, it brings the holy city in all its glory, directly on the traveler’s view.

Hosanna.――This also is an expression taken from the same festal hymn, (Psalm cxviii.
25,) ‫( הושיעה־נא‬hoshia-na) a pure Hebrew expression, as Drusius shows, and not Syriac,
(See Poole’s Synopsis on Matthew xxi. 9,) but corrupted in the vulgar pronunciation of this
frequently repeated hymn, into Hosanna. The meaning of the Hebrew is “save him” or “be
gracious to him,” that is in connection with the words which follow in the gospel story, “Be
gracious, O Lord, to the son of David.” This is the same Hebrew phrase which, in the psalm
above quoted, (verse 25,) is translated “Save now.” The whole expression was somewhat
like the English “God save the king,” in its import.

Nazareth.――This city, in particular, had an odious name, for the general low character
of its inhabitants. The passage in John i. 46, shows in what estimation this city and its
inhabitants were held, by their own neighbors in Galilee; and the great scorn with which all
Galileans were regarded by the Jews, must have redoubled their contempt of this poor
village, so despised even by the despicable. The consequence was that the Nazarenes
acquired so low a character, that the name became a sort of byword for what was mean and
foolish. (See Kuinoel on Matthew ii. 23, John i. 46. Also Rosenmueller on the former
passage and Bloomfield on the latter.)

Galilee.――In order to appreciate fully, the scorn and suspicion with which the Galileans
were regarded by the citizens of Jerusalem, a complete view of their sectional peculiarities
would be necessary. Such a view will hereafter be given in connection with a passage which
more directly refers to those peculiarities, and more especially requires illustration and
explanation.

the blighting of the fig-tree.


Having thus, by his public and triumphant entrance into
Jerusalem, defied and provoked the spite of the higher orders, while
he secured an attentive hearing from the common people, when he
should wish to teach them,――Jesus retired at evening, for the sake
of quiet and comfort, to the house of his friends, Lazarus, Mary and
Martha, at Bethany, in the suburbs. The next morning, as he was on
his way with his disciples, coming back from this place to Jerusalem,
hungry with the fatigues of his long walk, he came to a fig-tree, near
the path, hoping to find fruit for his refreshment, as it seemed from a
distance flourishing with abundance of leaves, and was then near
the season of bearing. But when he came near, he found nothing but
leaves on it, for it was somewhat backward, and its time of producing
figs was not yet. And Jesus, seizing the opportunity of this
disappointment to impress his disciples with his power, personifying
the tree, denounced destruction against it. “May no man eat fruit of
thee hereafter, forever.” And his disciples heard it. They returned to
Bethany, as usual, that evening, to pass the night,――but as they
passed, probably after dark, they took no notice of the fig-tree. But
the next morning, as they went back to the city, they saw that it had
dried up from the roots. Simon Peter, always ready to notice the
instances of his Master’s power, called out in surprise to Jesus, to
witness the effect of his malediction upon its object. “Master, behold,
the fig-tree which thou didst curse, is withered away.” Jesus noticing
their amazement at the apparent effect of his words, in so small a
matter, took occasion to turn their attention to other and higher
objects of faith, on which they might exert their zeal in a spirit, not of
withering denunciation and destroying wrath, such as they had seen
so tremendously efficient in this case, but in the spirit of love and
forgiveness, as well as of the holy energy that could overthrow and
overcome difficulties, not less than to uproot Mount Olivet from its
everlasting base and hurl it into the sea.

the discussions with the sectaries.

The disciples steadily remained the diligent and constant


attendants of their heavenly teacher, in his long and frequent
seasons of instruction in the temple, where he boldly met the often
renewed attacks of his various adversaries, whether Herodians,
scribes, Pharisees or Sadducees, and in spite of their long-trained
subtleties, beat them out and out, with the very weapons at which
they thought themselves so handy. The display of genius, of taste, of
learning, of ready and sarcastic wit, and of heart-searching
acuteness, was so amazing and super-human, that these few days
of open discussion established his divinely intellectual superiority
over all the elaborate science of his accomplished opponents, and at
the same time secured the fulfilment of his destiny, by the spite and
hatred which their repeated public defeats excited in them. Imagine
their rage. Exposed thus before the people, by whom they had
hitherto been regarded as the sole depositaries of learning, and
adored as the fountains of right, they saw all their honors and power,
to which they had devoted the intense study of their whole lives,
snatched coolly and easily from them, by a nameless, untaught
pretender, who was able to hold them up, baffled and disgraced, for
the amusement of the jeering multitude. Here was ground enough for
hatred;――the hatred of conceited and intolerant false learning,
against the discerning soul that had stripped and humbled it;――the
hatred of confident ambition against the heroic energy which had
discomfited it, and was doing much to free a long enslaved people
from the yoke which formal hypocrisy and empty parade had long
laid on them. And again, the intolerable thought that all this heavy
disgrace had been brought on the learned body of Judaism by a
Galilean! a mere carpenter of the lowest orders, who had come up to
Jerusalem followed by a select train of rude fishermen and outcast
publicans;――and who, not being able to command a single night’s
lodging in the city, was in the habit of boarding and lodging in a paltry
suburb, on the charity of some personal friends, from which place he
quietly walked in for the distance of two miles every morning, to
triumph over the palace-lodged heads of the Jewish faith. From such
a man, thus humbly and even pitiably circumstanced, such an
invasion and overthrow could not be endured; and his ruin was
rendered doubly easy by his very insignificance, which now
constituted the chief disgrace of their defeat. Never was cause more
closely followed by its effect, than this insulted dignity was by its
cruel vengeance.

the prophecy of the temple’s ruin.

In preparing his disciples for the great events which were to take
place in a few years, and which were to have a great influence on
their labors, Jesus foretold to them the destruction of the temple. As
he was passing out through the mighty gates of the temple on some
occasion with his disciples, one of them, admiring the gorgeous
beauty of the architecture and the materials, with all the devotion of a
Jew now visiting it for the first time, said to him, “Master, see! what
stones and what buildings!” To him, Jesus replied with the awful
prophecy, most shocking to the national pride and religious
associations of every Israelite,――that ere long, upon that glorious
pile should fall a ruin so complete, that not one of those splendid
stones should be left upon another. These words must have made a
strong impression of wonder on all who heard them; but no farther
details of the prophecy were given to the disciples at large. Not long
afterwards, however, as he sat musingly by himself, in his favorite
retirement, half-way up the Mount of Olives, over against the temple,
the four most loved and honored of the twelve, Peter, James, John
and Andrew, came to him, and asked him privately, to tell them when
these things should be, and by what omen they should know the
approach of the great and woful ruin. Sitting there, they had a full
view of the enormous pile which rose in immense masses very near
them, on the verge of mount Moriah, and was even terraced up, from
the side of the slope, presenting a vast wall, rising from the depths of
the deep ravine of Kedron, which separated the temple from mount
Olivet, where they were. It was morning when the conversation took
place, as we may fairly guess, for this spot lay on the daily walk to
Bethany, where he lodged;――the broad walls, high towers, and
pillars of the temple, were doubtless illuminated by the full splendors
of the morning sun of Palestine; for Olivet was directly east of
Jerusalem, and as they sat looking westward towards the temple,
with the sun behind them, the rays, leaving their faces in the shade,
would shine full and bright on all which crowned the highth beyond. It
was at such a time, as the Jewish historian assures us, that the
temple was seen in its fullest grandeur and sublimity; for the light,
falling on the vast roofs, which were sheeted and spiked with pure
gold, brightly polished, and upon the turrets and pinnacles which
glittered with the same precious metal, was reflected to the eye of
the gazer with an insupportable brilliancy, from the million bright
surfaces and shining points which covered it. Here, then, sat Jesus
and his four adoring chosen ones, with this splendid sight before
them crowning the mountain, now made doubly dazzling by contrast
with the deep gloom of the dark glen below, which separated them
from it. There it was, that, with all this brightness and glory and
beauty before them, Jesus solemnly foretold in detail the awful, total
ruin which was to sweep it all away, within the short lives of those
who heard him. Well might such words sink deep into their
hearts,――words coming from lips whose perfect and divine truth
they could not doubt, though the things now foretold must have gone
wofully against all the dreams of glory, in which they had made that
sacred pile the scene of the future triumphs of the faith and followers
of Christ. This sublime prophecy, which need not here be repeated
or descanted upon, is given at great length by all the first three
evangelists, and is found in Matthew xxiv. Mark xiii. and Luke xxi.

The view of the temple.――I can find no description by any writer, ancient or modern,
which gives so clear an account of the original shape of Mount Moriah, and of the
modifications it underwent to fit it to support the temple, as that given by Josephus. (Jewish
War, book V. chapter v.) In speaking of the original founding of the temple by Solomon,
(Antiquities book VIII. chapter iii. section 2,) he says, “The king laid the foundations of the
temple in the very depths, (at the bottom of the descent,) using stones of a firm structure,
and able to hold out against the attacks of time, so that growing into a union, as it were, with
the ground, they might be the basis and support of the pile that was to be reared above, and
through their strength below, easily bear the vast mass of the great superstructure, and the
immense weight of ornament also; for the weight of those things which were contrived for
beauty and magnificence was not less than that of the materials which contributed to the
highth and lateral dimension.” In the full description which he afterwards gives in the place
first quoted, of the later temple as perfected by Herod, which is the building to which the
account in the text refers, he enters more fully into the mode of shaping the ground to the
temple. “The temple was founded upon a steep hill, but in the first beginning of the structure
there was scarcely flat ground enough on the top for the sanctuary and the altar, for it was
abrupt and precipitous all around. And king Solomon, when he built the sanctuary, having
walled it out on the eastern side, (εκτειχισαντος, that is, ‘having built out a wall on that side’
for a terrace,) then reared upon the terraced earth a colonnade; but on the other sides the
sanctuary was naked,――(that is, the wall was unsupported and unornamented by
colonnades as it was on the east.) But in the course of ages, the people all the while
beating down the terraced earth with their footsteps, the hill thus growing flat, was made
broader on the top; and having taken down the wall on the north, they gained considerable
ground which was afterwards inclosed within the outer court of the temple. Finally, having
walled the hill entirely around with three terraces, and having advanced the work far beyond
any hope that could have been reasonably entertained at first, spending on it long ages,
and all the sacred treasures accumulated from the offerings sent to God from the ends of
the world, they reared around it, both the upper courts and the lower temple, walling the
latter up, in the lowest part, from a depth of three hundred cubits, (450 feet,) and in some
places more. And yet the whole depth of the foundations did not show itself, because they
had greatly filled up the ravines, with a view to bring them to a level with the streets of the
city. The stones of this work were of the size of forty cubits, (60 feet,) for the profusion of
means and the lavish zeal of the people advanced the improvements of the temple beyond
account; and a perfection far above all hope was thus attained by perseverance and time.

“And well worthy of these foundations were the works which stood upon them. For all the
colonnades were double, consisting of pillars twenty-five cubits (40 feet) in highth, each of a
single stone of the whitest marble, and were roofed with fretwork of cedar. The natural
beauty of these, their high polish and exquisite proportion, presented a most glorious show;
but their surface was not marked by the superfluous embellishments of painting and
carving. The colonnades were thirty cubits broad, (that is, forty-five feet from the front of the
columns to the wall behind them;) while their whole circuit embraced a range of six stadia,
(more than three-quarters of a mile!) including the castle of Antonia. And the whole
hypethrum (ὑπαιθρον, the floor of the courts or inclosures of the temple, which was exposed
to the open air, there being no roof above it) was variegated by the stones of all colors with
which it was laid,” (making a Mosaic pavement.) Section 1.

“The outside of the temple too, lacked nothing that could strike or dazzle the mind and
eye. For it was on all sides overlaid with massy plates of gold, so that in the first light of the
rising sun, it shot forth a most fiery splendor, which turned away the eyes of those
who compelled themselves (mid. βιαζομενους) to gaze on it, as from the rays of the sun
itself. To strangers, moreover, who were coming towards it, it shone from afar like a
complete mountain of snow: for where it was not covered with gold it was most dazzlingly
white, and above on the roof it had golden spikes, sharpened to keep the birds from lighting
on it. And some of the stones of the building were forty-five cubits long, five high, and six
broad;”――(or sixty-seven feet long, seven and a half high, and nine broad.) Section 6.

“The Antonia was placed at the angle made by the meeting of two colonnades of the
outer temple, the western and the northern. It was built upon a rock, fifty cubits high, and
precipitous on all sides. It was the work of king Herod, in which, most of all, he showed
himself a man of exalted conceptions.” Section 8.

In speaking of Solomon’s foundation, he also says, (Antiquities book VIII. chapter iii.
section 9,)

“But he made the outside of the temple wonderful beyond account, both in description
and to sight. For having piled up huge terraces, from which, on account of their immense
depth, it was hardly possible to look down, and reared them to the highth of four hundred
cubits, (six hundred feet!) he made them on the same level with the hill’s top on which the
shrine (ναος) was built, and thus the open floor of the temple (ἱερον, or the outer court’s
inclosure) was level with the shrine.”

I have drawn thus largely from the rich descriptions of this noble and faithful describer of
the old glories of the Holy Land, because this very literal translation gives the exact naked
detail of the temple’s aspect, in language as gorgeous as the most high-wrought in which it
could be presented in a mere fancy picture of the same scene; and because it will prove
that my conception of its glory, as it appeared to Christ and the four disciples who “sat over
against it upon the Mount of Olives,” is not overdrawn, since it is thus supported by the
blameless and invaluable testimony of him who saw all this splendor in its most splendid
day, and afterwards in its unequaled beauty and with all its polished gold and marble,
shining and sinking amid the flames, which swept it utterly away from his saddening eyes
forever, to a ruin the most absolute and irretrievable that ever fell upon the works of man.

This was the temple on which the sons of Jonah and Zebedee gazed, with the awful
denunciation of its utter ruin falling from their Lord’s lips, and such was the desolation to
which those terrible words devoted it. This full description of its location shows the manner
in which its terraced foundations descended with their vast fronts, six hundred feet into the
valley of Kedron, over which they looked. To give as clear an idea of the place where they
sat, and its relations to the rest of the scene, I extract from Conder’s Modern Traveler the
following description of Mount Olivet.

“The Mount of Olives forms part of a ridge of limestone hills, extending to the north and
the south-west. Pococke describes it as having four summits. On the lowest and most
northerly of these, which, he tells us, is called Sulman Tashy, the stone of Solomon, there is
a large domed sepulcher, and several other Mohammedan tombs. The ascent to this point,
which is to the north-east of the city, he describes as very gradual, through pleasant corn-
fields planted with olive-trees. The second summit is that which overlooks the city: the path
to it rises from the ruined gardens of Gethsemane, which occupy part of the valley. About
half way up the ascent is a ruined monastery, built, as the monks tell us, on the spot where
the Savior wept over Jerusalem. From this point the spectator enjoys, perhaps, the best
view of the Holy City. (Here Jesus sat, in our scene.)

“The valley of Jehoshaphat, which lies between this mountain and the hills on which
Jerusalem is built, is still used as a burial-place by the modern Jews, as it was by their
ancestors. It is, generally speaking, a rocky flat, with a few patches of earth here and there,
about half a mile in breadth from the Kedron to the foot of Mount Olivet, and nearly of the
same length from Siloa to the garden of Gethsemane. The Jews have a tradition, evidently
founded on taking literally the passage Joel iii. 12, that this narrow valley will be the scene
of the final judgment. The prophet Jeremiah evidently refers to the same valley under the
name of the valley of the Son of Hinnom, or the valley of Tophet, the situation being clearly
marked as being by the entry of the east gate. (Jeremiah xix. 2, 6.) Pococke places the
valley of Hinnom to the south of Jerusalem, but thinks it might include part of that to the
east. It formed part of the bounds between the tribes of Benjamin and Judah, (Joshua xv. 8.
xviii. 16,) but the description is somewhat obscure.” [Modern Traveler Palestine, pp. 168,
172.]
MOUNT MORIAH.

the last supper.

Meanwhile the offended and provoked dignitaries of Judaism were


fast making arrangements to crush the daring innovator, who had
done so much to bring their learning and their power into contempt.
Some of the most fiery spirits among them, were for defying all risks,
by seizing the Nazarene openly, in the midst of his audacious
denunciations of the higher orders; and the attempt was made to
execute this act of arbitrary power; but the mere hirelings sent upon
the errand, were too much awed by the unequaled majesty of the
man, and by the strong attachment of the people to him, to be willing
to execute their commission. But there were old heads among them,
that could contrive safer and surer ways of meeting the evil. By them
it was finally determined to seize Jesus when alone or unattended by
the throngs which usually encompassed him,――to hurry him at
once secretly through the forms of law necessary for his
commitment, and then to put him immediately into the hands of the
Roman governor, as a condemned rioter and rebel, who would be
obliged to order his execution in such a way as that no popular
excitement would rescue the victim from the grasp of the soldiery.
This was the plan which they were now arranging, and which they
were prepared to execute before the close of the passover, if they
could get intelligence of his motions. These fatal schemes of hate
could not have been unknown to Jesus; yet the knowledge of them
made no difference in his bold devotion to the cause for which he
came into the world. Anxious to improve the few fast fleeting hours
that remained before the time of his sufferings should come on, and
desirous to join as a Jew in this great national festival, by keeping it
in form with his disciples, he directed his two most confidential
apostles, Peter and John, to get ready the entertainment for them in
the city, by an arrangement made with a man already expecting to
receive them. This commission they faithfully executed, and Jesus
accordingly ate with his disciples the feast of the first day of the
passover, in Jerusalem, with those who sought his life so near him.
After the supper was over, he determined to use the brief remnant of
time for the purpose of uprooting that low feeling of jealous ambition
which had already made so much trouble among them, in their
anxious discussions as to who should be accounted the greatest,
and should rank as the ruler of the twelve. To impress the right view
upon their minds most effectually, he chose the oriental mode of a
ceremony which should strike their senses, and thus secure a regard
and remembrance for his words which they might fail in attaining if
they were delivered in the simple manner of trite and oft spoken oral
truisms. He therefore rose after supper, and leaving his place at the
head of the table, he laid aside his upper garments, which, though
appropriate and becoming him as a teacher in his hours of public
instruction, or social communion, were yet inconvenient in any active
exertion which needed the free use of the limbs. Being thus
disrobed, he took the position and character of a menial upon him,
and girding himself with a towel, he poured water into a basin and
began to wash the disciples’ feet in it, wiping them with his towel. He
accordingly comes to Simon Peter, in the discharge of his servile
office; but Peter, whose ideas of the majesty and ripening honors of
his Master were shocked at this extraordinary action, positively
refused to be even the passive instrument of such an indignity to one
so great and good,――first inquiring “Lord, dost thou wash my feet?”
Jesus in answer said to him, “What I do, thou knowest not now, but
thou shalt know hereafter.” That is, “this apparently degrading act
has a hidden, useful meaning, at this moment beyond your
comprehension, but which you will learn in due time.” Peter,
however, notwithstanding this plain and decided expression of
Christ’s wise determination to go through this painful ceremony, for
the instruction of those who so unwillingly submitted to see him thus
degraded,――still led on by the fiery ardor of his own headlong
genius,――manfully persisted in his refusal, and expressed himself
in the most positive terms possible, saying to Jesus, “Thou shalt
never wash my feet.” Jesus answered, “If I wash thee not, thou hast
no part with me.” This solemn remonstrance had the effect of
checking Peter’s too forward reverence, and in a tone of deeper
submission to the wise will of his Master, he yielded, replying
however, “Lord, wash not my feet only, but also my hands and my
head.” Since so low an office was to be performed by one so
venerated, he would not have the favor of his blessed touch confined
to the baser limbs, but desired that the nobler parts of the body
should share in the holy ablution. But the high purpose of Jesus
could not accommodate itself to the whims of his zealous disciple;
for his very object was to take the humblest attitude before them, by
performing those personal offices which were usually committed to
slaves. He therefore told Peter, “He that is washed needs not save to
wash his feet, but is clean in every part;”――a very familiar and
expressive illustration, alluding to the circumstance that those who
have been to a bath and there washed themselves, will on their
return find themselves wholly clean, except such dust as may cling
to their feet as they have passed through the streets on their return.
And any one may feel the force of the beautiful figure, who has ever
gone into the water for the purposes of cleanliness and refreshment,
on a warm summer’s day in this country, and has found by
experience that after all possible ablution, on coming out and
dressing himself, his wet feet in contact with the ground have
become loaded with dirt which demands new diligence to remove it;
and as all who have tried it know, it requires many ingenious efforts
to return with feet as clean as they came to the washing; and in spite
of all, after the return, an inspection may forcibly illustrate the truth,
that “he that is washed, though he is clean in every part, yet needs to
wash his feet.” Such was the figure with which Jesus expressed to
his simple-minded and unlettered disciples, the important truth, that
since they had been already washed, (baptized by John or himself,)
if that washing had been effectual, they could need the repurification
only of their feet――the cleansing away of such of the world’s
impure thoughts and feelings as had clung to them in their
journeyings through it. So, after he had washed their feet, and had
taken his garments and sat down again, he said to them, “Know ye
what I have done to you? Ye call me Master and Lord; and ye say
well, for so I am. If I then, your Lord and Master, have washed your
feet, ye also ought to wash one another’s feet. For I have given you
this as an example, that ye should do as I have done to you. Truly
the servant is not greater than his lord, neither is he that is sent
greater than him that sent him. If ye know these things, happy are ye
if ye do them.”――A charge so clear and simple, and so full, that it
needs not a word of comment to show any reader the full force of
this touching ceremony.

Shortly after, in the same place and during the same meeting,
Jesus speaking to them of his near departure, affectionately and
sadly said, “Little children, but a little while longer am I with you. Ye
shall seek me; and as I said to the Jews, ‘whither I go, ye cannot
come,’――so now I say to you.” To this Simon Peter soon after
replied by asking him, “Lord whither goest thou?” Jesus answered
him, “Whither I go thou canst not follow me now, but thou shalt follow
me afterwards.” Peter, perhaps beginning to perceive the mournful
meaning of this declaration, replied, still urging, “Lord, why cannot I
follow thee now? I will lay down my life for thy sake.” Jesus
answered, “Wilt thou lay down thy life for my sake? I tell thee
assuredly, the cock shall not crow till thou hast denied me
thrice.”――Soon after, at the same time and place, noticing the
confident assurance of this chief disciple, Jesus again warned him of
his danger and his coming fall. “Simon! Simon! behold, Satan has
desired to have you (all) that he may sift you as wheat; but I have
prayed for thee (especially) that thy faith fail not; and when thou art
converted, strengthen thy brethren.” Never before had higher and
more distinctive favor been conferred on this chief apostle, than by
this sad prophecy of danger, weakness and sin, on which he was to
fall, for a time, to his deep disgrace; but on him alone, when rescued
from ruin by his Master’s peculiar prayers, was to rest the task of
strengthening his brethren. But his Master’s kind warning was for the
present lost on his immovable self-esteem; he repeated his former
assurance of perfect devotion through every danger, “Lord, I am
ready to go with thee into prison and to death.” Where was
affectionate and heroic devotion ever more affectingly and
determinedly expressed? What heart of common man would not
have leaped to meet such love and fidelity? But He, with an eye still
clear and piercing, in spite of the tears with which affection might dim
it, saw through the veil that would have blinded the sharpest human
judgment, and coldly met these protestations of burning zeal with the
chilling prediction again uttered, “I tell thee, Peter, the cock shall not
crow this day, before thou shalt thrice deny that thou knowest me.”
Then making a sudden transition, to hint to them the nature of the
dangers which would soon try their souls, he suddenly reverted to
their former security. “When I sent you forth without purse, or scrip,
or shoes, did ye need any thing?” And they said “Nothing.” Then said
he to them “But now, let him that has a purse, take it, and likewise
his scrip; and let him that has no sword sell his cloak and buy one.”
They had hitherto, in their wanderings, every where found friends to
support and protect them; but now the world was at war with them,
and they must look to their own resources both for supplying their
wants and guarding their lives. His disciples readily apprehending
some need of personal defense, at once bestirred themselves and
mustered what arms they could on the spot, and told him that they
had two swords among them, and of these it appears that one was in
the hands of Peter. It was natural enough that among the disciples
these few arms were found, for they were all Galileans, who, as
Josephus tells us, were very pugnacious in their habits; and even the
followers of Christ, notwithstanding their peaceful calling, had not
entirely laid aside their former weapons of violence, which were the
more needed by them, as the journey from Galilee to Jerusalem was
made very dangerous by robbers, who lay in wait for the defenseless
traveler wherever the nature of the ground favored such an attack.
Of this character was that part of the road between Jerusalem and
Jericho, alluded to in the parable of the wounded traveler and the
good Samaritan,――a region so wild and rocky that it has always
been dangerous, for the same reasons, even to this day; of which a
sad instance occurred but a few years ago, in the case of an eminent
English traveler, who going down from Jerusalem to Jericho, fell
among thieves and was wounded near the same spot mentioned by
Christ, in spite of the defenses with which he was provided. It was in
reference to such dangers as these, that two of his disciples had
provided themselves with hostile weapons, and Peter may have
been instigated to carry his sword into such a peaceful feast, by the
suspicion that the danger from the chief priests, to which Christ had
often alluded, might more particularly threaten them while they were
in the city by themselves, without the safeguard of their numerous
friends in the multitude. The answer of Jesus to this report of their
means of resistance was not in a tone to excite them to the very
zealous use of them. He simply said, “It is enough,” a phrase which
was meant to quiet them, by expressing his little regard for such a
defense as they were able to offer to him, with this contemptible
armament.

Some have conjectured that this washing of feet (page 97) was a usual rite at the
Paschal feast. So Scaliger, Beza, Baronius, Casaubon and other learned men have
thought. (See Poole’s Synopsis, on John xiii. 5.) But Buxtorf has clearly shown the falsity of
their reasons, and Lightfoot has also proved that it was a perfectly unusual thing, and that
there is no passage in all the Rabbinical writings which refers to it as a custom. It is
manifest indeed, to a common reader, that the whole peculiar force of this ablution, in this
instance, consisted in its being an entirely unusual act; and all its beautiful aptness as an
illustration of the meaning of Jesus,――that they should cease their ambitious strife for
precedence,――is lost in making it anything else than a perfectly new and original
ceremony, whose impressiveness mainly consisted in its singularity. Lightfoot also illustrates
the design of Jesus still farther, by several interesting passages from the Talmudists,
showing in what way the ablution would be regarded by his disciples, who like other Jews
would look upon it as a most degraded action, never to be performed except by inferiors to
superiors. These Talmudic authorities declare, that “Among the duties to be performed by
the wife to her husband, this was one,――that she should wash his face, his hands and his
feet.” (Maimonides on the duties of women.) The same office was due from a son to his
father,――from a slave to his master, as his references show; but he says he can find no
precept that a disciple should perform such a duty to his teacher, unless it be included in
this, “The teacher should be more honored by his scholar than a father.”

He also shows that the feet were never washed separately, with any idea of legal
purification,――though the Pharisees washed their hands separately with this view, and the
priests washed their hands and feet both, as a form of purification, but never the feet alone.
And he very justly remarks upon all this testimony, that “the farther this action of Christ
recedes from common custom, the higher its fitness for their instruction,――being
performed not merely for an example but for a precept.” (Lightfoot’s Horae Hebraica in
Gospel of John xiii. 5.)

Laid aside his garments.――The simple dress of the races of western Asia, is always
distinguishable into two parts or sets of garments,――an inner, which covered more or less
of the body, fitting it tightly, but not reaching far over the legs or arms, and consisted either
of a single cloth folded around the loins, or a tunic fastened with a girdle; sometimes also a
covering for the thighs was subjoined, making something like the rudiment of a pair of
breeches. (See Jahn Archaeologia Biblica § 120.) These were the permanent parts of the
dress, and were always required to be kept on the body, by the common rules of decency.
But the second division of the garments, (“superindumenta,” Jahn,) thrown loosely over the
inner ones, might be laid aside, on any occasion, when active exertion required the most
unconstrained motion of the limbs. One of these was a simple oblong, broad piece of cloth,
of various dimensions, but generally about three yards long, and two broad, which was
wrapped around the body like a mantle, the two upper corners being drawn over the
shoulders in front, and the rest hanging down the back, and falling around the front of the
body, without any fastenings but the folding of the upper corners. This garment was called
by the Hebrews ‫ שמלה‬or ‫שלמה‬, (simlah or salmah,) and sometimes ‫( ;בגד‬begedh;)――by the
Greeks, ἱματιον. (himation.) Jahn Archaeologia Biblica. This is the garment which is always
meant by this Greek word in the New Testament, when used in the singular
number,――translated “cloak” in the common English version, as in the passage in the text
above, where Jesus exhorts him that has no sword to sell his cloak and buy one. When this
Greek word occurs in the plural, (ἱματια, himatia,) it is translated “garments,” and it is
noticeable that in most cases where it occurs, the sense actually requires that it should be
understood only of the outer dress, to which I have referred it. As in Matthew xxi. 8, where it
is said that the people spread their garments in the way,――of course only their outer ones,
which were loose and easily thrown off, without indecent exposure. So in Mark xi. 7, 8: Luke
xix. 35. There is no need then, of supposing, as Origen does, that Jesus took off all his
clothes, or was naked, in the modern sense of the term. A variety of other outer garments in
common use both among the early and the later Jews, are described minutely by Jahn in
his Archaeologia Biblica, § 122. I shall have occasion to describe some of these, in
illustration of other passages.

My exegesis on the passage “He that is washed, needs not,” &c. may strike some as
rather bold in its illustration, yet if great authorities are necessary to support the view I have
taken, I can refer at once to a legion of commentators, both ancient and modern, who all
offer the same general explanation, though not exactly the same illustration. Poole’s
Synopsis is rich in references to such. Among these, Vatablus remarks on the need of
washing the feet of one already washed, “scil. viae causa.” Medonachus says of the feet,
“quos calcata terra iterum inquinat.” Hammond says, “he that hath been initiated, and
entered into Christ, &c. is whole clean, and hath no need to be so washed again, all over.
All that is needful to him is the daily ministering of the word and grace of Christ, to cleanse
and wash off the frailties, and imperfections, and lapses of our weak nature, those feet of
the soul.” Grotius says, “Hoc tantum opus ei est, ut ab iis se purget quae ex occasione
nascuntur. Similitudo sumpta ab his qui a balneo nudis pedibus abeunt.” Besides these and
many others largely quoted by Poole, Lampius also (in commentary in Gospel of John) goes
very fully into the same view, and quotes many others in illustration. Wolfius (in Cur.
Philology) gives various illustrations, differing in no important particular, that I can see, from
each other, nor from that of Kuinoel, who calls them “contortas expositiones,” but gives one
which is the same in almost every part, but is more fully illustrated in detail, by reference to
the usage of the ancients, of going to the bath before coming to a feast, which the disciples
no doubt had done, and made themselves clean in all parts except their feet, which had
become dirtied on the way from the bath. This is the same view which Wolf also quotes
approvingly from Elsner. Wetstein is also on this point, as on all others, abundantly rich in
illustrations from classic usage, to which he refers in a great number of quotations from
Lucian, Herodotus, Plato, Terence and Plutarch.

Sift you as wheat.――The word σινιαζω (siniazo) refers to the process of winnowing the
wheat after threshing, rather than sifting in the common application of the term, which is to
the operation of separating the flour from the bran. In oriental agriculture the operation of
winnowing is performed without any machinery, by simply taking up the threshed wheat in a
large shovel, and shaking it in such a way that the grain may fall out into a place prepared
on the ground, while the wind blows away the chaff. The whole operation is well described
in the fragments appended to Taylor’s editions of Calmet’s dictionary, (Hund. i. No. 48, in
Vol. III.) and is there illustrated by a plate. The phrase then, was highly expressive of a
thorough trial of character, or of utter ruin, by violent and overwhelming misfortune, and as
such is often used in the Old Testament. As in Jeremiah xv. 7. “I will fan them with a fan,”
&c. Also in li. 3. In Psalm cxxxix. 2. “Thou winnowest my path,” &c.; compare translation
“Thou compassest my path.” The same figure is effectively used by John the Baptist, in
Matthew iii. 12, and Luke iii. 17.

Galilean pugnacity.――Josephus, who was very familiar with the Galileans by his
military service among them, thus characterizes them. “The Galileans are fighters even from
infancy, and are every where numerous, nor are they capable of fear.” Jewish War, book III.
chapter iii. section 2.

From Jerusalem to Jericho.――The English traveler here referred to, is Sir Frederic
Henniker, who in the year 1820, met with this calamity, which he thus describes in his
travels, pp. 284‒289.

“The route is over hills, rocky, barren and uninteresting; we arrived at a fountain, and
here my two attendants paused to refresh themselves; the day was so hot that I was
anxious to finish the journey, and hurried forwards. A ruined building situated on the summit
of a hill was now within sight, and I urged my horse towards it; the janissary galloped by me,
and making signs for me not to precede him, he rode into and round the building, and then
motioned me to advance. We next came to a hill, through the very apex of which has been
cut a passage, the rocks overhanging it on either side. Quaresmius, (book vi. chapter 2.)
quoting Brocardus, 200 years past, mentions that there is a place horrible to the eye, and
full of danger, called Abdomin, which signifies blood; where he, descending from Jerusalem
to Jericho, fell among thieves. I was in the act of passing through this ditch, when a bullet
whizzed by, close to my head; I saw no one, and had scarcely time to think, when another
was fired some distance in advance. I could yet see no one,――the janissary was beneath
the brow of the hill, in his descent; I looked back, but my servant was not yet within sight. I
looked up, and within a few inches of my head were three muskets, and three men taking
aim at me. Escape or resistance were alike impossible. I got off my horse. Eight men
jumped down from the rocks, and commenced a scramble for me; I observed also a party
running towards Nicholai. At this moment the janissary galloped in among us with his sword
drawn.

“A sudden panic seized the janissary; he cried on the name of the Prophet, and galloped
away. As he passed, I caught at a rope hanging from his saddle. I had hoped to leap upon
his horse, but found myself unable;――my feet were dreadfully lacerated by the honey-
combed rocks――nature would support me no longer――I fell, but still clung to the rope. In
this manner I was drawn some few yards, till, bleeding from my ancle to my shoulder, I
resigned myself to my fate. As soon as I stood up, one of my pursuers took aim at me, but
the other casually advancing between us, prevented his firing; he then ran up, and with his
sword, aimed such a blow as would not have required a second; his companion prevented
its full effect, so that it merely cut my ear in halves, and laid open one side of my face; they
then stripped me naked.

“It was now past mid-day, and burning hot; I bled profusely,――and two vultures, whose
business it is to consume corpses, were hovering over me. I should scarcely have had
strength to resist, had they chosen to attack me. At length we arrived about 3 P. M. at
Jericho.――My servant was unable to lift me to the ground; the janissary was lighting his
pipe, and the soldiers were making preparations to pursue the robbers; not one person
would assist a half-dead Christian. After some minutes a few Arabs came up and placed me
by the side of the horse-pond, just so that I could not dip my finger into the water. This pool
is resorted to by every one in search of water, and that employment falls exclusively upon
females;――they surrounded me, and seemed so earnest in their sorrow, that,
notwithstanding their veils, I almost felt pleasure at my wound. One of them in particular
held her pitcher to my lips, till she was sent away by the Chous;――I called her, she
returned, and was sent away again; and the third time she was turned out of the yard. She
wore a red veil, (the sign of not being married,) and therefore there was something
unpardonable in her attention to any man, especially to a Christian; she however returned
with her mother, and brought me some milk. I believe that Mungo Park, on some dangerous
occasion during his travels, received considerable assistance from the compassionate sex.”

the scenes of gethsemane.

After much more conversation and prayer with his disciples in the
supper-room, and having sung the hymn of praise which usually
concluded the passover feast among the Jews, Jesus went with
them out west of the city, over the brook Kedron, at the foot of the
Olive mount, where there was a garden, called Gethsemane, to
which he had often resorted with his disciples, it being retired as well
as pleasant. While they were on the way, a new occasion happened
of showing Peter’s self-confidence, which Jesus again rebuked with
the prediction that it would too soon fail him. He was telling them all,
that events would soon happen that would overthrow their present
confidence in him, and significantly quoted to them the appropriate
passage in Zechariah xiii. 7. “I will smite the shepherd, and the
sheep shall be scattered.” Peter, glad of a new opportunity to assert
his steadfast adherence to his Master, again assured him that,
though all should be offended, or lose their confidence in him, yet
would not he; but though alone, would always maintain his present
devotion to him. The third time did Jesus reply in the circumstantial
prediction of his near and certain fall. “This day, even this night,
before the cock crow twice, thou shalt deny me thrice.” This repeated
distrustful and reproachful denunciation, became, at last, too much
for Peter’s warm temper; and in a burst of offended zeal, he declared
the more vehemently, “If I should die with thee, I will not deny thee in
any wise.” To this solemn protestation against the thought of
defection, all the other apostles present gave their word of hearty
assent.

VALLEY OF THE BROOK KEDRON

between Jerusalem and the Mount of Olives.


John xviii. 1.

They now reached the garden, and when they had entered it,
Jesus spoke to all the disciples present, except his three chosen
ones, saying, “Sit ye here, while I go and pray yonder.” He retired
accordingly into some recess of the garden, with Peter and the two
sons of Zebedee, James and John; and as soon as he was alone
with them, begun to give utterance to feelings of deep distress and
depression of spirits. Leaving them, with the express injunction to
keep awake and wait for him, he went for a short time still farther,
and there, in secret and awful woe, that wrung from his bowed head
the dark sweat of an unutterable agony, yet in submission to God, he
prayed that the horrible suffering and death to which he had been so
sternly devoted, might not light on him. Returning to the three
appointed watchers, he found them asleep! Even as amid the lonely
majesty of Mount Hermon, human weakness had borne down the
willing spirit in spite of the sublime character of the place and the
persons before them; so here, not the groans of that beloved
suffering Lord, for whom they had just expressed such deep regard,
could keep their sleepy eyes open, when they were thus exhausted
with a long day’s agitating incidents, and were rendered still more
dull and stupid by the chilliness of the evening air, as well as the
lateness of the hour of the night; for it was near ten o’clock. At this
sad instance of the inability of their minds to overcome the frailties of
the body, after all their fine protestations of love and zeal, he mildly
and mournfully remonstrates with Peter in particular, who had been
so far before the rest in expressing a peculiar interest in his Master.
And he said to Peter, “Simon! sleepest thou? What! could ye not
watch with me one hour? Watch ye and pray, lest ye enter into
temptation. The spirit indeed is willing, but the flesh is weak.” Well
might he question thus the constancy of the fiery zeal which had so
lately inspired Peter to those expressions of violent attachment.
What! could not all that warm devotion, that high pride of purpose,
sustain his spirit against the effects of fatigue and cold on his body?
But they had, we may suppose, crept into some shelter from the cold
night air, where they unconsciously forgot themselves. After having
half-roused them with this fruitless appeal, he left them, and again
passed through another dreadful struggle between his human and
divine nature. The same strong entreaty,――the same mournful
submission,――were expressed as before, in that moment of solitary
agony, till again he burst away from the insupportable strife of soul,
and came to see if yet sympathy in his sorrows could keep his
sleepy disciples awake. But no; the gentle rousing he had before
given them had hardly broken their slumbers. For a few moments the
voice of their Master, in tones deep and mournful with sorrow, might
have recalled them to some sense of shame for their heedless
stupidity; and for a short time their wounded pride moved them to an
effort of self-control. A few mutual expostulations in a sleepy tone,
would pass between them;――an effort at conversation perhaps,
about the incidents of the day, and the prospect of coming danger
which their Master seemed to hint;――some wonderings probably,
as to what could thus lead him apart to dark and lonely
devotion;――very likely too, some complaint about the cold;――a
shiver――a sneeze,――then a movement to a warmer attitude, and
a wrapping closer in mantles;――then the conversation languishing,
replies coming slower and duller, the attitude meanwhile declining
from the perpendicular to the horizontal, till at last the most wakeful
waits in vain for an answer to one of his drowsy remarks, and finds
himself speaking to deaf ears; and finally overcome with impatience
at them and himself, he sinks down into his former deep repose, with
a half-murmured reproach to his companions on his lips. In short, as
every one knows who has passed through such efforts, three sleepy
men will hardly keep awake the better for each other’s company; but
so far from it, on the contrary, the force of sympathy will increase the
difficulty, and the very sound of drowsy voices will serve to lull all the
sooner into slumber. In the case of the apostles too, who were
mostly men accustomed to an active life, and who were in the habit
of going to bed as soon as it was night, whenever their business
allowed them to rest, all their modes of life served to hasten the
slumbers of men so little inured to self-control of any kind. These
lengthy reasons may serve to excite some considerate sympathy for
the weakness of the apostles, and may serve as an apology for their
repeated drowsiness on solemn occasions; for a first thought on the
subject might suggest to a common man, the irreverent notion, that
those who could slumber at the transfiguration of the Son of God on
Mount Hermon, and at his agony in Gethsemane, must be very
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like