0% found this document useful (0 votes)
139 views131 pages

RASPBERRY PI A Beginners Concise Guide

This document is a beginner's guide to setting up and using Raspberry Pi, covering its hardware and software components, programming basics, and project development. It emphasizes the affordability and versatility of Raspberry Pi, particularly its compatibility with Python and Linux. The guide includes detailed instructions for installation, usage, and various applications, making it a comprehensive resource for newcomers to programming and electronics.

Uploaded by

Tihomir Mihaylov
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views131 pages

RASPBERRY PI A Beginners Concise Guide

This document is a beginner's guide to setting up and using Raspberry Pi, covering its hardware and software components, programming basics, and project development. It emphasizes the affordability and versatility of Raspberry Pi, particularly its compatibility with Python and Linux. The guide includes detailed instructions for installation, usage, and various applications, making it a comprehensive resource for newcomers to programming and electronics.

Uploaded by

Tihomir Mihaylov
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 131

RASPBERRY PI

A Beginners Concise Guide to Raspberry Pi Setup,


Learning Programming and Developing Innovative
Projects

DUKE
DENTON
Copyright © 2020 Duke Denton

All rights reserved.


It is not legal to reproduce, duplicate, or transmit any part
of this document by either electronic means or in printed
format. Recording of this publication is strictly prohibited

Disclaimer

The information in this book is based on personal


experience and anecdotal evidence. Although the
author has made every attempt to achieve an accuracy
of the information gathered in this book, they make no
representation or warranties concerning the accuracy or
completeness of the contents of this book. Your
circumstances may not be suited to some illustrations in
this book.

The author disclaims any liability arising directly or


indirectly from the use of this book. Readers are
encouraged to seek Medical. Accounting, legal, or
professional help when required.

This guide is for informational purposes only, and the


author does not accept any responsibilities for any
liabilities resulting from the use of this information. While
every attempt has been made to verify the information
provided here, the author cannot assume any
responsibility for errors, inaccuracies or omission.
Table of Contents
INTRODUCTION ..............................................................................
CHAPTER ONE ................................................................................
What is Raspberry Pi? ...................................................................
MERITS OF RASPBERRY PI ..........................................................
A TOUR OF RASPBERRY PI.........................................................
The Raspberry Hardware components ................................
The Raspberry Software Components .................................
SETTING UP RASPBERRY PI FOR THE FIRST TIME......................
CHAPTER TWO ...............................................................................
Taking off ........................................................................................
HOW LINUX DIFFERS FROM OTHER OPERATING SYSTEMS ..
COMMAND PROMPTS USING LINUX AND ITS
APPLICATIONS ............................................................................
CHAPTER THREE .............................................................................
Python Basics .................................................................................
TROUBLESHOOT MENU ..............................................................
CHAPTER FOUR ..............................................................................
An Outlook into Functions ..........................................................
GENERAL CODE SYNTAX OF FUNCTIONS .............................
Component parts of a Function ...........................................
How to Call a Function ...........................................................
How to determine the length of a string .............................
CHAPTER FIVE ................................................................................
Modules Classes and Methods .................................................
Dates and Time Module .........................................................
How to create a class .............................................................
CHAPTER SIX ..................................................................................
Files and the Web ........................................................................
Creating a File...........................................................................
Reading and Writing Binary Data .........................................
CHAPTER SEVEN ............................................................................
Tkinter ..............................................................................................
CHAPTER EIGHT .............................................................................
Games Programming .................................................................
What is Pygame? .....................................................................
CHAPTER NINE...............................................................................
Interfacing with the Hardware..................................................
INTERFACING THE BREADBOARD TO RASPBERRY PI
USING JUMPER WIRES...............................................................
ARDUINO AND RASPBERRY PI .................................................
CHAPTER TEN .................................................................................
Linux Resources ............................................................................
Raspberry pi Resources ...........................................................
Other Programming Languages ...........................................
Applications and Projects .......................................................
CONCLUSION ................................................................................
INTRODUCTION

Python is a simple, easy to learn language similar to written


English. Raspberry pi is a simple single motherboard
computer, portable fast, and easy to use. Now combine
a very easy to learn a language with an easy to use
computer and what you’ll get will be absolute simplicity
that can fit right into your back pocket. There are other
alternatives to the Raspberry pi and other substitute
programming languages out there you can make use of
instead. But here is the thing, none of the other options, for
example, Arduino, gives you simplicity plus computing
power and speed that the Raspberry pi will offer. This book
will take you through the basics, and you’ll do yourself a
great deal of good to improve on them even further after
you are done reading this book.
CHAPTER ONE

What is Raspberry Pi?

Raspberry Pi is an affordable, pocket-sized computer that


plugs conveniently into a screen like a monitor or TV with
a mouse and a standard keyboard. It is the most popular
single-board computer in the market.

MERITS OF RASPBERRY PI
Some questions do pop up when an individual or a
business owner intends to invest a considerable amount
of money in just about anything. Questions like “will the
value be worth the money?”, “what other alternatives
there is?.” When questions like this come to mind, the next
course of action is to think of the various benefits it offers
in the shorter and longer terms.

There are many advantages Raspberry Pi offers, which


anyone willing to buy must consider before buying one.

1. It is suitable for low budget businesses or projects.


2. It can be used by just about anyone with or without
prior coding or programming experience.
3. The default programming language is python (with
Linux OS), which is very easy to understand, unlike
other programming languages.
4. It consumes way less power compared to what a
regular PC will consume. This implies reduced
spending on electricity bills.
5. It has a low carbon footprint.
6. It is very good for experimenting adaptive
technologies.
7. It supports other programming languages too. This
means if you are not a big fan of python
programming language, you can still make use of it
nonetheless using your preferred programming
language.
8. It has many interfaces yet can fit comfortably in
your purse.

A TOUR OF RASPBERRY PI
The Raspberry Pi comes in two variants, namely; Model A
and Model B. The discrepancy between the two models
is the micro USB port. Model B comes with an ethernet
port, which means it consumes more power than its model
A.
To fully understand the purpose for the birth of the
Raspberry Pi, a good understanding of its various
components parts is quintessential.

The Raspberry Hardware components


The Raspberry micro-computer board like any other
computer is made up of the RAM (Read Only Memory),
Processor, GPU (Graphics Programming unit), CPU
(Central Processing Unit), the Ethernet Port, GPIO pins
(Graphics Programming Input/ Output pins), XBee pin out/
socket, UART (Universal Asynchronous Transceiver), power
connector, SD card slot, RCA connector, LED (Light-
emitting Diodes), Bluetooth, Wi-Fi, MIPI DSI (Display Serial
Interface), MIPI CSI (Camera Display Interface), HDMI port
and extension for other external devices through the USB
port.

RAM

The board comes with two memory variants, which are;


250MB and 512MB for early models. The newer versions
now boast of up to 4GB RAM.

PROCESSOR

This unit is responsible for carrying out instructions through


logical operations.
GPU

The GPU component is responsible for all image-related


operations.

THE GPIO PINS

They are general-purpose pins used to interface the


Raspberry pi board to external boards. These pins are
capable of executing I/ O commands from external
electronic circuit boards.

POWER CONNECTOR

The power connector allows for the Raspberry Pi board to


be connected to an external power source.

XBEE PIN OUT/ SOCKET

It is used for wireless communication.

ETHERNET PORT

The Ethernet port provides a means of communication


with additional devices.

SD CARD

This serves as the storage and can be likened to a


computer hard drive of a traditional computer. This is also
where the operating system of the Raspberry pi boots
from.

The Raspberry Software Components


Though Raspbian has been the most popular Linux-based
operating system for the Raspberry pi, there are other
operating systems that are widely used. Here is a bucket
list of them;

Raspbian

This is one of the operating systems of the Raspberry Pi. The


OS is built based on Debian. It is compatible with all the
versions of Raspberry pi, plus it is easy to adapt to as a
beginner.

Ubuntu MATE

The Ubuntu MATE operating system is much simpler and


straight forward. Also, based on Linux, the Ubuntu MATE
OS has a modern feel to it and very much up to date.
However, it is not available for all the versions of Raspberry
pi. It starts from Raspberry 2 upwards.

RetroPie

Based on Raspbian, it is an emulator that allows you to


play old games way back as the ’70s.
DietPi

DietPi runs on an optimized Debian version. Its small size


makes it the lighter compared to Raspberry lite. It is
available for all version of Raspberry Pi models.

Manjaro

It is an uncommon system on Raspberry Pi based on arch


Linux. Simple, cool, light, and super flexible. It also gives
you the freedom to install only what you want to use.

Fyde OS: Chromium OS for Raspberry Pi

The OS can be installed on just about any device,


including Raspberry Pi. Installing the Operating system also
gives you access to Cloud-Based tools available on
chrome OS.

OSMC

This is one of the best media solutions built for the


Raspberry pi based on Debian. It can stream and play just
about any media formats. Easy to install and use.

Windows 10 ARM

With the WDOA deployer, you can easily install windows


10 on your Raspberry Pi. This is achieved by booting ARM
windows 10 from Micro SD card.
Open ELEC

This is developed to use the system and its resources to


access media browsing and playback.

Android

Android is known to run on just about any device, and its


good news; it also runs on Raspberry Pi. This gives the user
the opportunity to access the vast collection of android
apps and games.

SETTING UP RASPBERRY PI FOR THE FIRST TIME


To get Raspberry pi to work, you need to first install an
operating system on it through a micro SD card. NOOBS
(New out of box software) happens to be the installer for
the Raspberry pi OS.

HOW DO YOU GET NOOBS

There are two ways you can get your hands on NOOBS.
One is by buying an SD card with NOOBS pre-installed on
it. The second is to download on the Raspberry pi official
website at https://www.raspberrypi.org/downloads.

How to install NOOBS on SD card


Before you start the installation of NOOBS from your SD
card;

-Make sure the SD card is at least 8GB. 16GB for full


Raspberry pi OS installation.

-The SD card is formatted as FAT.

-Extract the file from the NOOBS zip file.

-You can then copy the file to the formatted SD card for
installation.

-As soon as you boot, the Recovery FAT partition will


automatically be resized to a minimum. A list of operating
systems available for installation will pop up.
CHAPTER TWO

Taking off

At this point, you must have familiarized yourself with the


basics of Raspberry pi ranging from the hardware to the
software components of it. Now, let’s move up a little bit
up to the Linux composition, the desktop, and the web.

LINUX

The Linux operating system probably the best known and


commonly utilized operating system.

It is a software that sits in between the software and the


hardware components of a computer system.

Linux is the operating system of the Raspberry pi by


default.
HOW LINUX DIFFERS FROM OTHER OPERATING
SYSTEMS
Like other operating systems, Linux has a GUI (graphical
user interphase) and the same types of software you may
have come across like video and photo editors, word
processors on Microsoft Windows, MacOS, and so on.
Simply put, if you can operate a computer or any other
electronic device, you sure can operate Linux.

There are, however, major differences between Linux and


other operating systems. Here are some of the reasons

Linux is an open-source software or operating system. This


implies that it is free.

The code used to create the software is open, free, and


accessible to anyone to view, use, and modify-this is
especially for developers.

There are many distribution of Linux, which comes with


different software options. This implies that Linux is super
flexible and easy to customize.

Another with Linux is that users have the freedom to select


the core components they want to use. This is one of the
reasons why the raspberry pi can successfully run on many
operating systems sharing the basic Linux kernel.
Linux is not completely security proof, but more secure
compared to other operating systems such as windows.

It can be used to bring older computer systems back to


life.

Software updates are done effortlessly and much faster


on the Linux operating system.

It enjoys large community support to help you navigate


through any issues you may encounter.

It is very stable compared to other operating systems. In


windows, whenever you uninstall an application, you will
have to reboot. This is not so in Linux.

Linux ensures the privacy of its users and does not collect
user data like other operating systems.

It is good for high performance on various networks and


work stations. It can successfully handle a large number of
users to work simultaneously and handles them smoothly.

It provides large base support for network functionalities.


This implies that, with Linux, you can easily set up server
systems for clients on your computer plus speed of
delivery.
Linux is a very flexible operating system as you can choose
what to install without cut back on performance.

Linux is compatible with just about any file format and can
run any program file you can think of, be it windows or
mac operating systems.

Linux is easy and fast to install compared to other


operating systems.

It also provides high performance as relates to hardware.


All tasks are easily executable even when the hard drive
is almost full.

Linux is memory friendly as it can easily perform multiple


tasks simultaneously without any cut back on its speed
and overall performance.

It also allows for various desktop environments, thereby


making it very easy to use.

USES OF LINUX

There are many uses of Linux. It’s like so many other


operating systems you can find out there.

Here are some of those uses;


Web server

More than 50percent of all websites on the internet run on


an open program called Apache, which in most cases
runs on Linux. So, if you are surfing the internet right now,
the chances that you are Linux is very high.

Networking

Linux is heavily used to run a larger part of the internet.


They are also used to run small and large networks in
homes, offices, and corporations.

Databases

Linux is largely used in database infrastructures for storing


large amounts of information. This is because it is robust,
secure, and robust.

Desktop

Because Linux is super flexible and stable, it has


successfully found its way on our various desktops.

Heavy computing

Linux systems can be meshed to work together for large


datasets testing. This one of the reasons it is used with
supercomputers in weather forecasting, scientific
simulations, and renderings …
Home use

And to be frank, people like you and me can also use


Linux on a day to day basis.

COMMAND PROMPTS USING LINUX AND ITS


APPLICATIONS
The Linux command-line interface is the program that
permits users to type commands in the form of text
instructing the computer system to carry out a specified
task or a group of tasks.

If you are not familiar with the command-line interface,


you can simply search for command prompt on your
desktop lists of applications. Open and run. It’s usually with
a dark background.

Here is a bucket list of basic Linux command you will find


very useful;

1. cd command

This prompt is used to navigate through the Linux files,


folders, or directories.

i. cd.. to move one directory up

ii. cd go straight to home


iii. cd-to move to your previous directory

2. PWD command

This command prompt is used to find the path of the


current directory.

3. Is command

It is used in viewing the contents of a directory

4. cat command

It is one of the most commonly used commands on Linux.


It is used to list the contents of a file sequentially on the
standard output.
CHAPTER THREE

Python Basics

IDLE

The Integrated Development and Learning Environment


are entirely coded in python with a cross-platform
functionality, i.e., it can work on just about any operating
system, be it windows or MacOs. It is composed of two
main windows, which are; the shell window and the editor
window.

IDLE MENU

When you open the IDLE, the first text that you see within
the editor is the version of the IDLE, which is also written
boldly at the top left corner of the application. The various
menus within the app are;

°File
°Edit

°Shell

°Debug

°Options

°Windows

°Help

FILE MENU

This menu contains other sub-menus. Here is a list of them


and their various uses;

New File

Is used to create a new file editing window


Open…

To open a pre-existing file with an open dialog

Recent files

To open a list of recently created files

Open Module…

To open an existing module

Class Browser

This is used to show classes, functions, and methods in the


current editor file

Path browser

A click on this shows the system path directories, modules,


classes, functions, and methods in a tree structure.

Save

This will save a copy of the current windows to the file


associated with it.

Save as…

This will save a copy of the current window with a save as


dialog. The saved file becomes the new associated file for
the window.
Save copy as…

This will save the current window without changing the file
name associated with it.

Print window

This will print the current window to the default printer.

Close

This will close the current window and prompt if contents


are yet to be saved.

Exit

This will close all open windows and quit IDLE.

THE EDIT MENU

Undo

This will undo the last changes done to the current


window. The total number of changes must at no time be
more than 1000.
Redo

This will redo the last undone and change to the current
window

Cut

This will copy the selection to clipboard and delete the


selection.

Copy

This will copy the selection into the clipboard

Paste

This will insert the content of the clipboard into the current
window.

Select all…
Select the entire contents of the current window

Find…

This will open a search dialog with many options

Find again

This will repeat the last search if there is a history of one.

Find selection

This will search for the currently selected if there is one

Find in files…

This will open a file search dialog and display results in a


new window

Replace…

This will open a search and replace the existing if there is


one.

Go to line

This will move the cursor to the start of a line and make it
visible.

Show completions

This opens a list you can scroll, allowing selection of


keywords and attributes
Expand word

This will expand a prefix typed to match a word in the


same window

Show call tip

This will open a small window containing function


parameter hints

Show surrounding parens

This will highlight the surrounding parenthesis

FORMAT MENU
Indent region

This will shift the selected lines to the right by the width of
the indent

Dedent region

This will shift the selected lines to the left by the width of
the indent

Comment out region

This will include double hash in front of selected lines

Uncomment region

Remove the leading hash or the double hash from the


selected lines

Tabify region

This will turn leading stretches of spaces into tabs

Untabify region

This turns all tabs into correct number of spaces

Toggle tabs

This opens dialog to switch in between indenting with


space and tabs.

New indent width


This opens a dialog to change the width of indent

Format paragraph

This will reformat the current blank-line-delimited


paragraph in comment block or multiline string or
selected line in a string.

Strip trailing whitespace

Evacuate trailing space and other whitespace characters


after the last non-whitespace character of a line by
applying str. rstrip to each line, including lines inside
multiline strings. With the exception of Shell windows,
evacuate extra newlines toward the finish of the record.

RUN MENU
Run Module

Do Check Module. In the event that no blunder restarts


the shell to clean the earth, at that point, execute the
module. Yield is shown in the Shell window. Note that yield
requires utilization of print or compose. At the point when
execution is finished, the Shell holds the center and shows
a brief. Now, one may intelligently investigate the
aftereffect of execution. This is like executing a document
with python - I record at an order line.

Run… Modified

Same as Run Module, yet run the module with modified


settings. Order Line Contentions expand sys.argv as
though passed on an order line. The module can be run
in the Shell without restarting.

Check Module

Check the structure of the module as of now open in the


Editor window. In the event that the module has not been
spared, Inert will either provoke the client to spare or
autosave, as chosen in the General tab of the Inactive
Settings discourse. On the off chance that there is a
language structure mistake, the rough area is shown in the
Editorial manager window.
Python Shell

Open or wake up the Python Shell window.

SHELL MENU

View Last Restart

Look over the shell window to the last Shell restart.

Restart Shell

Restart the shell to clean the environment.

Previous History

Cycle through prior orders in history, which coordinates


the current section.

Next History

Cycle through later orders in history, which coordinates


the current section.

Interrupt on Execution

Stop a running program.


TROUBLESHOOT MENU
Go to File/Line

Look at the current line, with the cursor, and the line
above for a filename and line number. Whenever
discovered, open the document if not effectively open,
and show the line. Utilize this to see source lines referenced
in a special case trace back and lines found by Find in
Documents. Additionally, accessible in the setting menu
of the Shell window and output windows.

Debugger (switch)

At the point when enacted, code entered in the Shell or


run from a Supervisor will run under the debugger. In the
Editorial manager, breakpoints can be set with the setting
menu. This element is as yet fragmented and fairly test.

Stack Viewer

Show the stack traceback of the last exemption in a tree


gadget, with access to locals and globals.

Auto-open Stack Viewer

Switch naturally opening the stack watcher on an


unhandled special case.
OPTION MENU

Configure IDLE

Open an arrangement exchange and change


inclinations for the accompanying: textual styles, space,
key bindings, text shading topics, startup windows and
size, extra assistance sources, and augmentations. On
macOS, open the arrangement discourse by choosing
Inclinations in the application menu. For additional
subtleties, see Setting inclinations under Assistance and
inclinations.

Most arrangement alternatives apply to all windows or


every single future window. The choice things beneath just
apply to the dynamic window.
Show/ hide Code Setting

Open a sheet at the highest point of the alter window,


which shows the square setting of the code, which has
looked over the highest point of the window. See Code
Setting in the Altering and Route segment beneath.

Show/ Hide Line Numbers

Open a segment to one side of the alter window, which


shows the quantity of each line of text. The default is off,
which might be changed in the inclinations (see Setting
inclinations).

Zoom/Reestablish Height

Flips the window between typical size and most extreme


height. The underlying size defaults to 40 lines by 80 roasts
except if changed on the General tab of the Arrange
Inactive discourse. The most extreme stature for a screen
is dictated by quickly amplifying a window on the first
occasion when one is zoomed on the screen. Changing
screen settings may discredit the spared stature. This
switch has no impact when a window is expanded.
WINDOW MENU

Records the names of every single open window; select


one to carry it to the closer view (de-iconifying it if
important). For more details on this visit;

https://docs.python.org/3/library/idle.html

Now that we are familiar with the menus in the IDLE let's
dive right into the programming aspect of it.
NUMBERS

Numbers are quintessential in mathematics, so is it in


programming too. Every line of code has one thing or
another to do with numbers or at least at the hardware
level, and the reason is that computers are good at
running numbers.

In this lesson, we’ll be using a Python programming


language to run numbers. Yes! Run numbers like your
calculator.

Here is an example: >>>20*2

In your idle, simply type

>>>print (20*2) and this gives you back

40

Here is another,

Example: >>>10*3/5-2

You can simply hit the enter button, and you get

4.0

Alternatively, you can use the print function

>>>print (10*3/5-2)
And the answer remains the same

i.e., 4.0

This takes us to two keywords;

Integers: The numbers in the calculation

Float: the result of the divided numbers with “.0,”i.e., each


time you divide a number in python, the result is afloat.

Example: >>>25/7

3.5714

The result is a float.

Consider these;

Example: >>>20//3

The result gives 6.0

This is called floor division, i.e., the remainder is ignored.

Example: >>>2**5

This is a way to express power of numbers in python

2**5 means 2 raised to a power of 5

And the result is

32 (an integer)
Example: >>>7%2

This will display the result as

1. The remainder is displayed.


VARIABLES

What is a variable? You can think of a variable like your


father, who happens to represent all of you by registering
your house in his last name, a name you all bear. Now,
whenever that name is mentioned in the community,
they’ll know it’s your family. Like the name your Dad used
in registering your house, which points directly to your
family, a variable point to a particular value or a set of
values stored in the memory. The interpreter then
allocates memory space and takes the decision to store
a particular data type in the reserved memory.

Here are the things to know about variables;

1. You cannot use a reserved word in the python


library as a variable
2. A variable name cannot start with a number
3. You can start a variable with symbols, special
characters or letters
4. Variable names can be in upper or lower case.
5. White space characters are not allowed in naming
a variable.
Example: >>>k=3*5

Here, k is the variable representing the product of two


numbers 3 and 5.

The next is to print

i.e. >>>print (k)

Which gives 15.

Example: >>>k+5/4

Now print the result

>>>print k+5/4

16.25

STRINGS

Letters or a group of letters, numbers, or symbols that are


enclosed in either single or double quotes are called
strings. The variables or elements contained in a string
cannot be changed. Hence, they are immutable.

Keep in mind that strings must now be enclosed in quotes,


be it single or double, or it will return an error. This is one of
the new features of Python 3.

Example: >>>” Hello world.”


This is interpreted and displayed as;

‘Hello, world.’

Example: >>>’ I love python programming language.’

Alternatively, you can use the print function. This means


that the function to be called for print must be in
parenthesis.

Example: >>> print (“Python is my favorite programming


language”)

Python is my favorite programming language

TUPLES

Tuples are considered to be like strings. This is because


they contain the same elements as strings, but they differ
in that they are enclosed in the parenthesis instead of
brackets. Like strings, the values of the variables in tuples
cannot be changed. Hence, they are immutable.

Keep in mind that the values of the variables in the lists


can be changed. Hence, they are mutable.

Example: >>> tuple1= (‘Merlin’, ‘Morgana’, 246, ‘Dublin’,


‘Mowena’)
>>>print (tuple1)

Which displays

(‘Merlin,’ ‘Morgana,’ 246, ‘Dublin,’ ‘Mowena’)

Example: >>>tuple2= (‘Seeker’, ‘Frodo’, ‘Mango’, 1945)

>>>print (tuple1+tuple2)

(‘Merlin,’ ‘Morgana,’ 246, ‘Dublin,’ ‘Mowena,’ ‘Seeker,’


‘Frodo,’ ‘Mango,’ 1945)

Example: >>>tuple1= (‘April’, ’May’, ’June’, 326,


‘December’)

>>>tuple2= (‘January’, ‘February’, ‘April’, ‘May’, 326, 559)

>>>print (tuple1+tuple2)

(‘April,’’ May,’’ June,’ 326, ‘December,’ ‘January,’


‘February,’ ‘April,’ ‘May,’ 326, 559)

Note: some of the variables in the tuple are also found in


tuple2 but the result remains unaltered. This is to re-affirm
the fact that tuples are immutable.
LISTS

Two or more strings combine to form a list. The values of


lists can be modified, concatenated, or cut. It can
contain various data types or the same data types, i.e.,
the data can be homogenous and heterogeneous. Unlike
tuples, they are mutable.

Example: >>> [‘April’, ’May,’’ June,’ 326, ‘December’]

To name lists or a list, you can simply assign names that are
related to their contents.

Examples: >>>vegetables = [‘Lettuce’, ‘Amaranthus’,


‘Cabbage’, ‘Carrot’]

Or you can simply use the list

Example: >>>list1= [‘Lettuce’, ‘Amaranthus’, ‘Cabbage’,


‘Carrot’]

Example: >>>list1= [‘April’, ’May’, ’June’, 326,


‘December’]

>>>list2= [‘January’, ‘February’, ‘April’, ‘May’, 326, 559]

>>>print (list1+list2)
[‘April’, ’May’, ’June’, 326, ‘December’, ‘January’,
‘February’, ‘April’, ‘May’, 326, 559]

Example: >>>print (list1 or list2)

[‘April’, ’May’, ’June’, 326, ‘December’, ‘January’,


‘February’, ‘April’, ‘May’, 326, 559]

[‘April’, ’May’, ’June’, 326, ‘December’]

Example: >>>print (list1 and list2)

[‘January’, ‘February’, ‘April’, ‘May’, 326, 559]

Sets

They are composed of an unordered collection of


datatypes or elements that has no duplicate elements in
the same set. Sets, unlike lists, does have a way of
checking whether or not an element is repeated in the
same set. Hence, they are mutable.

Example: >>>set1= {‘Bread’, ‘Rice’, ‘Egg’, ‘Chicken’,


‘Rice’}

>>>print (set1)
{‘Bread’, ‘Rice,’ ‘Egg,’ ‘Chicken’}

‘Rice’ was duplicated but eventually removed from the


list.

To add elements to the above set

>>>set1.add(‘Fish’)

Frozen sets

These types of sets cannot be changed, i.e., immutable.


This is unlike sets which are normally mutable even when
they contain unalterable elements.

Example:>>>weapons= frozenset ([“Axe,” “Knives,”


Arrow,” “Gun,” “Bomb”])

>>>print (weapons)

{‘Axe’, ‘Knives,’ ‘Arrow,’ ‘Gun,’ ‘Bomb’}

Operations for sets

i. Clear () function

This will clear all elements of the set.


Example:>>> weapons= {“Axe”, “Knives”, Arrow”, “Gun”,
“Bomb”}

>>>weapons.clear()

ii. Difference () function

This will return the difference between elements in a set.

Example: >>>set1= C, ’f’, ’g’}

>>>set2= {‘f’, ‘g’}

>>>print (set1). difference (set2)

{‘e’, ’d’, ’c’}

Alternatively, you can perform the same function as;

>>>set1-set2

{‘e’, ’d’, ’c’}

The output is still the same.

To know the elements in set1 or set2, you can use


set1|set2.

Example:>>>set1|set2

{‘c’, ’d’, ’e’, ’f’, ’g’}


For elements in both set1 and set2, you can use set1&set2

Example:>>>set1&set2

{‘f’, ‘g’}

For unduplicated elements in set1 and set2, use set1^set2

Example:>>> set1^set2

{‘c’, ’d’, ’e’}

iii. Add () function

This method is used to add unalterable elements to a set.

Example:>>>players= {“Messi”, “Pepe”, “Son”}

>>>players.add (“Ronaldo”)

>>>names

{“Messi,” “Pepe,” “Son,” “Ronaldo”}

iv. Discard/Remove () function

You can use the discard function to remove any element


in a set. Alternatively, you can use remove ().

Example:>>>set1= {1,2,3,4,5}

>>>set1.discard (5)
>>>print (set1)

{1,2,3,4}

Note that discard function can only take one argument.


More than one discard will return error.

The good news is you don’t have to write all of them


somewhere or cram them. It can be easily accessible
anytime you want to make use of them. In python 3, once
you start typing, for example, the function “discard,”
before you complete “discard,” a drop-down box pops
up for options to choose from.

All these functions come in handy when trying to


manipulate data and organizing them into orderly files.

Booleans

The output represents two constant values, which can


either be ‘True’ or ‘False.’ The built-in function “bool ()” is
used.

Example:>>>7<9

True

Example:>>>15==19
False

Example:>>>4*2! =10

Note that (!=) signifies ‘not equal’ operator

True

Example:>>>5<=9

True

If Statements

You can use the ‘if’ statements to run your code if


specified conditions are met. If the expression is true, it is
executed. Otherwise, they are not carried out.

Example:>>>if 5>9:

>>>print (“9 greater than 5”)

>>>print (“program ended”)

The output gives

9 greater than 5

program ended

Example: >>> error=9


>>> if error>6:

print ("6")

if error>10:

print ("10")

the output gives

6.

For more complex checks, if statements can be nested,


one inside the other. This implies that the inner if the
statement is part of the outer one.

Example:>>> file=7

>>> if file>3:

print ("3")

3.
Else statements

It follows an ‘if’ statements, and contains code that is


called when the ‘if’ statement is ‘false.

Example:>>>m=7

If m==8:

print (‘yes’)

else:

print (‘no’)

no.

Boolean Logic

This is used to make more complicated conditions for ‘if’


statements that rely on more than one condition.

The Boolean operators in python are ‘and,’ ‘or’ and ‘not.’

And operator

The ‘and’ operator usually takes two statements, and the


results are true if and only if both statements are true.

Example:>>>3==3 and 1==1


True

Example:>>>5==5 and 3==4

False

Example:>>>if (5==5) and (3*3>7)

print (‘true’)

else:

print (‘false’)

true.

Or operator

Like the ‘and’ operator, it also takes two arguments, and


it returns ‘true’ if either or both arguments are true and
‘false’ if both arguments are false.

Example:>>>4==4 or 5==5

True

Example:>>>1==1 or 7==8

True

Example:>>>2+1>1 or 2*3<5
False

Example:>>> age=17

>>> fee=1000

>>>if age >18 or fee>500

>>>print (“Qualified”)

Boolean not

Not takes only one argument and inverts it. i.e., ‘not true’
is false, and ‘not false’ is true.

Example:>>>not 1==1

False

Example:>>>not 5<4

True

LOOP

There are two types of loops in python. They are ‘while’


and ‘for’ loops.
While Loop

They are used to execute a block of statements or


arguments continuously until certain conditions are met.
The block of code is executed continuously as long as the
condition holds. Once it becomes false, the next block of
code is executed.

Example:>>> i=2

>>> while i<=4:

print (i)

i=i+1

print ('finished')

finished

finished

Finished.
For Loops

They are used for iterating each element in a list, string,


tuple, or a dictionary.

Example: >>>num= [1,2,3,4]

>>> for n in num:

print (n)

4.

Simulating Dice

To further build on what you’ve learned so far, here is an


example of a rolling die program in python.

>>>import random

>>>while true:
rolled_num = random.randint(1,6)

print ("the dice rolled, and you have: "rolled_num)

input ("Press any key to roll again")

The first line of code was used to import library of random


numbers

Import random

The random numbers are generated using the randint ()


library function. In this case the numbers range between
1 and 6.

If you run this code, the dice will keep rolling until it
encounters an error and stops eventually.
CHAPTER FOUR

An Outlook into Functions

By now, you should be familiar with functions, at least at


the most basic level. Let’s refresh our memories a little bit.
You can define a function as a group of statements that
performs a specific task. One of the good things with a
function is that it helps you break down your code into
smaller and simple pieces easy to put together. This you
can refer to as block, which not only helps you to avoid
writing a line of code over and over again but also ensure
code recycling.

Let’s start with the print function.

Example :>>> print (“Mangoes”)

Which will display

Mangoes as output.
Here is another example;

Example :>>> print (‘I love python programming


Language’)

I love python programming Language.

DEFINING FUNCTIONS

Functions are defined using the abbreviated keyword


“def”. The general code syntax can be written as;

def function_name ():

GENERAL CODE SYNTAX OF FUNCTIONS


def function_name (parameter or argument list):

“ “ “docstring” “ “

Statement(s)

Component parts of a Function


i. The function keyword “def” that marks the
beginning of the function header
ii. Parameters which is where function values are
incorporated.
iii. A colon (:) which indicates the termination of the
function header
iv. Python statements that constitute the body of
the functions
v. A return statement in case you decide to
recycle code.

How to Call a Function


Once a function has been defined, you can easily call it
from another function or program.

Example: >>> def greet (name):

“““

This function will greet the named person in a parameter

“““

print (“Good morning, “+name.” “How are you


doing today?”)

Good morning Leonard. How are you doing today?

Docstrings

The first thing that comes immediately after the function


header is docstring. It explains what a function does.
Example: def greet (name):
“““

This function will greet the named person in a parameter

“““

print (“Good morning, “+name.” “How are you


doing today?”)

Return statement

Statements can have expression(s) that gets evaluated,


and the value returned, and it can have one or more
returns depending on the line of code you are running.

Example: >>> def meters (L_in_centimeters):

“”” this will return the length in centimeters”””

return (l_in_centimeters/100)

for L in (120,332,145,270,225):

print (l, ": ", meters (l))

The output should look like this:

Meters Centimeters

120: 0.12

332: 0.332

145: 0.145
270: 0.270

225: 0.225

Functions can be defined in terms of;

*Keyword arguments

*Default arguments values

*Arbitrary arguments lists

Keyword Arguments

The keyword arguments can be used to call functions.

Example: >>> def printdata (age, state):

"This prints the data into this function"

print ("age: ", age)

print ("state: ", state)

printdata (age="45", state="Kansas")

return

Default Argument values

They are commonly used to call a function once.

Example: >>>def print data (height, eyes = Brown):

“This will print this data into the function.”


print (“ height: “height)

print (“eyes: “eyes)

print data (height= 6ft)

return

Height: 6ft

Eyes: Brown

Arbitrary Argument Lists

You can call this function if it involves a number of


arguments. You can also keywords parameters to call
functions.

The code syntax is usually in the form;

>>>def functionname ([formal_args,]*var_args_tuple):

STRING THEORY

You should be familiar with the basics of strings. Let’s


quickly have a refresh on that;

I bet you have come across the single, double, or even


triple quotes in the course of these lessons so far. Now
that’s what we call string in python programming
language.

Here is a quick one to grab;


Example: >>> (“Python is an awesome programming
language”)

‘Python is an awesome programming language.’

Alternatively, you can also print;

Example: >>> print (“Python is an awesome programming


language”)

Python is an awesome programming


language.

Escaping Quotes

This can simply be achieved using the backslash symbol \

Example: >>>print (‘I won\’t be there today’)

I won’t be there today

Concatenating strings

You can easily and swiftly join strings by making use of the
addition sign (+) and repeat the addition using the asterisk
sign (*).

Example: >>>str1=”Mango”
‘Mango’

>>>str2=”es”

‘es’

>>>str1+str2

‘Mangoes’

In a more simple way, you can put this way

Example: >>> “Hydro” + “Quinone”

Hydroquinone

Example: >>> 2* “Chloro”+ “Carbons”

'ChloroChloroCarbons'

2* means the first indent will be repeated twice.

Creating New strings

You can make new strings or data from old ones. Since
strings are immutable, you cannot change them.
However, you can manipulate the procedures in
executing them.

Example: >>>str1=”sky”

‘sky’

Str2=” fall”
‘fall’

Str1+str2

‘skyfall’

Indexing strings

Indices starting from 0 can be applied to strings. Reverse


indexing can also be applied.

Slicing strings

You can simply create new strings by slicing through the


old ones or anyone for that matter.

Example :>>> >>> str1="charger"

>>> str1 [2]

'a'

Example: >>>str1=”charger”

>>>str1[3]

‘r’

Example: >>>str1 =”Abacus”

>>>str1 [1:3]

‘ba’
Keep in mind while writing your code that python
interpreter will return an error if you enter a non-existent
index.

Example: >>> str1 =”Abacus”

Str1[9]

The output should look like this;

Traceback (most recent call last):

File "<pyshell#36>", line 1, in <module>

str1 [9]

IndexError: string index out of range.

Example: >>>string2=”Apparatus”

>>>str2 [2:4]

‘pa’

Example: >>>str2 [1:]

'pparatus'
If you aim to get the first indexed value up to a specified
index, you can simply create your statement this way.

Example: >>>str2 [:5]

'Appar'

How to determine the length of a string


To determine the length of a string is not quite hard. This
can be achieved by using the key function “len ().” This
aspect is key in manipulating your indexes.

Example: >>>str1=”Samuel”

len (str1)

Example: >>>myAddress =”Maddison Street”

>>>len (myAddress)

14.

HANGMAN

Hangman is a word guessing game that can be played


by at least two players. In this game, a pen and paper is
used. When a player draws a line, the other player try to
guess the letter it corresponds to until all the letters of the
secret word(s) is completely guessed, if you happened to
guess the wrong letter, you’ll lose a life at a time until you
have none left. This game seems to be interesting, right!
So, let’s write a program for it in python.

import random, sys

from typing import List

# TODO try to load these from a text file

WORD_LIST = [

"alpine", "yellow", "family", "screen", "bamboo", "fruit",


"desk", "chair",

"lap", "snake", "fish", "nylon"

GUESS_WORD = []

SECRET_WORD = random.choice(WORD_LIST) # lets


randomize single word from the list

LENGTH_WORD = len(SECRET_WORD)

ALPHABET = "abcdefghijklmnopqrstuvwxyz"
letter_storage = []

# Utility functions

def print_word_to_guess(letters: List) -> None:

"""Utility function to print the current word to guess"""

print("Word to guess: {0}".format(" ".join(letters)))

def print_guesses_taken(current: int, total: int) -> None:

"""Prints how many chances the player has used"""

print("You are on guess {0}/{1}.".format(current, total))

# Game functions

def beginning() -> None:

"""Starts the game"""

print("Hello Mate!\n")
while True:

name = input("Please enter Your name\n").strip()

if name == '':

print("That's not allowed! No blank lines")

else:

break

def ask_user_to_play() -> None:

"""Ask user if they want to play"""

print("Let's get started!\n")

while True:

gameChoice = input("Would You?\n").upper()

if gameChoice == "YES" or gameChoice == "Y":

break

elif gameChoice == "NO" or gameChoice == "N":

sys.exit("That's not right! Have a good one")

else:
print("kindly Answer Yes or No")

continue

def prepare_secret_word() -> None:

"""Prepare secret word and inform user of it"""

for character in SECRET_WORD: # printing blanks for


each letter in secret word

GUESS_WORD.append("-")

print("Ok, so the word You need to guess has",


LENGTH_WORD, "characters")

print ("Be aware that You can enter only 1 letter from a-
z\n\n")

print_word_to_guess(GUESS_WORD)

def guessing() -> None:

"""

Main game loop to have user guess letters


and inform them of the results

"""

guess_taken = 1

MAX_GUESS = 10

print_guesses_taken (guess_taken, MAX_GUESS)

while guess_taken < MAX_GUESS:

guess = input("Pick a letter\n").lower()

if not guess in ALPHABET: #checking input

print("Enter a letter from a-z ALPHABET")

elif guess in letter_storage: #checking if letter has


been already used

print("You have already guessed that letter!")

else:

letter_storage.append(guess)

if guess in SECRET_WORD:

print("That's correctly!")

for i in range(0, LENGTH_WORD):


if SECRET_WORD[i] == guess:

GUESS_WORD[i] = guess

print_word_to_guess (GUESS_WORD)

print_guesses_taken (guess_taken, MAX_GUESS)

if not '-' in GUESS_WORD:

print ("Congratulations you won!")

print ("Game Over!")

break

else:

print ("The letter does not match any in the word.


Try Again!")

guess_taken += 1

print_guesses_taken (guess_taken, MAX_GUESS)

if guess_taken == 10:

print (" Sorry Buddy, You lost :<! The secret word
was {0}".format (SECRET_WORD))

Keep in mind that python interpreter will ignore the


hashed statements because they are comments. They
are included to
DICTIONARIES

A dictionary is simply a group of items or elements that are


unarranged, mutable and indexed. They are usually
written with curly brackets with keys and values to them.

Example:

# Changing and adding Dictionary Elements

>>>my_dict = {'name': 'Pablo', 'age': 65}

# update value

my_dict ['age'] = 66

#Output: {'age': 66, 'name': 'Pablo'}

>>>print (my_dict)

# add item

my_dict ['address'] = 'Efijuiro'

# Output: {'address': 'Efijuiro', 'age': 66, 'name': 'Pablo'}

print (my_dict)

Python dictionaries are quintessential in the creation and


execution of correct syntax and statements.
Here are some of the keywords to keep in mind regarding
dictionaries and their various meanings;

Maps

Python 3 dictionaries are different in some ways to tha3t


of python 2 in that they have maps (something they have
in common with a list) whose values you ca1n gain access
to if and only if you have the unique key corresponding to
each of the maps. Think of a map as your smartphone
whose contents you can only get access to when you
have the password. The good news about them is that
you can store them and get them later on when you need
them.

Example:

>>>mygirlfriends= {“Jane”:21, “Debby”:23, “Loveth”: 19,


“Keith: 25}

>>>print (mygirlfriends)

{'Jane': 21, 'Debby': 23, 'Loveth': 19, 'Keith': 25}

Since they can be modified, you can add elements to


them if you want to.

Example:

>>>myfamily= {“Mother”:54, “Father”: 62, “Sister”: 17}


>>>print (myfamily)

{'Mother': 54, 'Father': 62, 'Sister': 17}

You can simply create dictionaries directly from key: value


Pairs

Example:

>>> dict ([(“Mother”,54), (“Father”, 62), (“Sister”,17)])

{'Mother': 54, 'Father': 62, 'Sister': 17}

Creating an empty Dictionary

You can simply create empty dictionaries by using two


empty curly brackets {} and unemptied them by inserting
values.

Deleting an entry from a dictionary

You can remove a key: value pair from a dictionary using


the “del” function. Let’s use the previous example
myfamily;

Example:

>>> myfamily= {“Mother”:54, “Father”: 62, “Sister”: 17}

>>>del myfamily [“Sister”: 17]


>>>print (myfamily)

Accessing and sorting keys from a dictionary

To see all of the keys from a dictionary, simply use the


command function;

list (d.keys())

This will show you all of the keys within your dictionary.

Example:

>>>list (myfamily.keys ())

[‘Mother’, ‘Father,’ ‘Sister’]

And if you want to arrange them, you can simply use the
keyword for sorting data;

sorted.(d.keys())

Example:

>>>sorted (myfamily.keys())

[‘Father’, ‘Mother,’ ‘Sister’]

Finding specific keys

If you are looking for a specific key in a dictionary, you


can simply use the ‘in’ keyword. Here is an example;
Example:

>>> “Father” in myfamily

And the output reads

True

Example:

>>>” Uncle” in myfamily

False

You can see a dictionary as a reservoir which you can tap


from any time because it will serve you well in your python
coding journey.

TUPLES

You should, at this point, know a thing or two about tuples,


and if you don’t know already, a quick refresh will do you
a great deal of good.

Tuples are similar to strings and numbers in that they are


immutable but can contain mutable elements or sets of
values. They can be homogeneous, i.e., contain the same
elements like numbers or letters and can also be
heterogeneous, i.e., containing a mixture of letters and
numbers. Like strings and lists, they are separated by
commas, but it is enclosed in parentheses.

Why Tuples?

Unlike lists, tuples cam contain heterogeneous data or


elements that can be arranged properly.

Example:

>>>tup1= (1720, 2003, 1945, “Indianapolis”, “Kentucky”)

>>>print (tup1)

(1720, 2003, 1945, 'Indianapolis', 'Kentucky')

Tuples can also be nested. Here is an example below;

Example:

>>>tup2= (((1720, 2003, 1945, 'Indianapolis', 'Kentucky'),


“Father”, “Mother”, 2011, 1948, 2020, “Sister”))

Updating Tuples

Tuples can be updated by creating new tuples from the


values or elements of existing or previous.

This is simply because they are unalterable.

Example
>>>marks = (35, 27, 54, 64, 69)

>>>studentnames = (“Arthur”, “Bella”, “Vickky”,


“Blessing”, “Matthew”)

>>>candidates = marks + studentnames

>>>print (candidates)

(35, 27, 54, 64, 69, ‘Arthur’, ‘Bella’, ‘Vickky’,


‘Blessing’, ‘Matthew’)
CHAPTER FIVE

Modules Classes and Methods

Modules are used to organize or arrange files. They are


grouped elements or values that you can refer to and call
them any time they are needed.

Packages

They are similar to folders. They contain more than a single


module that are properly organized. They are represented
by “_init_.py file name (empty file)

To have a glimpse of how modules truly work, a good


knowledge of import will be of great essence. Let’s do a
little bit of straight dive.

There are two ways you can import packages;

Absolute Import

What an absolute import does is point out the elements or


values to be imported using its full path from the project's
main folder. The absolute import can be associated with
the following codes;

import package.module

obj = package.module.class A ()

from package.module.class A ()

import class A ()

from package import module

obj = module.classA ()

>>>from module_name import*

This statement will import all modules from the root folder.
The only thing you must avoid is modules duplicate.

Relative Imports

You can simply import the class of a module into another


within the same package. A relative import points out the
data to be imported depending on the recent location of
the import.
Here are a few examples of relative imports;

From.module2 import classB

Obj = classA ()

From..some_module3 import some_classC

Obj = classC ()

Dates and Time Module


These are of two types, which are dates and times objects.
These are “naïve” and “aware.”

Aware is conscious of its environment as relates to time


zones, time adjustments, and other aspects of time it may
currently or in the near future be in. The naïve, on the other
hand, is unaware of its environment and cannot work on
its work since it lacks the necessary information to work on
its own.

Here are some of the examples of constants that can be


exported by datetime module;

Datetime.minyear

This is tantamount to 1. This implies that the output will


include years back in the past, even before the birth of
the python programming language.

>>>datetime.time = datetime.time (hours=0, minute =0):


Example:

>>>import datetime

>>>current_time = datetime.datetime.now ()

>>>print (“{:%H:%M}”.format (current_time))

10:38

Example:

>>>import datetime

>>>datetime.datetime.now ()

>>>print (now.year)

2020

Example:

>>> import datetime

>>> datetime.datetime.now ()

datetime.datetime (2020, 6, 27, 16, 10, 21, 180317)

This is the same as 16:10


Datetime.maxyear

This is like writing 9999, i.e., the largest amount of year into
the future that can be provided by an element or
datetime object.

OBJECT ORIENTATION

The python programming language is object-based,


meaning that more emphasis is placed on objects rather
than functions. When data and objects and data
becomes bigger, the need for an object-oriented
programming approach becomes quintessential.

You can simply look at object-oriented programming as a


way of representing or modeling real-world objects in your
codes. The key thing to remember here is that python is
an object-oriented programming language, and
everything is woven around, built on and about objects
even if some aspects of it is not directly pointing to an
object, it may be a representation of it.

CLASSES IN PYTHON

You can, by analogy, refer to a class as a clay reserve


where several mugs and plates are made from. A class, in
short, is like a code guide or model from which objects are
built or made.
How to create a class
You can easily create a class by using “class” keyword.
Here is an example of a class

Example:

>>> class religion:

def __init__(name,doctrine):

name.name = name

name.doctrine = doctrine

r1=religion ("christian", "pentecostal")

print (r1.name)

print (r1.doctrine)

Keep in mind in this example that the function _ _init_ _ is


called each time an object is created within or from a
class.

Instances

You can simply refer to an instance as a duplicate of class


with real values, i.e., an object member of a class.
Try and imagine a google form URL or link that is shared in,
let’s say your WhatsApp group. You clicked on it and
yooza! A form appeared with fields for you to fill up. At the
end of it, a copy of all the info you entered was sent to
your inbox. Now, the copy sent to you is an instance which
contains the info you filled out yourself.

`Instance Attributes

Classes in python are object-specific, and they have


certain properties known as “Attributes.”

Class Attributes

The variables are the same for all instances.

INHERITANCE

This is used to refer to a situation where a class assumes


the method and attribute of another one. They usually of
two forms which are; the parent or base class and the
child or derived class.

Child classes are a resultant of a parent inheritance, and


they share all of the attributes of their parent classes.
However, they can choose the path they intend to follow,
which in some cases may be different from that of their
parent.

You can create a parent class from just about any class
of objects or variables. Here is an example;

Example:

>>> class HouseAddress:

def _ _init_ _(self, housename, streetname):

self.housename = housename

self.streetname = streetname

def printname (self):

print (self.housename, self.streetname)


CHAPTER SIX

Files and the Web

File Management

File management is very important in python


programming; this is because, with files, you can properly
arrange your codes and store them. You can carry out
simple tasks like writing into a file, reading a stored file, or
closing a file. Before we dive right in, there a few things
about a file or files you should be familiar with;

Header

This refers to the data about the contents of the file, like
the name of the file, size, format, etc.

Data

What is contained in the file.

End of file

This is used to signify the end of a file.

File Path
This is where a file is located on your system.

This is further divided into three, which are;

i. Filename

This is the name given to a file. You can rename anytime


you want.

ii. Extension

This is used to indicate the file type.

iii. Folder Path

This indicate the location of a file in a folder or sub-folder.

Reading a File

To read a file is very easy. All you have to do is open the


target file with the open () function.

Here is the syntax

Open ()

Open (filename, mode)

filename.read ()

filename.readline ()

This will allow you read the file line by line

filename.readlines ()
This will allow you to read lines in a given text file.

Closing a File

You can simply close a file using the file object method
close (fobj). Here is the syntax;

fobj = open (“filename.text”)

for line in fobj:

print (line.rstrip ())

fobj.close ()

Alternatively, you can decide to use this one instead;

quote = open (“filename.txt”).readlines ()

print (quote)

You can also use this;

quote = open (“filename.txt”).read ()

print (quote[:])

Writing into a File

To write into a file, you can use the write () method. Here
is the syntax;
fh. (“filename.txt”, “w”)

fh.write (“live and let live”)

fh.close ()

Creating a File
If you want to create a file in python, you can start by
simply opening a text editor and input all the contents you
intend to input. When you are done, before you exit, do
not forget to name and save your file for later use. You will
be prompted to save the file before you exit the
application.

Reading and Writing Binary Data


In python programming language, you can use the open
() function and the read binary “rb” or write binary “wb”
mode to read or write binary data. Bytes, byte array, and
memory view are all part of binary sequence types.

Bytes

Bytes can be expressed in terms of integers, zero filled


bytes objects, or binary data contained in the buffer
protocol, and the binary values are unchangeable.
Bytearrays

Unlike the bytes, the variables are mutable.

PICKLE MODULE OR PICKLING

Pickling or pickle module in python programming is used


to describe the process of turning objects structures or
their equivalent values into byte fragments or streams, i.e.,
0s and 1s. importing pickle can simply be achieved by
using the command below;

The Dump Method

This is simply used to dump objects using the command

>>>pickle.dump (obj,file [protocol, *, fix_imports = true])

And you can also read the contents of the dumped files
whenever you want to by using;

>>>pickle.load (file).pickle.load

Example:

>>>import pickle

>>>subjects = [“Mathematics”, “Biology”, “Chemistry”,


“Physics”]
>>>fh = open (“data.pk1”, “wb”)

>>>fh.close () where fh means file handle object

Some important things to keep in mind regarding pickling


in python;

 The fact that pickling can be put to good use in


saving complicated data is undeniable
 It is quite simple, doesn’t require long lines of code
 Pickled file in python may be unreadable in other
programming languages
 The pickled file or module is not malware proof

INTERNET

Most of the applications we know of rely on the internet,


a chunk of them works without the internet, though, but
one way or another, they still rely on the internet, whether
for download, upload, import or update. You can
comfortably liken the internet to a classroom filled with
students with each of them having their unique identities
and names. Now, you want to call on one of them at a
particular point in time; all you have to do is call on the
identity of that particular student, whether by name or a
designated id number. This is how the internet works.

Simply put, your raspberry pi communicates with the


internet through a web server by sending HTTP (Hypertext
transfer protocol) requests to it. The server then responds
by returning packets of data in form of text, usually in HTML
(hypertext markup language). You can use python to
perform other web services like parsing and retrieval of
data using XML (extensible markup language).
CHAPTER SEVEN

Tkinter

There are many frameworks associated with python


regarding the Graphical User Interface, and Tkinter
happens to be the only one that’s embedded in the
python library. Of the many GUIs available, Tkinter is the
most typically used technique. Python with Tkinter is the
quickest and easiest method to make the user interface
applications. Making a user interface victimization Tkinter
is a straightforward task.

To create applications using Tkinter, here are the steps you


need to follow;

 Importing the module – Tkinter


 Create the key window (container)
 Add any variety of widgets to the key window
 Carry out the event Trigger on the widgets.

To import Tkinter, you can simply use the “import Tkinter”


function.
When creating GUI in python programming language,
keep these in mind;

*In the process of creating the main window, you can


make use of;

>>>tk (screenName= None, baseName= None,


className=’tk’, usetk=1)

You can also change the name of the window you have
created by simply altering the “className” to the one
you want. Here is the code to make it happen;

m=tkinter.tk (), in this case, m is the name of the window.

As soon as you are ready to run your application, you can


simply the mainloop function to execute the codes in your
Tkinter application.

m.mainloop (), mainloop is an endless loop used in the


running of tk application.

There are several widgets you can include in your Tkinter


application to make it intuitive. Here are some of them;

Several options are available to alter the format of


buttons. Some of these choices may be passed as
parameters separated by commas. A number of them is
listed below.
 Button

This widget is used to include button in your application.


Here is the code syntax;

w = Button (master, option=value)

Activebackground

This widget is typical in the fixing of the background color


once button is beneath the mouse pointer.

Active foreground

This is used to fix the foreground color once button is


beneath the mouse pointer.

Bg

This comes in handy when you want to fix the default


background color.

Command

This is used to retrieve a function.

Font

This is used to line the font on the button label.

Image

You can utilize this to line the image on the button.


Width

To line the dimension of the button.

Height

This is used to fix the peak of the button.

Example:

>>>import tkinter as tk

r = tk.Tk ()

r.title ('Countdown')

button = tk.Button (r, text='end', width=20,


command=r.destroy)

button.pack ()

r.mainloop ()

1. Canvas

You can make use of this to depict images and other


conventional graphics layouts like text and widget. Here
is the code syntax;

>>>w = canvas (master, option = value)

Where master stands for the mother window.


There a number of options available that you can make
use of to alter the outlook of a widget. Here is a quick list
of some of them;

Bd

This can be used to put the border width in pixels

Bg

You can use this to fix the traditional background-color

Cursor

This can be used to include the mouse pointer in the


canvas widget

Highlight color

You can make use of this to fix the color of the highlighted
area in place

Width

This is used mainly to put the widget in place

Height

To measure the height of the widget

Example:

>>>from Tkinter import *


master = Tk ()

w = Canvas (master, width=42, height= 58)

w.pack ()

canvas_height =20

canvas_width = 220

y = int (canvas_height / 2)

w.create_line (0, y, canvas_width, y)

mainloop ()

There are other widgets too apart from canvas used in


GUI. Here is a list of them and their various definitions;

 Check Button

This is used to pick an option from a number of options


shown to the user in form a toggle button. Here is the code
syntax;

w = CheckButton (master, option=value)

 Entry

You can type in the one-line text using entry. For more
than one line, simply opt for the widget.
The code syntax is written as;

w=Entry (master, option=value)

 Frame

This used to put widgets together as a single entity in an


organized form. The code syntax is written as;

w = Frame (master, option=value)

 Label

A label is like a box where you can palace a text or image


to be displayed and altered any time you want to. The
code syntax is written as;

w=Label (master, option=value)

 Listbox

This offers a user some options to choose from, be it of long


or shortlist. The code syntax is written as;

w = Listbox (master, option=value)

 MenuButton

It is a part of a drop-down menu that remains within the


window at all times, with each of them having their various
usage. The code syntax is written as;

w = MenuButton (master, option=value)


 Menu

With this, you can create just about any type of menu for
Tkinter application. Here is the code syntax;

w = Menu (master, option=value)

 Message

This functions like a label, and it has a non-single


unalterable text. The code syntax is written as;

w = Message (master, option=value)

 ScrollBar

This refers to a slide regulator that can be carried out using


listed widgets. The code syntax can be written as;

w = Scrollbar (master, option=value)

 Text

This is used to alter the way a multiple-line text is shown.


Below is the code syntax;

w = Text (master, option=value)


TEMPERATURE CONVERTER

Here is an example of a simple temperature converter


application using Tkinter.

# tempconverter.py (filename)

from Tkinter import *

def convert_to_cel ():

words = fbtext.get ()

ftemp = float (words)

celbox.delete (0, END)

celbox.insert (0, '%.3f' % (tocel (ftemp)))

return

def convert_to_fahr ():

words = cbtext.get ()

ctemp = float (words)

fahrbox.delete (0, END)


fahrbox.insert (0, '%.3f' % (tofahr (ctemp)))

def tocel (fahr):

return (fahr-32) * 5.0 / 9.0

def tofahr (cel):

return cel * 9.0 / 5.0 + 32

app = Tk ()

app.title ('Temperature converter')

fahrlabel = Label (app, text = 'Fahrenheit')

fahrlabel.grid (row = 0, column = 0, padx = 5, pady = 5,


sticky = E)

cellabel = Label(app, text = 'Celsuis')

cellabel.grid (row = 1, column = 0, padx = 5, pady = 5,


sticky = E)
fbtext = StringVar ()

fbtext.set ('32')

fahrbox = Entry (app, textvariable = fbtext)

fahrbox.grid (row = 0, column = 1, padx = 5, pady = 5)

cbtext = StringVar ()

cbtext.set ('0')

celbox = Entry (app, textvariable=cbtext)

celbox.grid (row = 1, column = 1, padx = 5, pady = 5)

fgobutton = Button (app, text = 'Go', command =


convert_to_cel)

fgobutton.grid (row = 0, column = 2, padx = 5, pady = 5,


sticky = N+S+E+W)

cgobutton = Button (app, text = 'Go', command =


convert_to_fahr)

cgobutton.grid (row = 1, column = 2, padx = 5, pady = 5,


sticky = N+S+E+W)
exitbutton = Button (app, text = 'Exit', command = quit)

exitbutton.grid (row = 2, column = 0, padx = 5, pady = 5,


sticky = N+S+E+W, columnspan = 3)

app.mainloop ()
CHAPTER EIGHT

Games Programming

There are some programming languages you can utilize in


game development, and python happens to be one of
them. A very good example of this is the Pygame, which
we’ll explore in this chapter. I bet this chapter definitely
won’t turn you from a rookie to an expert, but it will arm
you with the basics to goad you on your journey in
creating games using python.

What is Pygame?
Pygame is a set of modules specifically written in python
programming language to create video game or any
type of game you can think of.

Many times you wish to visualize the programs you're


making because it will facilitate you to find out
programming logic quickly. Games area unit is fantastic
for this, as your area unit specifically programming
everything you see.

Game creation in any artificial language is incredibly


bountied, and additionally makes for a good teaching
tool. With game development, you regularly have quite a
little bit of logic, arithmetic, computer science, and
alternative things, all of that move for game creation. Not
solely this, however, the subject is games; thus, it is often
terribly fun.

To get started, you'll have to transfer pygame, then install


it, and you're able to go! If you're a Raspberry pi user, you'll
merely open the applying at once because it comes with
pygame already put in on the default raspbian
installation.

You can currently begin to make your 1st python


program.

But before you progress to any further, here are some of


the things you would like to keep in mind;

 In Pygame, Multicore CPUs are often used simply.


 It is very transportable and light-weight.
 It's straightforward and straightforward to use.
Many games are printed. More than 660 games are
printed on the pregame; thus, you'll make sure a lot of it's
been tested well by voluminous users.

You can use pygame from instruction if you would like to


use it simply to method pictures, get joystick input, or play
sounds.

It doesn't have many thousands of lines of code for stuff


you will not use anyway. The core is unbroken,
straightforward, and further things like interface libraries
and effects area unit developed several outside of
pygame.

Now, let’s consider an example of a typical pygame. At


the end of the code line, you should have a working snake
game written purely in python.

#Snake.py

Import pygame

Import sys

Import time

Import random
From pygame.locals import *

FPS = 5

Pygame.init ()

fpsClock = pygame.time.Clock ()

SCREEN_WIDTH, SCREEN_HEIGHT = 620, 460

Screen = pygame.display.set_mode ((SCREEN_WIDTH,


SCREEN_HEIGHT), 0, 32)

Surface = pygame.Surface (screen.get_size ())

Surface = surface.convert ()

Surface.fill ((250,250,250))

Clock = pygame.time.Clock ()

Pygame.key.set_repeat (1, 40)

GRIDSIZE=10
GRID_WIDTH = SCREEN_WIDTH / GRIDSIZE

GRID_HEIGHT = SCREEN_HEIGHT / GRIDSIZE

UP = (0, -1)

DOWN = (0, 1)

LEFT = (-1, 0)

RIGHT = (1, 0)

Screen.blit (surface, (0, 0))

Def draw_box (surf, color, pos):

R = pygame.Rect ((pos [0], pos [1]), (GRIDSIZE,


GRIDSIZE))

Pygame.draw.rect (surf, color, r)

Class Snake (object):

Def __init__ (self):

Self.lose ()

Self.colour = (0, 0, 0)
def get_head_position (self):

Return self.positions [0]

def lose (self):

Self.length = 1

Self.positions = [((SCREEN_WIDTH / 2),


(SCREEN_HEIGHT / 2))]

Self.direction = random.choice ([UP, DOWN, LEFT,


RIGHT])

def point (self, pt):

If self.length > 1 and (pt [0] * -1, pt [1] * -1) ==


self.direction:

Return

Else:

Self.direction = pt

Def move (self):


Cur = self.positions[0]

X, y = self.direction

New = (((cur [0] +(x*GRIDSIZE)) % SCREEN_WIDTH),


(cur [1] +(y*GRIDSIZE)) % SCREEN_HEIGHT)

If len (self.positions) > 2 and new in self.positions [2:]:

Self.lose ()

Else:

Self.positions.insert (0, new)

If len (self.positions) > self.length:

Self.positions.pop ()

def draw (self, surf):

For p in self.positions:

Draw_box (surf, self.color, p)

Class Rat (object):

def __init__ (self):

Self.position = (0, 0)
Self.color = (255, 0, 0)

Self.randomize ()

def randomize (self):

Self.position = (random.randint (0, GRID_WIDTH-1) *


GRIDSIZE, random.randint (0, GRID_HEIGHT-1) * GRIDSIZE)

def draw (self, surf):

Draw_box (surf, self.color, self.position)

def check_eat (snake, rat):

If snake.get_head_position () == rat.position:

Snake.length += 1

Rat.randomize ()

If __name__ == ‘__main__’:

Snake = Snake ()

Rat = Rat ()
While True:

For event in pygame.event.get ():

If event.type == QUIT:

Pygame.quit ()

Sys.exit ()

Elif event.type == KEYDOWN:

If event.key == K_UP:

Snake.point(UP)

Elif event.key == K_DOWN:

Snake.point(DOWN)

Elif event.key == K_LEFT:

Snake.point(LEFT)

Elif event.key == K_RIGHT:

Snake.point (RIGHT)

Surface.fill ((255,255,255))

Snake.move ()
Check_eat (snake, rat)

Snake.draw (surface)

Rat.draw (surface)

Font = pygame.font.Font (None, 36)

Text = font.render (str (snake.length), 1, (10, 10, 10))

Textpos = text.get_rect ()

Textpos.centerx = 20

Surface.blit (text, textbox)

Screen.blit (surface, (0, 0))

Pygame.display.flip ()

Pygame.display.update ()

fpsClock.tick (FPS + snake.length/3)

It’s a little bit long but at last, here we are. So far, we have,
through the code, make use of the following crucial parts
of pygame. Here they are;

Screen pixels

This is a picture element visible on the screen consisting


mainly of pixels (smallest unit of an image on a screen).
These picture elements can be altered by simply using the
“blit ()” function. This will duplicate the pixel from one
picture element to another.

Screen Coordinates

I think I can take a logical guess here and say that you
have in one or another come across the Cartesian
coordinate system, most probably in your high school
years. The same concept applies in pygame. The only
difference as compared to the way you use it in the
pygame world is that your coordinates (x, y) is at the top
left corner of your screen rather than in the middle, which
is perhaps what you are accustomed within your
knowledge of mathematics.

To position an object on the screen, we want to inform the


blit () function of where to place the image on the screen.
In pygame, we tend to continually pass positions as (x, y)
coordinate. This represents the amount of pixel to the right
and, therefore, the range of pixels down to place the
picture element. The top-left corner of a surface is
coordinate (0, 0). Moving to the right a little bit would be
(10, 0), and moving down would be (10, 10).once blitting,
the position argument represents where the top-left
corner of the origin should be placed on the destination.
CHAPTER NINE

Interfacing with the Hardware

There are many ways you can connect other hardware to


the raspberry pi board. It can be through the GPIO pins,
the USB ports, or any other ports you can find on the
raspberry board. In this chapter, we will be focusing on
connecting other external hardware using the GPIO pins
to the raspberry pi.

GPIO PIN CONNECTIONS

A very good feature of the Raspberry Pi is that the row of


GPIO (general-purpose input/output) pins on the highest
fringe of the board. A 40-pin GPIO header is found on all
current Raspberry Pi boards (unpopulated on Pi Zero and
Pi Zero W). Before the Pi one Model B+ (2014), boards
comprised a shorter 26-pin header.

Voltages
Two 5V pins and 2 3V3 pins square measure gift on the
board, also as variety of ground pins (0V), that square
measure unconfigurable.

Outputs

The power output is usually between 0V and 3.3V.

Image source: raspberrypi.org

Inputs

A GPIO pin selected as an input pin can be as high as


(3.3V) or low (0V). the resistors added to it makes it easier
to control the voltage level at any point in time.
Image source: raspberrypi.org 2

INTERFACING THE BREADBOARD TO RASPBERRY PI


USING JUMPER WIRES
The breadboard live connection

You can simply use a jumper wire to connect the


breadboard to a 5V pin on the Raspberry Pi device and
be sure to confirm that the live and neutral end are
properly connected to the right pin port on the board.

The breadboard's ground connection

On the ground end of the breadboard, use a jumper wire


to initiate a bridge between the ground (GND) pin on the
pi board and the GND pin port on the breadboard using
jumper wire (you may decide to use a different color for
the GND connection to differentiate it from other wires).
Keep in mind that all blue holes currently act as a ground
pin.

Add an electrical device to the board

Take an electrical device and connect one leg of it to a


hole on the bottom rail of the board. Take the opposite
leg and connect it to a hole on the major board.

Add the junction rectifier to the board

Take associate degree junction rectifier part and


appearance at the legs. Notice that one among the legs
is shorter than the opposite. Place the shorter leg in a very
hole on identical row because the electrical device.

Wire up the board

Place the longer leg in a very hole on succeeding row on.


Currently, take another male-to-male jumper and place
one finish within the hole next to the long leg of the
junction rectifier. Place the opposite finish in a very hole
on the red live rail to complete the circuit. The junction
rectifier lights up.

ARDUINO AND RASPBERRY PI

You may be familiar with or heard about Arduino before,


and you happen to think they are the same. Well, it is not
exactly the way you pictured it.
You can liken an Arduino to the circuit board of a
microcontroller. A microcontroller may simply be referred
to as a pc which will run one program time and time
again. It’s straightforward to use.

A Raspberry Pi is single-board hardware equipped with


the speed and memory to run many programs. It has
additional sophisticated usage compared to Arduino.

An Arduino is most suitable for a single task that can be


repeated as many times as possible.

Raspberry Pi can be used for just about anything a


traditional computer would normally do. This can range
from programming to hacking, design, and anything you
can hope to imagine or dream of.
CHAPTER TEN

Linux Resources

There are many systems out there that are built basically
from Linux, and raspberry pi happens to be one of them.
It primarily runs on Linux. This book doesn’t cover much on
Linux, but the good news is there tons of resources out
there you can get your hands on, and you don’t even
need to visit a library to achieve that. All of that can be
achieved at the comfort of your smartphone.

Here are some of the resources you will find very helpful;

Linuxcommand.org

Geekuniversity.com

Linuxnewbieguide.org

Linux.com
If you happen to get your hands on any of the books
written on Linux in the library, don’t hesitate to get as
many info you can from it.

Python Resources

The raspberry pi is not built entirely on the python


programming language. This means there is an almost
endless pool of resources out there for learning it. Like I
have said earlier, you don’t have to visit a library to get
your hands on the resources needed to learn python.
Here is a list of some you will find very helpful on your way
to becoming a professional python programmer.

Docs.python.org

Realpython.com

W3schools.com

Codecademy.com

Pygame.org

Raspberry pi Resources
If there is anything you want to know about raspberry pi,
you will find it on their official website on raspberrypi.org
Other Programming Languages
In the preceding chapters, we have dealt extensively on
how to program the raspberry pi using python. However,
there are other programming languages that can be
used. One of such is the C language. If you want to try
other programming languages on the raspberry pi, there
are a ton of them out there you can make use of.

Applications and Projects


There are tons of applications out there that can have
come to live as a result of the raspberry pi, and there is a
huge community of programmers out there who are
dedicated to the development of the raspberry pi or any
technology that is associated with it.

One of these community initiatives is the CoderDojo club


for kids between the ages of 7 and 17 and the Raspberry
Jam meetups for anyone who wants to just make things
using raspberry pi.
CONCLUSION

Having a fast computer while you do your programming


is quite impressive, much more when using a
programming language that is easy to understand. The
combination of the Raspberry Pi and Python
programming language yields excellent results; your job
gets easy and can be completed faster. With the ideas
shared in this book, all difficulties surrounding how to use
your Raspberry Pi and programming with Python can be
brought to a solved case. Hence, you can now
understand how the Raspberry Pi hardware components
work, the basics of Python, and better knowledge of
module classes and their methods.

You might also like