Python The Complete Manual 1652453990
Python The Complete Manual 1652453990
Code
& create
with
Python!
6
Get started
with
Python 8 Masterclass
Discover the basics of Python
7
Get with
started
Python
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 files 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 file using the command ‘touch’
followed by the filename. Our expert used the command touch
hello_world.py. The final and most important part of setting up the
file is making it executable. This allows us to run code inside the hello_
world.py file. We do this with the command chmod +x hello_world.
py. Now that we have our file 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.
Our Hello World program is very simple, it only needs two lines.
The first line begins with a ‘shebang’ (the symbol #! – also known
10
Get started with Python Getting started
#!/usr/bin/env python2
print(“Hello World”)
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 file
that follows a # character will be
ignored by the interpreter. This List Contains a collection of data in a specific order
is so you can write comments in
your code. Tuple Contains a collection immutable data in a specific
order
12
Get started with Python Getting started
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”)
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” }
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[“first_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[“first_name”],
hello_dict[“last_name”],
hello_dict[“eye_colour”]))
14
Get started with Python Getting started
Indentation in detail
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
[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
#!/usr/bin/env python2
ints = list()
These are used
to keep track
count = 0
of how many
integers we
currently have
17
Getting started Get started with Python
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
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)
#!/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 defined in the scope of the if statement. This means that we
get a very nasty error when we try to access var.
If cont is set to True, then the variable will be created and we can
access it just fine. 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
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 identifiers 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 file describing what the application does, or a part
of the application if it’s made up of multiple files.
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 fix, stick it into Google and you should be a lot
closer to solving your problem. For example, if we Google ‘play mp3
file with python’, the first link takes us to a Stack Overflow 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
Lay the foundations and build your knowledge
Now that you’ve taken the first steps with Python, it’s time
to begin using that knowledge to get coding. In this section,
you’ll find 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 finish 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
Python 2.7:
https://www.python.org/download/
Make web
apps with
releases/2.7/
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 different
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 stuff. 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.
26
Make web apps with Python Introducing Python
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.
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
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
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
31
Introducing Python Build an app for Android with Python
32
Build an app for Android with Python Introducing Python
made it a subclass of FloatLayout can use here to draw each of our different properties that can be
because this special layout is able widget shapes: set, like the pos and size of the
to position and size its children rectangle, and you can check the
in proportion to its own position <Player>: Kivy documentation online for
and size – so no matter where we canvas: all the different possibilities. The
Color:
run it or how much we resize the biggest advantage is that although
rgba: 1, 1, 1, 1
window, it will place all the game Rectangle: we still declare simple canvas
objects appropriately. pos: self.pos instructions, kv language is able
Next we can use Kivy's graphics size: self.size to detect what Kivy properties we
instructions to draw various have referred to and automatically
shapes on our widgets. We'll just <Ball>: track them, so when they are
demonstrate simple rectangles to canvas: updated (the widget moves or is
Color:
show their locations, though there resized) the canvas instructions
rgb: 1, 0.55, 0
are many more advanced options Rectangle: move to follow this!
you might like to investigate. In pos: self.pos
a Python file we can apply any size: self.size Fig 01
instruction by declaring it on the
canvas of any widget, an example <Block>: from kivy.app import App
canvas: from kivy.uix.widget import
of which is shown in Fig. 03.
Color: Widget
This would draw a red rectangle from kivy.uix.floatlayout
rgb: self.colour
with the same position and size # A property we import FloatLayout
as the player at its moment of predefined above from kivy.uix.modalview
instantiation – but this presents a Rectangle: import ModalView
problem, unfortunately, because pos: self.pos
the drawing is static. When we size: self.size __version__ = '0.1' #
Color: Used later during Android
later go on to move the player
rgb: 0.1, 0.1, 0.1 compilation
widget, the red rectangle will
Line:
stay in the same place, while the class BreakoutApp(App):
rectangle:
widget will be invisible when it is [self.x, self.y, pass
in its real position. self.width, self.
We could fix this by keeping height] BreakoutApp().run()
references to our canvas
instructions and repeatedly The canvas declaration is special,
updating their properties to track underneath it we can write any Fig 02
the player, but there's actually an canvas instructions we like. Don't
from kivy.properties
easier way to do all of this - we get confused, canvas is not a
import (ListProperty,
can use the Kivy language we widget and nor are graphics
NumericProperty,
introduced last time. It has a instructions like Line. This is just
special syntax for drawing on a special syntax that is unique to O bje c t Pr o p e r t y,
the widget canvas, which we the canvas. Instructions all have StringProperty)
33
Introducing Python Build an app for Android with Python
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 finished At this point we have also input, they are automatically
the basic graphics of our app! All added the first 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 finish off 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 off
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 'file. or native notifications. 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 different 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 first 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 different ways 0.28, 0.78)])
to add whatever extra behaviour unschedule(self.update)
you like – you could add different 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 finish 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 file 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 fine”
app store of your choice