Professional Documents
Culture Documents
1.1.1 Operating System: 1.1.2 Raspberry Pi Versions
1.1.1 Operating System: 1.1.2 Raspberry Pi Versions
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.
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.
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.
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.
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.
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.
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
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:
5
fig 1.6: Installing Python on Computer
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.
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.
7
CHAPTER 2
ADVANTAGES, APPLICATIONS & LIMITATIONS 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
It is used for:
num=401
if num>1:
for i in range(2,num);
if (num%1)==0;
break
else:
else:
9
3.1.1 Difference between Python and Java
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.
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.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid
name.
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.
12
'blue',
'green']
We can also put multiple statements in a single line using semicolons, as follows:
a = 1; b = 2; c = 3
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.
13
#This is a comment
#print out Hello
print('Hello')
"""This is also a
perfect example of
multi-line comments"""
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
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.
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.
17
3.9.1 Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc.
# 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
# Output: x == y is False
print('x == y is', x==y)
# Output: x != y is True
print('x != y is', x!=y)
19
x >= y is False
x <= y is True
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.
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.
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
There are various data types in Python. Some of the important types are listed below.
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.
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
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
26
program
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
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.
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
# 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
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
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.
Program
# Python string format() method
# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
32
print(default_order)
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
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
36
4.5.1.1 Set Union
# 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
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
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
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))
# 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
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.
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}
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"
43
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
Output
3. After converting num_str to an integer value, Python can add these two variables.
44
CHAPTER 5
5.1 if Statements
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.
45
Example: Python if Statement
num = 3
if num > 0:
num = -1
if num > 0:
Output
3 is a positive number
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
47
Example of if...else
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.
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
Body of elif
else:
Body of else
Flowchart of if...elif...else
49
Example of if...elif...else
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
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
[2] McManus, S. (2014). Raspberry Pi for dummies. John Wiley & Sons.
52