Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

CHAPTER 1

INTRODUCTION

1.1 Raspberry Pi
The Raspberry Pi is a low cost, credit-card sized computer that plugs into a
computer monitor or TV and uses a standard keyboard and mouse. It is a capable little
device that enables people of all ages to explore computing, and to learn how to program
in languages like Scratch and Python. It’s capable of doing everything you’d expect a
desktop computer to do, from browsing the internet and playing high-definition video, to
making spreadsheets, word-processing, and playing games.

What’s more, the Raspberry Pi can interact with the outside world and has been
used in a wide array of digital maker projects, from music machines and parent detectors
to weather stations and tweeting birdhouses with infra-red cameras.

1.1.1 Operating System


The main operating system for the Raspberry Pi is Raspbian and is based on
Debian. It is a distribution of Linux.

Even though the main supported operating system is Raspbian, you can install
other operating systems. Some examples of operating systems you can install include
Ubuntu mate, Ubuntu Core, OSMC, RISC OS, Windows 10 IoT, and much more.

1.1.2 Raspberry pi versions


1.1.2.1 Raspberry Pi A+
The Raspberry Pi A+ is the low spec and cost version of the Pi. This version only
has one USB port, lower power consumption, no Ethernet port, and only 256mb of ram.
The latest version has 512mb RAM.

This version of the Pi is better suited for projects that don’t require a considerable
amount of processing power and will benefit from the lighter weight and smaller size.A
ton of things can be done with this board such as robotics, remote control planes, remote

1
control cars, and embedded projects. To name a few examples, it would make for a great
robot brain, touch screen car dashboard, motion-sensing camera, and much more.

Read more on the Raspberry Pi A+

fig 1.1: Raspberry Pi A+

1.1.2.2 Raspberry Pi B+
Raspberry Pi B+ and B are old versions of the Pi that has now been replaced by the Pi 2.
The B+ version features a single-core CPU, 4 USB ports, microSD card slot, and lower
power consumption.

fig 1.2: Raspberry Pi B+

2
1.1.2.3 Raspberry Pi 2
The Raspberry Pi 2 is the second major generation of the Pi. This Pi and the
version B+ are one of the most popular versions you will find around due to the
processing power and number of ports you get on with it.

The Pi 2 is the replacement of the B+ and features a 900MHz quad-core CPU and
1GB of ram. The rest of the specs remain the same as what you will find in the previous
model. This version of the Pi has now been replaced by the more powerful Pi 3 and 4.

fig 1.3: Raspberry Pi 2


Read more on the Raspberry Pi 2

1.1.2.4 Raspberry Pi 3
The Raspberry Pi 3 is the second latest version of the Pi and beats version 2 in
performance and features. This version offers a few extras that make using a Pi so much
easier.
This version of the Pi brings with it a new CPU that clocks in at 1.2Ghz and is 64
bit.
The Pi also has onboard Wi-Fi (802.11n) and Bluetooth 4.1.

3
You can also get the Raspberry Pi 3 B+ which has a few slight upgrades but not
as many as the new Pi 4.

fig 1.4: Raspberry Pi3

1.1.2.5 Raspberry Pi 4
The Raspberry Pi 4 is the latest version of the Raspberry Pi family and is by far
the best board yet. It’s had quite a few upgrades to the hardware which makes it far
superior to the previous generation.

This version brings with it a 1.5GHZ quad-core ARM Cortex-A72. There are also
more RAM options for this Raspberry Pi. For example, you can choose between the
classic 1gb version, 2gb, and 4gb.
Many more improvements make this a board super appealing for enthusiasts and
casual users. The 4gb makes it a very viable desktop computer replacement.
A full list of all the new bits and pieces in the Raspberry Pi 4 is listed below.
• A 1.5GHz quad-core 64-bit ARM Cortex-A72 CPU (Roughly 3× performance)
• 1GB, 2GB, or 4GB of LPDDR4 SDRAM
• Full-throughput Gigabit Ethernet
• Dual-band 802.11ac wireless networking
• Bluetooth 5.0
• Two USB 3.0 and two USB 2.0 ports
• Dual monitor support, at resolutions up to 4K
• VideoCore VI graphics, supporting OpenGL ES 3.x

4
• 4Kp60 hardware decode of HEVC video
• Complete compatibility with earlier Raspberry Pi products

fig 1.5: Raspberry pi 4

1.2 Python
Python is a cross-platform programming language, which means that it can run on
multiple platforms like Windows, macOS, Linux, and has even been ported to the Java
and .NET virtual machines. It is free and open source.

Even though most of today's Linux and Mac have Python pre-installed in it.
1.2.1 Install Python
We can install and run Python on our computer by:

1. Download the latest version of Python.


2. Run the installer file and follow the steps to install Python
During the install process, check Add Python to environment variables. This
will add Python to environment variables, and you can run Python from any part
of the computer.
3. Also, we can choose the path where Python is installed.

5
fig 1.6: Installing Python on Computer

1.2.2 Run Python in the Integrated Development Environment (IDE)


We can use any text editing software to write a Python script file.

We just need to save it with the .py extension. IDE is a piece of software that
provides useful features like code hinting, syntax highlighting and checking, file
explorers, etc. to the programmer for application development.

By the way, when Python is installed, an IDE named IDLE is also installed. It can
be used to run Python on your computer. It's a decent IDE for beginners.

When IDLE is opened, an interactive Python Shell is opened.

6
fig 1.7: Python IDLE installed along with Python

Now a new file can be created and can be saved with .py extension. For example,
hello.py . Write Python code in the file and save it. To run the file, go to Run > Run
Module or simply click F5.

fig 1.8: Running the python program on IDLE

7
CHAPTER 2
ADVANTAGES, APPLICATIONS & LIMITATIONS OF
RASPBERRY PI

2.1 Advantages of Raspberry Pi


Although Raspberry Pi is as small as the size of a credit card, it works as if a
normal computer at a relatively low price. it is possible to work as a low-cost server to
handle light internal or web traffic. Grouping a set of Raspberry Pi to work as a server is
more cost-effective than a normal server. If all light traffic servers are changed into
Raspberry Pi, it can certainly minimize an enterprise’s budget.

2.2 Applications of Raspberry Pi

• Arcade Machine
• Tablet Computer
• Internet radio
• Controlling Robots
• Home Automation

2.3 Limitations
The memory of Raspberry Pi is limited than you’re probably used to, with just
512MB or 256MB available.

You can’t expand that with extra memory in the way you can a desktop PC.

8
CHAPTER 3

BASIC PYTHON

3.1 What is Python?

Python is a popular programming language. It was created by Guido van Rossum,


and released in 1991.

It is used for:

1. web development (server-side),


2. Software development
3. Mathematics
4. System scripting
5. Basic program of python:

# python to check if a number is prime or not

num=401

if num>1:

# check for factors

for i in range(2,num);

if (num%1)==0;

print(num, "is not a prime number")

print(i, "times", number//i, "is", num)

break

else:

print(num, "is a prime number")

# if input number is less than or equal to 1,it is not prime

else:

print(num, "is not a prime number"

9
3.1.1 Difference between Python and Java

Python: Python is a high-level, interpreted programming language. It was


invented back in 1991, by Guido Van Rossum. Python is an object-oriented programming
language that has large enormous library support making the implementation of various
programs and algorithms easy. Its language constructs and object-oriented approach aims
to help programmers to write clear, logical code for various projects.

Java: Java is a high-level, object-oriented programming language which was


originally developed by James Gosling at Sun Microsystems in 1995. Java has a syntax
similar to C and C++ but with low-level difficulties. Java is platform-independent
(WORA – Write Once Run Anywhere) meaning compiled java code can run on different
platforms without recompilation.

3.2 Why Python?

1. Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.).
2. Python has a simple syntax like the English language.
3. Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
4. Python runs on an interpreter system, meaning that code can be executed as soon
as it is written. This means that prototyping can be very quick.
5. Python can be treated in a procedural way, an object-oriented way or a functional
way.

3.2.1 Python Syntax compared to other programming languages:

1. Python was designed for readability and has some similarities to the English
language with influence from mathematics.
2. Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.

10
Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly brackets for
this purpose.

3.3 Python Keywords

Keywords are the reserved words in Python.

We cannot use a keyword as a variable name, function name or any other


identifier. They are used to define the syntax and structure of the Python language. In
Python, keywords are case sensitive.

There are 33 keywords in Python 3.7. All the keywords


except True, False and None are in lowercase and they must be written as they are. The
list of all the keywords is given below.

3.4 Python Identifiers

An identifier is a name given to entities like class, functions, variables, etc. It


helps to differentiate one entity from another.

3.4.1 Rules for writing identifiers

1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to


Z) or digits (0 to 9) or an underscore _. Names
like myClass, var_1 and print_this_to_screen, all are valid example.

2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid
name.

3. Keywords cannot be used as identifiers


4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.

5. An identifier can be of any length.

11
3.4.2 Things to Remember
Python is a case-sensitive language. This means, Variable and variable are not the
same.Always give the identifiers a name that makes sense. While c = 10 is a valid name,
writing count = 10 would make more sense, and it would be easier to figure out what it
represents when you look at your code after a long gap.

Multiple words can be separated using an underscore, like this_is_a_long_variable.

3.5 Statements and Comments


3.5.1 Python Statement
Instructions that a Python interpreter can execute are called statements. For
example, a = 1 is an assignment statement. if statement, for statement, while statement,
etc. are other kinds of statements which will be discussed later.

3.5.2 Multi-line statement


In Python, the end of a statement is marked by a newline character. But we can
make a statement extend over multiple lines with the line continuation character (\). For
example:
a=1+2+3+\
4+5+6+\
7+8+9
This is an explicit line continuation. In Python, line continuation is implied inside
parentheses ( ), brackets [ ], and braces { }. For instance, we can implement the above
multi-line statement as:
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is
the case with [ ] and { }. For example:
colors = ['red',

12
'blue',
'green']
We can also put multiple statements in a single line using semicolons, as follows:

a = 1; b = 2; c = 3

3.5.3 Python Indentation


Most of the programming languages like C, C++, and Java use braces { } to
define a block of code. Python, however, uses indentation.
A code block (body of a function, loop, etc.) starts with indentation and ends with
the first unindented line. The amount of indentation is up to you, but it must be consistent
throughout that block.
Generally, four whitespaces are used for indentation and are preferred over tabs.
Here is an example.

for i in range(1,11):
print(i)
if i == 5:
break
The enforcement of indentation in Python makes the code look neat and clean.
This results in Python programs that look similar and consistent.
Indentation can be ignored in line continuation, but it's always a good idea to
indent. It makes the code more readable.

3.5.4 Python Comments


Comments are very important while writing a program. They describe what is
going on inside a program, so that a person looking at the source code does not have a
hard time figuring it out. You might forget the key details of the program you just wrote
in a month's time. So, taking the time to explain these concepts in the form of comments
is always fruitful.
In Python, we use the hash (#) symbol to start writing a comment. It extends up to
the newline character. Comments are for programmers to better understand a program.
Python Interpreter ignores comments.

13
#This is a comment
#print out Hello
print('Hello')

3.5.4.1 Multi-line comments


We can have comments that extend up to multiple lines. One way is to use the
hash(#) symbol at the beginning of each line. For example:
#This is a long comment
#and it extends
#to multiple lines
Another way of doing this is to use triple quotes, either ''' or """.These triple
quotes are generally used for multi-line strings. But they can be used as a multi-line
comment as well. Unless they are not docstrings, they do not generate any extra code.

"""This is also a
perfect example of
multi-line comments"""

3.6 Python Variables


A variable is a named location used to store data in the memory. It is helpful to
think of variables as a container that holds data that can be changed later in the program.
For example,
number = 10
Here, we have created a variable named number. We have assigned the
value 10 to the variable.
number = 10
number = 1.1
Initially, the value of number was 10. Later, it was changed to 1.1.
Note: In Python, we don't assign values to the variables. Instead, Python gives the
reference of the object(value) to the variable.

14
Assigning values to Variables in Python
assignment operator = can be used to assign a value to a variable.
Example 1: Declaring and assigning value to a variable
website = "xyz.com"
print(website)
Output
xyz.com
In the above program, we assigned a value apple.com to the variable website.
Then, we printed out the value assigned to website i.e. xyz.com
Example 2: Changing the value of a variable
website = "xyz.com "
print(website)
# assigning a new value to website
website = "abc.com"
print(website)
Output
xyz.com
abc.com
In this , we have assigned xyz.com to the website variable initially. Then, the value is
changed to abc.com

3.7 Rules and Naming Convention for Variables and constants


1. Constant and variable names should have a combination of letters in lowercase (a
to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_). For example:
snake_case
MACRO_CASE
camelCase
CapWords

15
2. Create a name that makes sense. For example, vowel makes more sense than v.
3. If you want to create a variable name having two words, use underscore to
separate them. For example:
my_name
current_salary
4. Use capital letters possible to declare a constant. For example:
PI
G
MASS
SPEED_OF_LIGHT
5. Never use special symbols like !, @, #, $, %, etc.
6. Don't start a variable name with a digit.

3.8 Python Input, Output and Import


Python provides numerous built-in functions that are readily available to us at the
Python prompt. Some of the functions like input() and print() are widely used for
standard input and output operations respectively.

Python Import
When our program grows bigger, it is a good idea to break it into different
modules.
A module is a file containing Python definitions and statements. Python
modules have a filename and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive
interpreter in Python. We use the import keyword to do this.
For example, we can import the math module by typing the following line:
import math
We can use the module in the following ways:
import math
print(math.pi)

16
Output

3.141592653589793
Now all the definitions inside math module are available in our scope. We can
also import some specific attributes and functions only, using the from keyword. For
example:
>>> from math import pi
>>> pi
3.141592653589793
While importing a module, Python looks at several places defined in sys.path. It is
a list of directory locations.
>>> import sys
>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']
We can also add our own location to this list.

3.9 Python Operators


Operators are special symbols in Python that carry out arithmetic or logical
computation. The value that the operator operates on is called the operand.
For example:
>>> 2+3
5
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output
of the operation.

17
3.9.1 Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc.

Example 1: Arithmetic operators in Python


x = 15
y=4

# Output: x + y = 19
print('x + y =',x+y)

# Output: x - y = 11
print('x - y =',x-y)

# Output: x * y = 60
print('x * y =',x*y)

# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
Output
x + y = 19
x - y = 11
x * y = 60
x / y = 3.75

18
x // y = 3
x ** y = 50625

Example 2: Comparison operators in Python


x = 10
y = 12
# Output: x > y is False
print('x > y is', x>y)

# Output: x < y is True


print('x < y is', x<y)

# Output: x == y is False
print('x == y is', x==y)

# Output: x != y is True
print('x != y is', x!=y)

# Output: x >= y is False


print('x >= y is', x>=y)

# Output: x <= y is True


print('x <= y is', x<=y)
Output
x > y is False
x < y is True
x == y is False
x != y is True

19
x >= y is False
x <= y is True

3.9.3 Logical operators


Logical operators are the and, or, not operators.

3.9.4 Bitwise operators


Bitwise operators act on operands as if they were strings of binary digits. They
operate bit by bit, hence the name.

For example, 2 is 10 in binary and 7 is 111.


In the table 2.6: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

3.9.5 Assignment operators


Assignment operators are used in Python to assign values to variables.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the
variable a on the left.

There are various compound operators in Python like a += 5 that adds to the
variable and later assigns the same. It is equivalent to a = a + 5.

3.9.6 Special operators


Python language offers some special types of operators like the identity operator
or the membership operator. They are described below with examples.

3.9.7 Identity operators


is and is not are the identity operators in Python. They are used to check if two
values (or variables) are located on the same part of the memory. Two variables that are
equal does not imply that they are identical.

20
Example 4: Identity operators in Python
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]

# Output: False
print(x1 is not y1)

# Output: True
print(x2 is y2)

# Output: False
print(x3 is y3)
Output
False
True
False
Here, we see that x1 and y1 are integers of the same values, so they are equal as
well as identical. Same is the case with x2 and y2 (strings).

But x3 and y3 are lists. They are equal but not identical. It is because the
interpreter locates them separately in memory although they are equal.

3.9.8 Membership operators


in and not in are the membership operators in Python. They are used to test
whether a value or variable is found in a sequence (string, list, tuple, set and dictionary).

In a dictionary we can only test for presence of key, not the value.

21
Example #5: Membership operators in Python
x = 'Hello world'
y = {1:'a',2:'b'}

# Output: True
print('H' in x)

# Output: True
print('hello' not in x)

# Output: True
print(1 in y)

# Output: False
print('a' in y)
Output
True
True
True
False
Here, 'H' is in x, but 'hello' is not present in x (remember, Python is case sensitive).
Similarly, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.

22
CHAPTER 4
PYTHON DATATYPES

Data types in Python


Every value in Python has a datatype. Since everything is an object in Python
programming, data types are classes and variables are instance (object) of these classes.

There are various data types in Python. Some of the important types are listed below.

4.1 Python Numbers


Integers, floating point numbers and complex numbers fall under Python numbers
category. They are defined as int, float and complex classes in Python.

We can use the type() function to know which class a variable or a value belongs
to. Similarly, the isinstance() function is used to check if an object belongs to a particular
class.

a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
Output
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True
Integers can be of any length; it is only limited by the memory available.
A floating-point number is accurate up to 15 decimal places. Integer and
floating points are separated by decimal points. 1 is an integer, 1.0 is a floating-point
number.

23
Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part. Here are some examples.

program
>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
>>> c = 1+2j
>>> c
(1+2j)
Notice that the float variable b got truncated.
4.1.1 Python Fractions
Python provides operations involving fractional numbers through
its fraction module. A fraction has a numerator and a denominator, both of which are
integers.

We can create Fraction objects in various ways.


Import fractions
print(fractions.Fraction(1.5))
print(fractions.Fraction(5))
print(fractions.Fraction(1,3))
Output
3/2
5
1/3
While creating Fraction from float, we might get some unusual results. This is due
to the imperfect binary floating-point number representation as discussed in the previous

24
section. Fortunately, Fraction allows us to instantiate with string as well. This is the
preferred option when using decimal numbers.

import fractions
# As float
print(fractions.Fraction(1.1))
# As string
# Output: 11/10
print(fractions.Fraction('1.1'))
Output
2476979795053773/2251799813685248
11/10

4.1.2 Python Mathematics


Python offers modules like math and random to carry out different mathematics
like trigonometry, logarithms, probability and statistics, etc.
import math
print(math.pi)
print(math.cos(math.pi))
print(math.exp(10))
print(math.log10(1000))
print(math.sinh(1))
print(math.factorial(6))
Output
3.141592653589793
-1.0
22026.465794806718
3.0

25
1.1752011936438014
720

import random
print(random.randrange(10, 20))
x = ['a', 'b', 'c', 'd', 'e']
# Get random choice
print(random.choice(x))
# Shuffle x
random.shuffle(x)
# Print the shuffled x
print(x)
# Print random element
print(random.random())
Output (Values may be different due to the random behavior)
18
e
['c', 'e', 'd', 'b', 'a']
0.5682821194654443

4.2 Python List


List is an ordered sequence of items. It is one of the most used datatype in Python
and is very flexible. All the items in a list do not need to be of the same type.
Declaring a list is straight forward. Items separated by commas are enclosed
within brackets [ ].
a = [1, 2.2, 'python']
We can use the slicing operator [ ] to extract an item or a range of items from a
list. The index starts from 0 in Python.

26
program
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])

# a[0:3] = [5, 10, 15]


print("a[0:3] = ", a[0:3])

# a[5:] = [30, 35, 40]


print("a[5:] = ", a[5:])
a[2] = 15
a[0:3] = [5, 10, 15]
a[5:] = [30, 35, 40]
#Lists are mutable, meaning, the value of elements of a list can be altered.
a = [1, 2, 3]
a[2] = 4
print(a)
Output
[1, 2, 4]

4.2.1 Python List Methods


Methods that are available with list objects in Python programming are tabulated
below.

27
4.2.2 List Comprehension
List comprehension is an elegant and concise way to create a new list from an
existing list in Python. A list comprehension consists of an expression followed by for
statement inside square brackets. Here is an example to make a list with each item being
increasing power of 2.

pow2 = [2 ** x for x in range(10)]


print(pow2)
Output
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
This code is equivalent to:
pow2 = []
for x in range(10):
pow2.append(2 ** x)
A list comprehension can optionally contain more for or if statements. An
optional if statement can filter out items for the new list. Here are some examples.

>>> pow2 = [2 ** x for x in range(10) if x > 5]


>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
['Python Language', 'Python Programming', 'C Language', 'C Programming']

28
4.2.3 Iterating Through a List
Using a for loop we can iterate through each item in a list.
for fruit in ['apple', 'banana', 'mango']:
print("I like”, fruit)
Output
I like apple
I like banana
I like mango

4.3 Python Tuple


Tuple is an ordered sequence of items same as a list. The only difference is that
tuples are immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than lists as they
cannot change dynamically.
It is defined within parentheses ( ) where items are separated by commas.
t = (5,'program', 1+3j)
We can use the slicing operator [ ] to extract items but we cannot change its value.
t = (5,'program', 1+3j)
# t[1] = 'program'
print("t[1] = ", t[1])

# t[0:3] = (5, 'program', (1+3j))


print("t[0:3] = ", t[0:3])

# Generates error
# Tuples are immutable
t[0] = 10
Output
t[1] = program

29
t[0:3] = (5, 'program', (1+3j))
Traceback (most recent call last):
File "test.py", line 11, in <module>
t[0] = 10
TypeError: 'tuple' object does not support item assignment

Advantages of Tuple over List


Since tuples are quite similar to lists, both are used in similar situations. However,
there are certain advantages of implementing a tuple over a list. Below listed are some of
the main advantages:
1. We generally use tuples for heterogeneous (different) data types and lists for
homogeneous (similar) data types.
2. Since tuples are immutable, iterating through a tuple is faster than with list. So
there is a slight performance boost.
3. Tuples that contain immutable elements can be used as a key for a dictionary.
With lists, this is not possible.
4. If you have data that doesn't change, implementing it as tuple will guarantee that
it remains write-protected.

4.4 Python Strings


String is sequence of Unicode characters. We can use single quotes or double
quotes to represent strings. Multi-line strings can be denoted using triple quotes, ''' or """.

Program
s = "This is a string"
print(s)
s = '''A multiline
string'''
print(s)

30
Output
This is a string
A multiline
string
Just like a list and tuple, the slicing operator [ ] can be used with strings. Strings,
however, are immutable.
s = 'Hello world!'
# s[4] = 'o'
print("s[4] = ", s[4])

# s[6:11] = 'world'
print("s[6:11] = ", s[6:11])

# Generates error
# Strings are immutable in Python
s[5] ='d'
Output
s[4] = o
s[6:11] = world
Traceback (most recent call last):
File "<string>", line 11, in <module>
TypeError: 'str' object does not support item assignment

4.4.1 Python String Formatting


Escape Sequence
If we want to print a text like He said, "What's there?", we can neither use single
quotes nor double quotes. This will result in a SyntaxError as the text itself contains both
single and double quotes.

31
>>> print("He said, "What's there?"")
...
SyntaxError: invalid syntax
Alternatively, we can use escape sequences.
An escape sequence starts with a backslash and is interpreted differently. If we
use a single quote to represent a string, all the single quotes inside the string must be
escaped. Similar is the case with double quotes. Here is how it can be done to represent
the above text.

# escaping single quotes


print('He said, "What\'s there?"')

# escaping double quotes


print("He said, \"What's there?\"")
Output:
He said, "What's there?"
He said, "What's there?"
He said, "What's there?"

4.4.2 The format() Method for Formatting Strings


The format() method that is available with the string object is very versatile and
powerful in formatting strings. Format strings contain curly braces {} as placeholders or
replacement fields which get replaced. We can use positional arguments or keyword
arguments to specify the order.

Program
# Python string format() method
# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')

32
print(default_order)

# order using positional argument


positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('\n--- Positional Order ---')
print(positional_order)

# order using keyword argument


keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')
print(keyword_order)
Output
--- Default Order ---
John, Bill and Sean

--- Positional Order ---


Bill, John and Sean

--- Keyword Order ---


Sean, Bill and John

4.4.3 Programs
Program to remove duplicates from the string
str1 = input(“Enter a string:”)
list1 = [] # empty list
for x in str1:

33
if x not in list1:
list1.append(x)
output = “”.join(list1) # empty string
print(output)
Output
>> Enter a string: Python Programming Language
>> Python rgamiLue

Program to Merge two strings into a single string


str1 = input(“Enter a string:”)
str2 = input(“Enter another string:”)
Output = “”
i=0
j=0
while i < len(str1) or j < len(str2)
output = output + str1[i]
i+=1
if j < len(str2):
output = output + str2[j]
j+=1
print(output)

output:
>> Enter a string: Hello
>> Enter another string: World
HWeolrllod

34
program to sort the characters of the given string
str1 = input(“Enter a string:”)
output = “”
s1=s2= “”
# to put alphabets in s1 and numbers in s2
for x in str1:
if x.isalpha():
s1 = s1+x
else:
s2= s2+x
# to sort alphabets in s1
for x in sorted(s1):
output = output + x
# to sort numbers in s2
for x in sorted(s2):
output = output + x
# to print the sorted output
print(output)
Output
>> Enter a string: Python Programming Language 812
>> LPPaaeggghimmnnoorrtuy 128

4.5 Python Set


Set is an unordered collection of unique items. Set is defined by values separated
by comma inside braces { }. Items in a set are not ordered.
Program
a = {5,2,3,1,4}
# printing set variable
35
print("a = ", a)

# data type of variable a


print(type(a))
Output
a = {1, 2, 3, 4, 5}
<class 'set'>
We can perform set operations like union, intersection on two sets. Sets have unique
values. They eliminate duplicates.
a = {1,2,2,3,3,3}
print(a)
Output
{1, 2, 3}
Since, set are unordered collection, indexing has no meaning. Hence, the slicing
operator [] does not work.
>>> a = {1,2,3}
>>> a[1]
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
TypeError: 'set' object does not support indexing

4.5.1 Python Set Operations


Sets can be used to carry out mathematical set operations like union, intersection,
difference and symmetric difference. We can do this with operators or methods.
Let us consider the following two sets for the following operations.
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}

36
4.5.1.1 Set Union

fig 4.1: Set Union

Union of A and B is a set of all elements from both sets.


Union is performed using | operator. Same can be accomplished using
the union() method.
Program
# Set union method
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
Output
{1, 2, 3, 4, 5, 6, 7, 8}

37
4.5.1.2 Set Intersection

fig 4.2: Set Intersection

Intersection of A and B is a set of elements that are common in both the sets.
Intersection is performed using & operator. Same can be accomplished using
the intersection() method.
Program
# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use & operator
print(A & B)
Output
{4, 5}

38
4.5.1.3 Set Difference

fig 4.3: Set difference

Difference of the set B from set A(A - B) is a set of elements that are only
in A but not in B. Similarly, B - A is a set of elements in B but not in A. Difference is
performed using - operator. Same can be accomplished using the difference() method.
Program
# Difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A
print(A - B)
Output
{1, 2, 3}

39
4.5.1.4 Set Symmetric Difference

fig 4.4: Set Symmetric Difference

Symmetric Difference of A and B is a set of elements in A and B but not in both


(excluding the intersection). Symmetric difference is performed using ^ operator. Same
can be accomplished using the method symmetric_difference().
Program
# Symmetric difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
print(A ^ B)
Output
{1, 2, 3, 6, 7, 8}

4.6 Python Dictionary


Dictionary is an unordered collection of key-value pairs. It is generally used when
we have a huge amount of data. Dictionaries are optimized for retrieving data. We must
know the key to retrieve the value.

40
In Python, dictionaries are defined within braces {} with each item being a pair in
the form key:value. Key and value can be of any type.
Program
>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>
# We use key to retrieve the respective value. But not the other way around.
d = {1:'value','key':2}
print(type(d))

print("d[1] = ", d[1]);

print("d['key'] = ", d['key']);

# Generates error
print("d[2] = ", d[2]);
Output
<class 'dict'>
d[1] = value
d['key'] = 2
Traceback (most recent call last):
File "<string>", line 9, in <module>
KeyError: 2

4.6.1 Python Dictionary Comprehension


Dictionary comprehension is an elegant and concise way to create a new
dictionary from an iterable in Python. Dictionary comprehension consists of an
expression pair (key: value) followed by a for statement inside curly braces {}.

41
Example to make a dictionary with each item being a pair of a number and its square.
# Dictionary Comprehension
squares = {x: x*x for x in range(6)}

print(squares)
Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
A dictionary comprehension can optionally contain more for or if statements. An
optional if statement can filter out items to form the new dictionary.

4.7 Conversion between data types


We can convert between different data types by using different type conversion
functions like int(), float(), str(), etc.
>>> float(5)
5.0
# Conversion from float to int will truncate the value (make it closer to zero).
>>> int(10.6)
10
>>> int(-10.6)
-10
Conversion to and from string must contain compatible values.
>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>

42
ValueError: invalid literal for int() with base 10: '1p'
We can even convert one sequence to another.
>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
To convert to dictionary, each element must be a pair:
>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}

4.8 Explicit Type Conversion


In Explicit Type Conversion, users convert the data type of an object to required
data type. We use the predefined functions like int(), float(), str(), etc. to perform explicit
type conversion .This type of conversion is also called typecasting because the user casts
(changes) the data type of the objects.

Syntax :
<required_datatype>(expression)
Typecasting can be done by assigning the required data type function to the expression.
Addition of string and integer using explicit conversion:
num_int = 123
num_str = "456"

print("Data type of num_int:",type(num_int))


print("Data type of num_str before Type Casting:",type(num_str))

43
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))

num_sum = num_int + num_str


print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))

Output

Data type of num_int: <class 'int'>

Data type of num_str before Type Casting: <class 'str'>

Data type of num_str after Type Casting: <class 'int'>

Sum of num_int and num_str: 579

Data type of the sum: <class 'int'>

In the before program,

1. We add num_str and num_int variable.

2. We converted num_str from string(higher) to integer(lower) type


using int() function to perform the addition.

3. After converting num_str to an integer value, Python can add these two variables.

4. We got the num_sum value and data type to be an integer.

44
CHAPTER 5

PYTHON FLOW CONTROL AND FUNCTIONS

5.1 if Statements

Decision making is required when we want to execute a code only if a certain


condition is satisfied. The if…elif…else statement is used in Python for decision making.

Python if Statement Syntax


if test expression:
statement(s)

Here, the program evaluates the test expression and will execute statement(s) only
if the test expression is True. If the test expression is False, the statement(s) is not
executed. In Python, the body of the if statement is indicated by the indentation. The
body starts with an indentation and the first unindented line marks the end. Python
interprets non-zero values as True. None and 0 are interpreted as False.

fig 5.1: Python if statement Flowchart

45
Example: Python if Statement

# If the number is positive, we print an appropriate message

num = 3

if num > 0:

print(num, "is a positive number.")

print("This is always printed.")

num = -1

if num > 0:

print(num, "is a positive number.")

print("This is also always printed.")

Output

3 is a positive number

This is always printed

This is also always printed.

In the above example, num > 0 is the test expression. The body of if is executed
only if this evaluates to True. When the variable num is equal to 3, test expression is true
and statements inside the body of if are executed. If the variable num is equal to -1, test
expression is false and statements inside the body of if are skipped. The print() statement
falls outside of the if block (unindented). Hence, it is executed regardless of the test
expression.

46
5.2 Python if...else Statement

The if...else statement evaluates test expression and will execute the body
of if only when the test condition is True. If the condition is False, the body of else is
executed. Indentation is used to separate the blocks.

Syntax of if...else

if test expression:

Body of if

else:

Body of else

Python if...else Flowchart

Flowchart of if...else statement in Python

fig 5.2: Python if.. else Statement Flowchart

47
Example of if...else

# Program checks if the number is positive or negative

# And displays an appropriate message

num = 3

if num >= 0:

print("Positive or Zero")

else:

print("Negative number")

Output

Positive or Zero

In the above example, when num is equal to 3, the test expression is true, and the
body of if is executed and the body of else is skipped.

If num is equal to -5, the test expression is false and the body of else is executed
and the body of if is skipped.

If num is equal to 0, the test expression is true, and body of if is executed


and body of else is skipped.

5.3 Python if...elif...else Statement

The elif is short for else if. It allows us to check for multiple expressions. If the
condition for if is False, it checks the condition of the next elif block and so on. If all the
conditions are False, the body of else is executed. Only one block among the
several if...elif...else blocks is executed according to the condition. The if block can have
only one else block. But it can have multiple elif blocks.

48
Syntax of if...elif...else

if test expression:

Body of if

elif test expression:

Body of elif

else:

Body of else

Flowchart of if...elif...else

Flowchart of if...elif....else statement in Python

fig 5.3: Python if.. elif.. else statement flowchart.

49
Example of if...elif...else

'''In this program,

we check if the number is positive or

negative or zero and

display an appropriate message'''

num = 3.4

if num > 0:

print("Positive number")

elif num == 0:

print("Zero")

else:

print("Negative number")

When variable num is positive, Positive number is printed.

If num is equal to 0, Zero is printed.

If num is negative, Negative number is printed.

50
CONCLUSION

In this paper, a comprehensive review of Raspberry Pi- A $25 small and compact credit
card sized computer is being done. Raspberry Pi, being a small form factor device has
unlimited possibilities of project development in area of embedded systems and daily
routing out of box projects. Raspberry Pi is helpful both for computer science students to
learn programming, Linux Administration and do Server Administration implementations
of Emails, Cloud and other Web Servers. For embedded systems, various interfacing like
Sensors, LED’s etc. can be interfaced via GPIO. This paper will be an eye-opener for all,
to use this device and explore for unlimited possibilities.

51
REFERENCES

[1] Warner, T. L. (2013). Hacking Raspberry Pi. Que Publishing.

[2] McManus, S. (2014). Raspberry Pi for dummies. John Wiley & Sons.

[3] https://www.raspberrypi.org/products/model-a/ (Accessed on Jan 1, 2016)

[4] https://www.raspberrypi.org/products/model-a-plus/ (Accessed on Jan 1, 2016)

[5] https://www.raspberrypi.org/products/model-b/ (Accessed on Jan 1, 2016)

[6] https://www.raspberrypi.org/products/model-b-plus/ (Accessed on Jan 1, 2016)

[7] https://www.raspberrypi.org/products/raspberry-pi-2-model-b/ (Accessed on Jan 1,


(2016)

[8] https://www.raspberrypi.org/products/pi-zero/ (Accessed on Jan 1, 2016)

[9] https://www.raspberrypi.org/blog/raspberry-pi-zero/ (Accessed on Jan 1, 2016)

[10] https://www.raspbian.org/ (Accessed on Jan 1, 2016)

52

You might also like