Raspberry Pi An Easy Guide To Programming Developing and Setup of Raspberry Pi
Raspberry Pi An Easy Guide To Programming Developing and Setup of Raspberry Pi
ALEXIS
RODRÍGUEZ
Copyright © 2020 Alexis Rodríguez
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 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.
Contents
INTRODUCTION
CHAPTER ONE
UNDERSTANDING RASPBERRY PI
Different Models of Raspberry PI
The General Features and Provisions of Raspberry PI
The General Provisions of Raspberry Pi
The Specifications of the Hardware of Raspberry Pi
The Central Processing Unit (CPU)
The Ethernet Port
The Graphics Processing Unit (GPU)
General Purpose Input & Output (GPIO) Pins
Raspberry Pi Memory
The Universal Asynchronous Receiver / Transmitter (UART)
Display Monitors or TV
Power Source Cable or Connector
The Board of Raspberry Pi Model A
The Features of the Board of Model A Raspberry Pi
The Board of Model B Raspberry Pi
The Features of the Board of Model B Raspberry Pi
Functionalities of Raspberry PI
Detailed Explanations of these Projects
Other Projects you can do using Raspberry Pi
All the Tools Required to Setup Raspberry PI
Internet Connection
Installing Raspberry PI
Installing Raspbian on a Raspberry Pi
What is NOOBS?
NOOBS Installation Manager
Raspberry Pi Installer
CHAPTER TWO
BASIC PROGRAMS IN PYTHON
Basic Python Programs
Python Programs for Functions
Python Programs for Numbers
Python Programs for Array
Python Programs for Circular Linked List
Python Programs for Doubly Linked List
Python for Native Data Type Programs
Python Programs for Conditions and Loops
The Versions of Python and their Release Dates
How to Run Python
Requirements for Running Python Programs on a Raspberry Pi
Details about Python Libraries
Running Python Programs Using Terminal
Running Python Programs through IDE
Running Python Program Using Thonny
Executing Python Script with Python Shell
Reasons for Using Loops in Python
Benefits of Using Python Loops
Different Loop Statements in Python Programs
Features of IDLE
Types of Python IDEs
Microsoft Visual Studio IDE
Numbers and Variables
Types of Numerical Variables
Floating-Point Values
How to Declare Variables and Assign Values
How to Reference Objects in Python
How to Create Object Identity in Python
How to Determine the Names of Variables
How to Create Multiple Assignments
Assigning a Single Factor to Multiple Variables
Assigning Multiple Factors to Multiple Variables
How to Install the Application Initially
How to Improve Error Handling Using Try and Except Method
CHAPTER THREE
WHAT ARE DICTIONARIES, LISTS, AND STRINGS?
How to Create Dictionaries
How to Access the Values of Dictionaries
How to Add Dictionary Values
How to Delete Elements using del keyword
Understanding the String Theory
How to Create String in Python
How to Index and Split Strings
How to Reassign Strings
How to Delete Strings
What are String Operators?
String Formatting in Python using Escape Sequence
String Functions in Python
What are the lists and their functions?
Built-in Functions in Python Lists
What are Multiple Assignments and Multiple Return Values?
Using Multiple Assignments with a List
Using Multiple Assignments with a String
Uses of Multiple Assignments in Python
Multiple Return Values
Defining and Identifying Function Keys in Python
Types of Number Conversions in Python
Using Python Decimal
Lists and Dictionaries
CHAPTER FOUR
UNDERSTANDING CLASSES, METHODS, AND MODULES
What is a Module?
What are the modules in Raspberry PI?
The Specifications of a Computer Module
Libraries in Python
Features of Matplotlib
Features of Requests Library
Features of Theano Library
Features of Pillow Library
Features of Keras Library
Features of Fire Library
Features of NLTK (Natural Language Toolkit)
Features of Arrow Library
Features of FlashText Library
What is object orientation?
CHAPTER FIVE
HOW TO USE FILES AND INTERNET WITH RASPBERRY PI
Using Files and Internet on Raspberry Pi
What are the files in Raspberry PI?
Step-By-Step Method of Accessing a File in a Raspberry Pi
How to manage the file system
How to Create Files
Deleting Files
How to Copy Files
How to Show the Content of a File
Reading and Writing Files
Ways to Write Values
What are the differences between the Internet and Pickling?#
CHAPTER SIX
HANDLING GRAPHICAL USER INTERFACES IN RASPBERRY
GUIs on Raspberry Pi
What is Tkinter Module in Python
The Approach on How to Use Tkinter
How do Hello World and Temperature Converter operate in GUI
Understanding Listbox and Spinbox
The Parameters for Using Listbox
The Methods of Listbox Objects
CHAPTER SEVEN
HARDWARE INTERFACES IN RASPBERRY
Pin Connections in GPI
.....................................................................................................................
Prototyping Boards in Raspberry
Features of Prototyping Boards in Raspberry Pi
CHAPTER EIGHT
LEAD FADER AND PROTOTYPING PROJECTS
Requirements for Lead Fader Projects
How to Assemble the Hardware
Running the Software
Requirements for Prototyping Project
How to Assemble Prototyping Hardware
What are in Phase Two of the Prototyping Project?
CHAPTER NINE
PROJECTS IN RASPBERRY PI
How to Construct a Weather Station
How to Craft a Security System
CHAPTER TEN
HOW TO PROGRAM GAMES
Step-by-step Process of Games Programming in Raspberry PI
Types of Games in Raspberry PI
What are the coordinates?
How to follow the Mouse
CHAPTER ELEVEN
WHAT IS RASPBERRY PI ROBOT?
Requirements for Raspberry PI Robot
Connect your System to the Power Source
How to Handle Autonomous Rover
How to Assemble the Hardware
CONCLUSION
INTRODUCTION
Are you interested in this new small device that has taken center
stage of the IT industry? Raspberry PI made a debut on February
24th, 2012. Unfortunately, the website of the supplying firm crashed.
However, new models of Raspberry PI 2, have been released and
are in circulation.
This computer device has a Linux operating system and designed
with a High-Definition Multimedia Interface (HDMI) video output. You
can connect a computer monitor or television into it. But the monitor
must have a DVI connector with HDMI to DVI adapters connected to
the system before it can function correctly. Your Raspberry PI may
not work if your monitor has only a VGA connector.
This device is a global phenomenon. It is useful for various activities
such as a regulator for smart home appliances and a media center.
Additionally, the Raspberry Pi could serve as a desktop workstation.
Now, beginners can code or decode python programming language.
In the same vein, experienced programmers that are not conversant
with Raspberry PI can learn various ways of using the features and
functionalities of the software for different businesses.
You can begin to write programs for your device using the renowned
Python programming language. You can learn the essentials of
graphical user interfaces. Understanding the pygame module will
assist you in building fun and exciting games.
Raspberry PI Foundation recommended using Raspbian Wheezy
distribution. The book contains a perfect representation of this
phenomenon for better understanding. It is good to note that the
original Raspbian operating system was developed and designed by
Peter Green and Mike Thompson.
In this book, you will learn the ABC of Raspberry Pi and the
requirements of setting it up. You will also learn basic programs in
Python. Other things that can help you navigate and use the
Raspbian include a comprehensive knowledge of string theory, lists,
and dictionaries.
How to use files and the internet are necessary information every
newbie in the field needs to enjoy this technology. Mastering the
operations of GUIs and other hardware interfaces in Raspberry are
proficient skills for success in software programming.
Let's dive inside the book for you to see and know more!
CHAPTER ONE
UNDERSTANDING RASPBERRY PI
Raspberry Pi Device
Raspberry Pi functions as a desktop computer designed to access
the internet and play games. It can help you to build spreadsheets
and word-processing documents. Additionally, the Raspbian can
help you play high-definition videos.
This device can help beginners and experienced software engineers
to learn computing skills and programming languages such as
Python and Scratch. A Pi is an affordable computer device as small
as a credit card that you can plug into a television or computer
monitor. It also functions with a mouse and standard keyboard.
The system is a multipurpose machine used for building digital
projects. The varieties of projects it can handle include building
weather stations, and recording and playing music. Also, it comes
with infra-red cameras for tweeting birdhouses.
It is designed as a prototype of a computer that enables children to
learn to program. They will also know how to operate a computer
device.
Raspberry Pi is a trademark from Raspberry Pi Foundation. This
charity organization is registered and located in the United Kingdom.
The registration number is 1129409 . It was founded with the
purpose of furthering the academic courses of children and adults
interested in acquiring technical skills in the field of computer science
and other subjects in that field. Another target market for this product
is the literate masses in developing countries, who may avail
themselves of the opportunity of learning
programming.
Specifications of a Raspberry Pi
This microcomputer is an educational tool with hardware having the
following specifications: GPIO pins, power source connector, central
processing unit (CPU), random access memory (RAM), Xbee socket,
GPU, and UART.
Raspberry Pi has mass storage using an SD flash memory card. You
PC boots into Microsoft windows through the hard disk while an SD
memory card helps the Raspbian to boot. Other specifications of the
hardware include a US standard keyboard, video cable, power
supply cable, monitor, and a microSD card having Linux operating
system.
Other optional specifications you may need include device case,
model A or model B, WiFI adaptor, internet connectivity, USB mouse,
and powered USB hub. Use a LAN cable for internet connectivity to
the B model.
Detailed explanations of all the specs include
Raspberry Pi Memory
If you compare Raspberry Pi to other computer devices, it is a
miniature PC. Other standard computers have RAM measured in
gigabytes, but the RAM of a Raspbian contains a minimum of 256
MB while the maximum Ram is 512 MB.
Display Monitors or TV
Raspberry Pi board uses two monitors or television for displaying
digital data. These include HDMI and Composite displays. Use a
low-cost adaptor with an HDMI male cable to connect several LCD
and HD TV monitors.
The versions of HDMI supported by your Raspberry Pi are 1.3 and
1.4 using 1.4 cables too. These can help the functions of the video
and audio settings of Raspberry Pi. However, it does not support the
HDMI l/p adapter. The composite video functions are used for
connecting old televisions.
In this case, connecting the device to a display unit using a
composite video connection can make the audio system functional.
Connect the 3.5 mm jack socket and send it to your television. This
is possible using a cable that is adjustable for 3.5 mm to double the
RCA connection.
Functionalities of Raspberry PI
Internet Connection
Use a WiFi adapter or Ethernet cable to connect your device to the
internet. With this, you can download software or update an existing
one.
Power supply
The optimal power supply required by your Raspberry Pi is at least 5
volts. Apply a 5-volt micro USB power supply to power your device. If
you use a power output with a lower voltage, the device will function
funnily.
Earphones of Headphones
Your microcomputer functions with earphones or headphones using
a 3.5 mm jack.
HDMI / DVI Monitor or Television
A Raspberry Pi functions with a television or HDMI monitor or DVI
monitor as a display unit. If you want more explicit pictures and high-
quality images, use a monitor with HDMI input. If you are using older
devices, use other connections. An original Ethernet cable is ideal
for internet access to the system. Raspberry Pi 3 comes with a
integrated wireless LAN.
Installing Raspberry PI
Installing Raspbian on your device is easy by following simple
guidelines. A Raspberry Pi functions with an operating system called
a Raspbian. This originates from the Linux distribution Debian. All
Raspberry Pi's hardware functions with the Linux operating system.
The Raspbian is a multipurpose and professional operating system
that makes your Raspberry Pi device to work well as a computer. It
features a browser, command buttons, and several other programs.
A Raspberry Pi can function as a home computer since it is a low-
cost device with attributes of a PC. It serves as a springboard
enabling you to perform other tasks and projects seamlessly. You
can use it as wireless access points or play exciting video games.
Method 1
Download Raspbian OS
Raspberry Pi Installer
Method 2
Unzip the Compressed File
After downloading, the next step is to unzip the File. It exists with the
ZIP64 format. However, this depends on how the built-in features in
your system are. If they are updated and current, you can use any
program to unzip the File.
Some programs for unzipping files in a Raspberry Pi include
Method 3
Use a MicroSD Card and Write the Disc Image
MicroSD Card
Put your microSD card into your system and write the disc image to
it. This may demand some programs such as:
Method 4
Boot up Your Raspberry Pi after Inserting the microSD Card
The final stage is to insert the SD card into your device and boot
your device. Remember to plug in the power source and the
peripherals. If you have updated your device to the current edition of
Raspbian, this will display on the desktop of your Raspberry Pi.
Apply the default username and password.
Username: pi
Password: Raspberry
Afterward, you can change to your username and password.
Change Name and Password
The Connections
As I stated earlier, a Raspberry Pi is already equipped with a
microSD card slot. Inserting an SD card into the slot is easy since it
is the primary storage space in a Raspberry Pi board. Its function is
the same as a hard disc in any computer device.
The operating system is Linux OS, which is loaded onto the SD card.
This operating system is bootable after plugging the Pi into a power
source. A Raspberry Pi supports Linux OS, Mac, ARM, and Qtonpi
operating systems.
You can select any of these operating systems for your Raspberry Pi
device. Then, you can use a disk manager application and write it to
an SD card. Other external storage systems include a USB drive or a
USB external hard drive.
Different sizes and brands of SD cards are available on the market.
However, your Raspberry Pi can contain an SD card with a
maximum storage capacity of 64 GB.
The connections that can make your Raspberry Pi functional include
a monitor or TV, Mouse, and keyboard. Various output channels are
needed for the display unit. These include composite video, DSI
video, and HDMI video. However, the DSI video output needs
specific hardware to function.
The SD card is an essential component of a Raspberry pi board.
Most times, they may sell a Raspberry Pi board with or without an
SD card. It is used for storing files, documents, and other programs
in this microcomputer.
If you purchase a Raspberry pi board without an SD card, then you
should buy a minimum of 4 GB for your device. But it can contain a
total of 8 GB. With this system; you can manage web traffic properly.
It also functions as a typical computer with a low-cost server,
although smaller in size.
CHAPTER TWO
Loops
In any programming language, the flow of programs is sequential by
default. In most cases, you can alter the sequence of programs. But,
executing a particular code could be done repeatedly.
Programming languages offer several types of loops that can repeat
some specific codes many times.
Features of IDLE
a. It functions as an integrated bugger.
b. IDLE helps in syntax colorization and command history.
c. This feature supports multiple windows.
d. Relevant for unindent or auto-indent for Python codes.
e. Word auto-completion process.
In Microsoft word, such as windows 7 or windows 8, Python IDLE
functions effectively. You could see it at the Start Button Menu in
Windows 7, as an Entry. In Windows 8, go to the Start Menu and
type IDLE. This can help you for running it in the system.
Immediately, it will show the details of the OS and Python version in
the device.
The code should be written after this prompt >>> on your windows.
After pressing on the Enter button, the program will be executed.
One-line commands are executed using shell windows. But, this is
not applied for writing full-fledged programs.
Python IDLE has a built-in text editor. It is useful for writing and
saving your codes. Editors begin to function if you click on File >
New File. This command opens a window for typing your code.
But saving this code in a box file before running it is ideal. Simply
click on File, then Save. However, ensure that the data has a .py
extension.
Running the code requires you tap on the Run button. This will take
you to the Run Module . You can simply press F5. The result of this
program will be printed on the window bearing IDLE. The result will
show below the Restart line.
Atom IDE
Atom IDE was built by GitHub as an open-source cross-platform.
This framework uses an electron that enhances cross-platform
desktop applications. The platform functions with Node.js and
Chromium, which are presently known as Hackable Text Editor.
The Features of this Integrated Development Environment include
i. Viewing outputs on Atom doesn’t require opening another window.
ii. Atom features built-in support for viewing and editing Markdown
files using a plugin called Markdown Preview Plus .
Thonny IDE
Learning or teaching programming languages demands you to use
Thonny IDE. Tartu University built this software. It is useful for
highlighting syntax errors and supporting code completion
processes.
Some of the features of this IDE include
Eric IDE
Eric IDE is a program developed by Python as an editor. It is
valuable for professional programmers and amateurs.
The features of this software include
Rodeo IDE
Retrieving data and information from various sources is possible
using Rodeo Integrated Development Environment. It is regarded as
an ideal IDE for programs. This software is used for the auto-
completion of codes and supports cross-platform functionalities.
The features of this program include
Spyder IDE
Spyder is ideal for data science with an open-source and highly
recognizable in the IDE market. It means the Scientific Python
Development Environment (Spyder). This program accepts and
functions on all relevant platforms such as MacOS X, Windows, and
Linux Operating System.
Spyder IDE offers various functionalities such as document viewer,
integrated console, localized code editor, and variable explorer.
Other scientific modules, such as SciPy, NumPy, etc. are supported
by this IDE.
The various features of this program include:
PyCharm IDE
PyCharm was built by the Jet Brains as software for Python with a
cross-platform for Integrated Development Environment (IDE). This
IDE is available in a free version and paid (PRO) version, and it is
the most widely used open-source program. It helps developers and
programmers take care of regular tasks.
PyCharm is a full-fledged IDE with fast error checking and
correction, database accessibility, auto code completion, quick
project navigation, and remote development support.
The features of this program include
Wing IDE
Wing IDE is packed with decent and necessary development support
features. This cross-platform offer free edition for beginners,
although it has a Pro version that has 30 days trial. This will enable
learners and experienced programmers to try it out.
This IDE program offers services such as debugging, auto-
completion, syntax highlighting, and indents.
The main features of the Wing IDE is that
PyDev IDE
PyDev IDE is an outside plugin for Eclipse and a commonly used
program in Python. If you have experience in Java, it is usually a
natural choice for Python developers with this background. Most
programmers know it as a Python interpreter.
In the years 2003 and 2004, Aleksander Totic is renowned for his
contribution to the Mosaic browser. He also worked on the Pydev
project during this period. It is an integration of Django, auto code
completion, block indents, and smart indents.
The features of this IDE include
Python Variables
A variable refers to the position of memory in the system and as an
identifier used for holding values. Python is an inferred language and
doesn't need specifying types of variables.
Variables are groups of letters and digits (numbers). However, they
start with a note or an underscore. In writing variables, you can use
lower case letters for names of variables such as John and john are
two separate variables.
Floating-Point Values
Floating-point values are Python numbers with decimal points. Any
number written with a decimal part is identified as a floating-point
value.
Therefore, a term like x = 6.5 means that the floating-point value
(6.5) is stored in the variable x. Moreover, vast numbers could be
stored in this way, such as 3.2250738585072015 × 10308 to 2.
7976931348623157 × 10308.
Integer numbers could be converted to floating numbers using the
float number functionality. For example,
X=6
Print (x)
Print ( float (x) )
Output:
James
An integer is created by the Python object and highlights it to the
console. I created a string object in the above print statement.
Another way to determine this is using the built-in type ( )
functionality . For example:
Type ("James")
Output:
< class ‘str’
>
In Python programs, variables are classified as symbolic names
functioning as pointers or references to objects in a statement. The
variables are used to assign names to objects. For example:
b = 20
b 20
Therefore, "b" in the above image represents "20", which is an
integer object. I can also assign the integer value (20) to a new
variable, such as "c." The expression will become
b = 20
c=b
b 20 c
In this expression, the variable b is referring to a specific object that
c is pointing. The reason is that Python doesn’t build separate
objects for variables. It is what you put in that will be represented.
But assigning a new value to c means that both variables will refer to
different objects. For example:
b = 20
c = 30
In this expression,
b 20
c 30
Python software is designed to manage memories properly.
Therefore, assigning similar variables to two different values is
possible.
Output:
14073498291168
14073498291168
2822056960944
I assigned the c = b, b, and c are pointing to the same object. If we
examined according to the id ( ) functionality, it returned the same
number. I assigned b to 500, and it referred to the new object
identifier.
Output:
Devans
h
25
90.5
a. Snake Case
b. Camel Case
c. Pascal Case
a=b=c=30
print(a)
print(b)
print(c)
Output:
30
30
30
x,y,z=20,25,30
print x
print y
print z
Output:
20
25
30
In Python programs, values are assigned in the order and manner
the variables occur in a statement.
Some fundamentals, a beginner, should take note of in Python
include comments and tokens with their different types in programs.
Tokens are reserved words, punctuation marks, and other
expressions in words. The smallest unit of letters in a particular
program is called tokens.
Examples of tokens in programming language include identifiers,
literals, operators, and keywords.
Simulating Dice
At the starting of the program, the user can enter an invalid minimum
or maximum value. This will cause the application to display an error
and quit.
The error could be handled using this method. You can output an
'input invalid program that will revert to default program.' Then, you
should set the lowest and highest values to a default of 1 and 6.
The player will be requested to enter a low and high value inside the
try block. A display of error in any of these values will not execute
the block of code. There will be a print statement from the except
block of code. This will come as a customized error message that
can help you to set the smallest and biggest values of the dice to
default values of one and six.
This feature can help you to improve the error handling of the code
slightly. You can add more support for handling errors with these
blocks of code.
There are many ways of doing the dice simulator. It depends on the
type you choose and your experience as a programmer. But you can
add up a few things to enhance your experience. Adding more
support for input and using a GUI can boost your expertise in
handling the dice simulator in Python.
CHAPTER THREE
There are some built-in structures in Python. These include dictionaries, lists, strings,
and other structures.
Dictionaries
Dictionaries in Python are used for storing data in a key-value pair format. They are the
data type that can simulate real-life data arrangement in Python. In this case, some
peculiar values exist for some specific keys. This data structure is mutable. But
dictionaries are expressed as values and element keys.
Values
In Python, values are expressed as lists, integers, tuples, etc.
Element Keys
Element keys are defined as single element keys.
A dictionary is the collection of key-value pairs, which can be any Python object. But
the keys are immutable Python objects such as strings, tuples, and numbers.
Output
<class 'dict'>
Printing Employee data ….
{‘Name’ : ‘Thompson’, ‘Age’ : 40, ‘salary’ : 35000, ‘Company’ : ‘GOOGLE’}
Python offers built-in function dict( ) method. This feature is used for creating a
dictionary. The curly braces {} with no value or object are used for generating an blank
dictionary.
# Creating an empty Dictionary
Dict = {}
print(“Empty Dictionary: “)
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: ‘Java’, 2: ‘T’, 3:’Point’})
print(“\nCreate Dictionary by using dict(): “)
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = ([(1, ‘Devansh’), (2, ‘Sharma’)])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
Create Dictionary by using dict( ):
{1: ‘Java’ 2: ‘T’, 3: ‘Point’}
Dictionary with each item as a pair:
{1: 'Devansh', 2: 'Sharma'}
Output:
<class 'dict'>
printing Employee data ….
Name : James
Age : 25
Salary : 28000
Company : GOOGLE
In Python, you will find an alternative method of using the get( ) method for accessing
dictionary values. The result you would get is similar to the output by the indexing.
Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: ‘Paul’, 2: ‘John’, 3: ‘Richard’}
Dictionary after adding 3 elements:
{0: ‘Paul’, 2: ‘John’, 3: ‘Richard’, ‘Emp_ages’ : (20, 33, 24)}
Updated key value:
{0: ‘Paul’, 2: ‘John’, 3: ‘JavaTpoint’, ‘Emp_ages’ : (20, 33, 24)}
You can quickly delete the items of the dictionary using a del keyword, such as in this
example.
Employee = {"Name": "James", "Age": 25, "salary":35000," Company":"
GOOGLE"}
print(type(Employee))
print("printing Employee data ….")
print(Employee)
print(Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Output:
<class ‘dict’> …..
Printing Employee data ….
{‘Name’ : ‘James’, ‘Age’ : 25, ‘salary’ : 25000, ‘Company’ : ‘GOOGLE’}
Deleting some of the employee data
printing the modified information
{‘Age’ : 25, ‘salary’ : 25000}
Deleting the dictionary: Employee
Let's try to print it again
NameError: name 'Employee' is not defined
An error is in the above print statement because the Employee dictionary that was
requested for printing has been deleted.
Another method is through the pop ( ) method. This method accepts the key as an
argument. It also removes the related value as in the example below:
# Creating a Dictionary
Dict = {1: ‘JavaTpoint’, 2: ‘Paul’, 3: ‘Thompson’}
# Deleting a key
# using pop( ) method
Pop_ele = Dict.pop(3)
Print(Dict)
Output:
{1: 'JavaTpoint', 2: 'Paul’}
In Python, there are built-in methods such as popitem( ) methods and clear ( ) methods
for removing factors from the glossary.
Popitem methods remove arbitrary elements from a dictionary. Also, the clear( ) feature
removes all elements from the whole Python dictionary.
How to Iterate Dictionary
You can use a loop for iterating a dictionary. Look at the example
# Using for loop to print all the keys of a dictionary.
Employee = {“Name”,: “James”, “Age”: 29, “salary”: 25000, “Company”:
“GOOGLE”
Output:
Name
Age
Salary
Company
Output
Name James
Age 30
Salary 35000
Company GOOGLE
The second method is a situation where the keys are not mutable objects. Strings,
tuples, and numbers could form the key. However, lists are considered as mutable
objects and not useful as the keys in the dictionary. For example:
Employee = {“Name”: “John”, “Age”: 29, “salary” 35000, “Company”:”GOOGLE”,
[100,201,301]:”Department ID”}
For x,y in Employee.items ( ):
Print(x,y)
Output
Traceback - recent call last:
File “dictionary.py”, line 1, in
Employee = {“Name”: “James” , “Age”: 30, “salary”:25000, “Company”: “GOOGLE”,
[100,201,301]:”Department ID”}
TypeError: unhashable type: ‘list’
Looking at the methods and functions of the built-in dictionary in Python programs
include
Strings are handled as a sequence of characters. In other words, Python doesn't agree
with the letter data-type. Therefore, one letter represented as 'p' can be handled like
the string of the first length.
Output:
Hello Python
Hello Python
Triple quotation marks are generally used to represent docstrings or multiline
strings.
HE L L O
0 1 2 3 4
str[0] = ‘H’
str[1] = ‘E’
str[2] = ‘L’
str[3] = ‘L’
str[4] = ‘O’
Now, you can also check this example below.
Str = “HELLO”
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# this is returning the indexError because 6th index doesn’t exist
print(str[6])
Output:
H
E
L
L
O
IndexError: string index is out of normal range
As shown in the example above, the individual characters of the string can be
accessed using the slice operator [ ]. Meanwhile, the substring could be obtained using
the colon operator (: ) in Python.
Look at this example:
Str = "HELLO"
HE L L O
0 1 2 3 4
In these examples, you can see that the higher series given in the slice operator is
exclusive at all times. That is if str (string) = 'HELLO' is given. Then, str [1:3] will have
str - string[1] = ‘E’ and str[2] = ‘L’ with nothing else attached.
Check this example
# Given String
Str = “JAVAPOINT”
# Begin 0th index to the end
print(str[0:])
# Begins 1th index to the 4th index
Print(str[1:5])
# Begins 2nd Index to the 3rd index
Print(str[2:4])
# Begins 0th index to 2nd index
Print(str[:3])
# Begins 4th index to 6th index
print(str[4:7])
Output:
JAVATPOIN
T
AVAT
VA
JAV
TPO
Negative cutting in the sequence begins from the rightmost character. This is indicated
as -1while the second rightmost character is shown as -2, and it continues in that order.
Look at this figure below.
Str = "HELLO"
HE L L O
-5 -4 -3 -2 -1
Str[-1] = ‘O’ str[-3:-1] = ‘LL’
Str[-2] = ‘L’ str[-4:-1] = ‘ELL’
Str[-3] = ‘L’ str[-5:-3] = ‘HE’
Str[-4] = ‘E’ str[-4:] = ‘ELLO’
Str[-5] = ‘H’ str[::-1] = ‘OLLEH’
Output:
T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range
Output:
Traceback - recent call last
File "10.py", line 2, in <module>
Str - String[0] = “h”;
TypeError: 'str' or ‘string’ object doesn’t hold up item assignment
In this sample, the (str) string can be transferred completely to a new content. Look at
this second example:
str = "HELLO"
print(str)
str = “hello
print(str)
Output:
HELLO
Hello
Output:
TypeError: 'str' object doesn't support the deletion of item
Output:
NameError: name ‘str1’ is not defined
Output:
HelloHelloHello
Hello world
O
II
False
False
C://python37
The string str :
Hello
If we need to write a text such as, He said, “Hello, where are you going?” This
expression could be written in single or double-quotes. This will raise the SyntaxError
in both quotes.
Let us check out this example.
str = “He said, “Hello where are you going?””
print(str)
Output:
SyntaxError: invalid syntax
This error could be handled using the triple quotes, although Python has an escape
sequence. The escape sequence is represented with a backslash (/). If this is followed
by a unique character, it is interpreted differently. In other words, the single quotes in
the string must be escaped, and this pattern can happen in double-quotes.
For example
# using triple quotes
print(“””He said, “Who are you?”””
# How to escape single quotes
print(‘He said, “What\’s happening?””)
# How to escape double quotes
print(“He said, \”What’s happening?\””
Output:
He said, “Who are you?”
He said, “What’s happening?”
He said, “What’s happening?”
Here is a list of escape sequence in Python
S/ Escape Description Examples
N Sequence
1. \’ Single Quotes Print(‘\’’)
Output: ‘
2. \a ASCII Bell Print(“\a”)
3. \\” Double Quotes Print(“\””)
Output: “
4. \\ Backlash Print(“\\”)
Output: \
5. \b ASCII Print(“Hello \b World”)
Backspace (BS) Output: Hello World
6. \newline This ignores the print(“Python1 \ Python2 \ Python3”)
line Output: Python1 Python2 Python3
7. \r ASCII Carriege print(“Hello \r World!”)
Return (CR) Output: World!
8. \n ASCII Linefeed print(“Hello\n World!”)
Output: Hello, World!
9. \f ASCII Formfeed print(“Hello \f World!”)
Hello World!
10. \xHH Character or print(“\x48\x5\x6c\6c\x6f”)
letter with hex Output: Hello
value
11. \v ASCII Vertical print(“Hello \v World!”)
Tab Output: Hello, World!
12. \t ASCII Horizontal print(“Hello \t World!”)
Tab Output: Hello, World!
13. \ooo The character or print(“\110\145\154\154\157”)
letter with octal Output: Hello
value
A python list is used for storing the sequence of different types of data. Lists are
mutable in Python. That means the elements can be modified after it is created. There
are six different types of data used for storing sequences. However, lists are accessible
and reliable types of data in Python.
Therefore, a list is a collection of items or values of various types. These items are
separated with a comma but enclosed with [ ] square brackets.
This definition could be explained further, as shown below:
L1 = [“James”, 102, “USA]
L2 = [1, 2, 3, 4, 5, 6]
I can print L1, L2, and L3 using type( ) functionality to make it a list. This will become
print(type(L1))
print(type(L2))
Output:
<class ‘list’>
<class ‘list’>
Features of Lists
Output:
False
List1 and list2 contain the same elements. However, the second list altered the index
point of the fifth element. This process breaks and abuses the order of lists. Therefore,
in comparison, both lists return the false.
In Python, lists uphold the sequence of elements for a lifetime making it the
prearranged and structured assortment of objects.
a = [1, 2, “Paul”,4.50,”Richard”,5,6]
b = [1, 2, “Paul”, 4.50,Richard”,5.6]
a==b
Output:
True
Output:
printing employee data …
Name : James, ID: 10, Country: USA
Printing departments …
Department 1:
Name: CS, ID: 11
Department :
Name: IT, ID: 11
HOD Details ….
CS HOD Name: Mr. Henry, Id: 10
IT HOD Name: Mr. Benson, Id: 11
<class ‘list’> <class list’> <class list> <class ‘list’> <class ‘list’>
The above example consists of lists of employees and departments with other
corresponding information. You may go through the table above for a better
understanding.
str = “Joseph”
s = list(str)
print(type(s))
<class list>
d. cmp(list1,list2) – for comparing all the factors of both lists but cannot work
in Python3.
e. min(list) – restores the lowest element of a list sequence. For example L1
= [12,34,266,48,72]print(max(L1))72
List1 = [1,2,2,3,55,98,65,65,13,29]
# Declare an empty list that will store unique values.
List2 = [ ]
For i in list1:
if i not in list2:
list2.apend(i)
print(list2)
Output:
[1, 2, 3, 55, 98, 65, 13, 29]
Multiple assignments are also known as tuple unpacking, as they are commonly used
with tuples. However, multiple tasks could be used with any iterable and not just tuples.
>>> x, y = ‘hi’
>>> x
‘hi’
>>> y
‘i’
As I explained before, objects that can be looped over are unpacked with multiple
assignments or tuple unpacking.
Let’s consider another pattern for demonstrating that multiple assignments function
with variables and other items including objects.
>>> point = 10, 20, 30
>>> x, y, z = point
>>> print(x, y, z)
10 20 30
>>> (x, y, z) = (z, y, x)
>>> print (x, y, z)
30 20 10
On the last line, we swapped variable names. This is something multiple assignments
allows you to do quickly.
Multiple assignments can improve the legibility of your codes and the accuracy of such
codes. That means it can make the code more descriptive with embedded statement
about the size and shape of the iterables for unpacking.
Summary of Functions
In Python, functions are blocks of organized and reusable codes used for performing
single-related actions. They provide better modality for your software with a greater
level of code reusing.
Python comes with various integrated functionalities such as print ( ) functions, type ( )
functions, etc. However, define and create your tasks by customizing your software
according to the projects you have at hand. These are known as user-defined
functions.
Parameters have a positional performance by default. That means you should place
them serially as they were defined.
An Illustration is
def printme( str ):
“This prints a passed string into this function”
print str
return
You can define a function and give it a name. With this, you can specify the parameters
to be embedded in the function, and also structure the blocks of letters. If you finalize
the basic structure of a task, you can execute it by calling it from another feature. This
process is done by following the prompt from Python.
Output:
<class ‘int’>
<class ‘float’>
(8+3j)
True
Integers can have any length in an expression. A floating-point number is only accurate
if it has 15 decimal places. If you notice a 16th decimal place, the expression is not
correct.
These numbers have decimal numbers in base ten number system. Programmers
usually work with binary (base 2) numbers and base 16 (hexadecimal) numbers. They
can also work with base 8 (octal) numbers.
You can place a prefix before the numbers to represent numbers in Python.
Prefixes Used for Numbering Systems
S Number Prefix
/ System
N
1 Binary ‘0B’ / ‘0b’
. Numbers
2 Octal ‘0O’ / ‘0o’
. numbers
3 Hexadeci ‘0X’
. mal / 0x
numbers
Output:
Run the program, you will have an output such as:
107
253
13
This result implies that floating-point numerals are executed in computer hardware like
binary fractions. This is the only type of figure the computer system understands:
binary numbers 0 and 1 . Therefore, it will be complicated to store decimal fractions in
your computer system.
For instance, the fraction 2/6 cannot be represented in a computer as a decimal
number. It will give us 0.33333333….. and this result is long. But the answer can be
approximated.
However, the decimal fraction 0.1 will give us an incredibly long binary fraction of
0.0001100110011001100 …But there are the highest numbers of figures that the
computer can accept and store. For this reason, we can approximate 0.1, and it cannot
be equal. It is worthy of note that this shortfall is not an error from Python but due to
limitations of the computer hardware.
>>> 1.1 + 2.2
3.300000000000003
But, you can handle this discrepancy using the module for decimals built-into Python.
Floating-point numbers have precision up to fifteen decimal places. It has a decimal
module with user-settable accuracy.
The difference between both results will show:
import decimal
print(0.1)
print(decimal.Decimal(0.1))
Output:
0.1
0.100000000000000055511151231257827021181583404541015625
You can use this module to perform the decimal calculations as we learned in the
school. This format maintains the significance of values.
Output:
List containing multiple values:
Books
Books
Multi-Dimensional List:
[[ ‘Books’ , ‘For’], [ ‘Books’]]
Dictionary
In Python, the dictionary is an unorganized compilation of data values for storing
values and characters like a map. Therefore, unlike different data types holding only a
one value as an element, a dictionary contains the key:value pair. This is used for
optimizing a dictionary. In a dictionary, each key-value pair is separated using a colon
(: ). But each key in Python is divided by a comma (,).
For example:
# Python program to demonstrate
# dictionary
#creating a Dictionary
# with Integer Keys
Dict = {1: ‘Books’ , 2: ‘For’ , 3: ‘Books’}
print(“Dictionary with the use of Integer Keys: “)
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {‘Name’ : ‘Books’ , 1: [1, 2, 3, 4]}
print(“\nDictionary with the use of Mixed Keys: “)
print(Dict)
Output:
Dictionary with the use of Integer Keys:
{1: ‘Books’ , 2: ‘For’ , 3: ‘Books’ }
{1: [1, 2, 3, 4], ‘Name’ : ‘Books’}
What is a Module?
A module is a file with Python statements and definitions. It is also a
Python code sourced from other programs. Modules are used for
everyday tasks, and you don’t have to enter them in every program
where you could use them.
You can call a package module using “matplotlib.plot.” Without this
module, you must state the functions of the plot in every program
where a plot graph is used.
In Python documentation, if you exit from Python interpreter and
open the software again, the definitions, which are variables and
functions, are lost. But writing a more extended program requires
you to use a text editor in preparing the data for the interpreter.
Then, run the file as input.
This process is known as scripting. Splitting long programs into
several files is recommended to maintain the application. Apply a
handy function written for several applications. In this case, you don’t
need to copy the description into all programs before working.
Python can help you arrange descriptions in a folder or file and apply
them in a script. It could also be used in a relational occasion of the
interpreter. Data organized in that manner are called modules . The
descriptions from a module are extracted into different modules or
the main module. This is a collection of variables, which you can
access in a script. They can be performed at the upper level or in the
calculator mode.
From the analysis above, you can understand that it takes class
creation and features to transfer an instance from the program into a
specific class. You can apply this function in your current program
just by working and referencing this newly created module.
Summary of what we did above:
Libraries in Python
Features of Matplotlib
Requests Library
This is released under the Apache2.0 license and serves as a
loaded Python HTTP library. It helps to make HTTP requirements
user-friendly and responsive. This lib is made for beginners to help
them to use most features of HTTP. It is easy to configure,
customize, authorize, and inspect HTTP requests.
Features of Requests Library
Theano Library
Theano could be used for compiling available computer programs.
Programmers also call it an optimizing compiler. This library applies
multi-dimensional arrays, making you not to about the outcome and
perfections of your projects.
It is designed for describing, analyzing, influencing, and optimizing
various Mathematical operations simultaneously.
Keras Library
Keras is suitable for beginners or programmers learning deep neural
networks. It is an open-source, profound neural network library
printed in Python. This is a user-friendly library with a better modular
structure providing proper inspection policy for detailed networks.
Fire Library
Fire library can generate command-line interfaces (CLIs) instantly.
This is an open-source Python library requiring less shapes of code.
It is a dominant library capable of deriving CLIs from any object in
Python. Google also applies it to creating a command line. It is
relevant for developing various experiment board paraphernalia.
Arrow Library
This is a practical and user-friendly library in Python that functions
with times and dates. It features a smart API that supports general
schemes making it an exciting library. The library is well-suited for
beginners with a basic knowledge of coding.
TensorFlow Library
This is a free, open-source machine learning collection in Python.
TensorFlow contains a handful of useful tools, which are easy to
learn. This library is relevant for different programs and dataflow.
Before using TensorFlow in a computer device, install Colab
Notebooks in the browser.
Features of TensorFlow
These include
You can easily use files and the internet on your Pi. This will allow
you to complete tasks and handle multiple projects on a virtual basis.
Some of the ways to accomplish this are:
Deleting Files
Deleting a file is simple using the rm command . To delete the file
you created above, just type rm before the file name on your window,
and the data are removed.
pi@new-hostname – $ rm textfile.txt
GUIs on Raspberry Pi
The first step is to import the module, such as Tkinter and functools,
from partial. Then, create the main window. Add the desired amount
of widgets to the basic window, such as labels, buttons, and entry.
At this stage, display the message. Lastly, apply an event prompt on
the widgets.
A brief explanation of the fifteen widgets found in TKinter include
The Spinbox
This is an alternative of the usual Tkinter Entry widget used for
selecting a fixed number of elements.
The Syntax of Spinbox
The simple syntax for creating this widget involves
W = Spinbox( master, selection, … )
The Parameters for Spinbox include
The requirements for lead fader projects are fader, software, and
soldering. Others include 1 heat shrink tube, 1 twin cable, 2 3.5mm
Mono plug, wire strippers, nippers, solder-sucker, multimeter, clipped
cables, and helping hands.
These requirements can function only on variable resistor type
faders but not on the optical type.
Now, a Fader is sourced from a broken mixing console and
electronic components store. Some local electronic component
stores include Digi-Key, RSin, Maplin, Tokyu-Hands, and
RadioShack.
PROJECTS IN RASPBERRY PI
This project demands that you use a choice Pi board with a built-in
wireless support. You can also use a Wi-Fi dongle for this project.
Another essential hardware choice for this project is the BME280
sensor. This device can help you to analyze pressure, humidity,
temperature, anemometer, wind vane, and rain gauge.
You also need other common prototyping tools, including a 3D
printer for crafting purposes. The Oracle Raspberry Pi Weather
Station Software could be used for leveraging various Python API in
the system.
Beginners find this project an interesting one, as it helps them in
collecting and analyzing atmospheric data. Also, this will boost your
experience in using Pi projects. Apply sensors and Python libraries
of choice to control their functions.
Building a Bot
A Bot is a web software developed and designed on a Pi board. Go
to the Twitter APIs and register a twitter application. Then, install and
write the bot on your device using the programming language. Using
the Twython documentation is recommended for the best
performance and efficiency for the API bit.
After this, automate the bot. This process will cause it to upload the
CPU temperature of your Pi if it spreads to a certain temperature
threshold.
If you are an open-source enthusiast, this project can help you to
explore the Twitter API. You can use this method to build a personal
twitter bot. This is the recommended Raspberry Pi projects.
With this device, you can design a motion capture security device. It
is an HD surveillance camera system that can capture live videos
and imageries if people or objects cross the monitored environment.
A standard camera is used for time-lapse projects, or any other one
could be used for this project. Most persons build this security
apparatus for monitoring their driveways or checkmating on their
dogs while they are away.
Do a live stream of the videos using any mobile devices or from a
browser. This camera can record motions and images into a video
doc automatically or on-demand. However, you should operate the
camera through the Pi camera module.
Motion detection software could be used for configuring the system
through the motion capture functionality.
Some programmers configure their devices to send notifications to
them whenever suspicious images are captured or recorded for
examination.
CHAPTER TEN
Cwide = 520
Chigh = 333
function love.load( )
love.graphics.setBackgroundColor(177, 106, 248)
-- font = love.graphics.setNewFont(“SkirtGirl.ttf” , 72)
end
function love.draw( )
love.graphics.setColor(255, 33, 78)
love.graphics.print(“Hello World”, cwide/4, chigh/3.33)
end
Then, launch the app after creating the extension. This should be
like this:
$ love ./hello.love
This will give you an out, such as:
“HELLO, WORLD!”
This is an understandable code. The cwide and chigh variables are
universal and could be seen in the whole script.
The first block of code is called a function that sets the background
shade of the program. The second block of code gets the “hello
world!” printed on the screen.
The line containing two dashes (--) is the comment section. It also
includes a .ttf in the .love package . This leads to the new line text
setNewFont with no comment. In this case, you should not use the
Skirt Girl font. Get a font from FontLibrary.org . This will enable you
to adjust the codes accordingly. You will now have codes such as:
$ zip hello.love main.lua SkirtGirl.ttf
a. Minetest
b. Widelands
c. Duke Nukem 3D
d. Beneath a Steel Sky
e. Micropolis
f. Freeciv
g. Which-Way-Is-Up?
h. Openrena
i. Quake III Arena.
j. Star Wars by Jedi Knight
k. Battle for Wesnoth.
l. Funny Boat
m. Littlecrane
n. Flight of the Amazon Queen.
o. Abuse
p. SuperTux
q. Angry Drunken Dwarves.
r. RailWorld
s. PyDance
t. OpenTTD
u. Simutrans
v. Quake 3 “other”
w. Monsterz
x. PrBOOM, and more.
Pygame and Hello pygame
Pygame means a Primer on Game. This is game programming in
Python. If you understand the pygame as a programmer, use it in
writing games on every platform and language quickly.
This is a Python covering for SDL library. It means Simple
DirectMedia Layer, which provides cross-platform accessibility for
your Pi’s system underlying multimedia hardware components.
These components include a keyboard, joystick, video, sound, and
mouse.
Pygame began as a substitute for the PySDL project. This program
comes with a cross-platform nature convenient for pygame and SDL.
In other words, you can write games and other python programs on
any platform that supports these applications.
Hello, pygame is another version of pygame.
Software
Raspberry Pi Robots
a. 2 five-volt DC motors.
b. 6 AA batteries in a holder – for powering the motors.
c. Small breadboard – a device for building simple circuits
without soldering.
d. Sticky tack adhesive.
e. Chassis - a flat and squared material measuring 6 inches,
such as laser-cut plastic, legos, and cardboard.
Additional two feet are needed for stabilizing the droid.
f. L293D motor controller.
g. Two wheels with grippy rubber tires – these tires snap
onto the motor shafts.
h. 5-volt USB mobile phone battery pack – for powering the
Pi device.
i. Jumper wires for connecting all the equipment.
j. microSD card – for loading the BOT’s software before it
can function.
You can also view at the simple 10-line Python program in the
terminal with this command:
nano first_move.py
This command will open the code in Nano, which is Pi’s native text
editor.