Ilovepdf Merged

You might also like

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

1

Chapter 1-2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8
3

Chapter 1-2
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Chapter 3
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

Chapter 4
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

Chapter 5
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130

Chapter 6
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161

Chapter 7
162
163
164
165
166
167

Chapter 8
168
169
170
171
172
173
174
175
176
177
178
179
180
181
UPCISS O-Level (M3-R5)
Programming and Problem
Solving Through Python
Language

Video Tutorial
O-Level M3-R5 Full Video
Playlist Available on
YouTube Channel UPCISS

Free Online Computer Classes on


YouTube Channel UPCISS
www.youtube.com/upciss
For free PDF Notes
Our Website: www.upcissyoutube.com

Copyright © 2022 UPCISS


www.upcissyoutube.com O level M3-R5

Introduction to Programming --------------------------- 2


Algorithms and Flowcharts ------------------------------- 9
Introduction to Python ----------------------------------- 18
Python Operators ------------------------------------------ 28
Sequence Data Types ------------------------------------- 31
Python If ... Else --------------------------------------------- 42
Python Functions ------------------------------------------- 49
Python Scope ------------------------------------------------ 60
Python Modules -------------------------------------------- 62
File Processing (Handling)------------------------------- 71
NumPy Basics ------------------------------------------------ 80

1
www.upcissyoutube.com O level M3-R5

Introduction to Programming
Before we understand what programming is, you must know what a computer is. A
computer is a device that can accept human instruction, processes it, and responds
to it or a computer is a computational device that is used to process the data under
the control of a computer program. Program is a sequence of instruction along with
data.
The basic components of a computer are:
 Input unit
 Central Processing Unit(CPU)
 Output unit
The CPU is further divided into three parts-
 Memory unit
 Control unit
 Arithmetic Logic unit
Most of us have heard that CPU is called the brain of our computer because it accepts
data, provides temporary memory space to it until it is stored (saved) on the hard
disk, performs logical operations on it and hence processes (here also means
converts) data into information. We all know that a computer consists of hardware
and software. Software is a set of programs that performs multiple tasks together.
An operating system is also software (system software) that helps humans to interact
with the computer system.
A program is a set of instructions given to a computer to perform a specific operation.
Or computer is a computational device that is used to process the data under the
control of a computer program. While executing the program, raw data is processed
into the desired output format. These computer programs are written in a
programming language which are high-level languages. High level languages are
nearly human languages that are more complex than the computer understandable
language which are called machine language, or low level language. So after knowing
the basics, we are ready to create a very simple and basic program. Like we have
different languages to communicate with each other, likewise, we have different
languages like C, C++, C#, Java, python, etc. to communicate with the computers.
The computer only understands binary language (the language of 0’s and 1’s) also
called machine-understandable language or low-level language but the programs we
are going to write are in a high-level language which is almost similar to human
language.

Step 1
Variable 1001001
Step 2
if 1000111
Problem Step 3 Solve
while 1011111
Step 4
print 1000110
..

Algorithm Flowchart C, C++, Python, etc. Machine


Code

2
www.upcissyoutube.com O level M3-R5

Basic Model of Computation


Problem definition:
A problem definition involves the clear identification of the problem in terms
of available input parameters and desired solution.
Approach towards solving the problem:
After a problem is identified, the user needs to implement a step-by-step
solution in terms of algorithms.
Graphical representation of problem solving sequence:
This step involves representing the steps of algorithm pictorially by using a
flowchart. Each component of the flowchart presents a definite process to solve the
problem.
Converting the sequence in a programming language:
Converting the graphical sequence of processes into a language that the user
and the computer can understand and use for problem solving is called programming.
After the program is compiled the user can obtain the desired solution for the problem
by executing the machine language version of the program.

Algorithm
A sequential solution of any program that written in human language, called
algorithm. Algorithm is first step of the solution process, after the analysis of
problem, programmer writes the algorithm of that problem.
It can be understood by taking an example of cooking a new recipe. To cook a new
recipe, one reads the instructions and steps and execute them one by one, in the
given sequence. The result thus obtained is the new dish cooked perfectly. Similarly,
algorithms help to do a task in programming to get the expected output.
The Algorithm designed are language-independent, i.e. they are just plain
instructions that can be implemented in any language, and yet the output will be the
same, as expected.
Characteristics of Algorithm:
 Clear and Unambiguous: Algorithm should be clear and unambiguous. Each
of its steps should be clear in all aspects and must lead to only one meaning.
 Well-Defined Inputs: If an algorithm says to take inputs, it should be well-
defined inputs.
 Well-Defined Outputs: The algorithm must clearly define what output will be
yielded and it should be well-defined as well.
 Finite-ness: The algorithm must be finite, i.e. it should not end up in an infinite
loops or similar.
 Feasible: The algorithm must be simple, generic and practical, such that it can
be executed upon with the available resources. It must not contain some future
technology, or anything.
 Language Independent: The Algorithm designed must be language-
independent, i.e. it must be just plain instructions that can be implemented in
any language, and yet the output will be same, as expected.

3
www.upcissyoutube.com O level M3-R5

Advantages of Algorithms:
 It is easy to understand.
 Algorithm is a step-wise representation of a solution to a given problem.
 In Algorithm the problem is broken down into smaller pieces or steps hence, it
is easier for the programmer to convert it into an actual program.

Disadvantages of Algorithms:
 Writing an algorithm takes a long time so it is time-consuming.
 Branching and looping statements are difficult to show in Algorithms.

Example of Algorithm?
Algorithm for add two numbers entered by the user.
 Step 1: Start
 Step 2: Declare 3 variables num1, num2 and sum.
 Step 3: Read values num1 and num2.
 Step 4: Add num1 and num2 and assign the result to sum.
sum ← num1+num2
 Step 5: Print sum
 Step 6: Stop

Flowchart
Flowchart is a graphical representation of an algorithm. Programmers often use it
as a program-planning tool to solve a problem. It makes use of symbols which are
connected among them to indicate the flow of information and processing.
The process of drawing a flowchart for an algorithm is known as “flowcharting”.

Basic Symbols used in Flowchart Designs


 Terminal: The oval symbol indicates Start, Stop and Halt in a program’s
logic flow. A pause/halt is generally used in a program logic under some
error conditions. Terminal is the first and last symbols in the flowchart.

 Input/Output: A parallelogram denotes any function of input/output type.


Program instructions that take input from input devices and display output
on output devices are indicated with parallelogram in a flowchart.

 Processing: A box represents arithmetic instructions. All arithmetic


processes such as adding, subtracting, multiplication and division are
indicated by action or process symbol.

 Decision Diamond symbol represents a decision point. Decision based


operations such as yes/no question or true/false are indicated by diamond in
flowchart.

4
www.upcissyoutube.com O level M3-R5

 Connectors: Whenever flowchart becomes complex or it spreads over more


than one page, it is useful to use connectors to avoid any confusions. It is
represented by a circle.

 Flow lines: Flow lines indicate the exact sequence in which instructions are
executed. Arrows represent the direction of flow of control and relationship
among different symbols of flowchart.

Advantages of Flowchart:
 Flowcharts are better way of communicating the logic of system.
 Flowcharts act as a guide for blueprint during program designed.
 Flowcharts helps in debugging process.
 With the help of flowcharts programs can be easily analyzed.
 It provides better documentation.
 Flowcharts serve as a good proper documentation.
Disadvantages of Flowchart:
 It is difficult to draw flowchart for large and complex programs.
 In this there is no standard to determine the amount of detail.
 Difficult to reproduce the flowcharts.
 It is very difficult to modify the Flowchart.
Example: Draw a flowchart to input two numbers from user and display
the larger of two numbers

5
www.upcissyoutube.com O level M3-R5

Programming Language
As we know, to communicate with a person, we need a specific language, similarly
to communicate with computers, programmers also need a language is called
Programming language.
Before learning the programming language, let's understand what is language?

What is Language?
Language is a mode of communication that is used to share ideas, opinions with
each other. For example, if we want to teach someone, we need a language that
is understandable by both communicators.

What is a Programming Language?


A programming language is a computer language that is used by programmers
(developers) to communicate with computers. It is a set of instructions written
in any specific language (C, C++, Java, Python, etc.) to perform a specific task.
A programming language is mainly used to develop desktop applications,
websites, and mobile applications.

Characteristics of a programming Language


 A programming language must be simple, easy to learn and use, have good
readability, and be human recognizable.
 Abstraction is a must-have Characteristics for a programming language in
which the ability to define the complex structure and then its degree of
usability comes.
 A portable programming language is always preferred.
 Programming language’s efficiency must be high so that it can be easily
converted into a machine code and executed consumes little space in
memory.
 A programming language should be well structured and documented so that
it is suitable for application development.
 Necessary tools for the development, debugging, testing, and maintenance
of a program must be provided by a programming language.
 A programming language should provide a single environment known as
Integrated Development Environment (IDE).
 A programming language must be consistent in terms of syntax and
semantics.
Most Popular Programming Languages
 C
 Python
 C++
 Java
 SCALA
 C#
 R
 Ruby
 Go
 Swift
 JavaScript

6
www.upcissyoutube.com O level M3-R5

Compilation
The compilation is a process of converting the source code into object code. It is
done with the help of the compiler or interpreter. The compiler checks the source
code for the syntactical or structural errors, and if the source code is error-free,
then it generates the object code.
Introduction of Compiler Design
The compiler is software that converts a program written in a high-level language
(Source Language) to low-level language (Object/Target/Machine Language).
 Cross Compiler that runs on a machine ‘A’ and produces a code for another
machine ‘B’. It is capable of creating code for a platform other than the one
on which the compiler is running.
 Source-to-source Compiler or transcompiler or transpiler is a compiler that
translates source code written in one programming language into the source
code of another programming language.
Language processing systems (using Compiler) –
We know a computer is a logical assembly of Software and Hardware. The hardware
knows a language that is hard for us to grasp, consequently, we tend to write
programs in a high-level language that is much less complicated for us to
comprehend and maintain in thoughts. Now, these programs go through a series of
transformations so that they can readily be used by machines. This is where language
procedure systems come in handy.
 High-Level Language – If a program contains #define or #include directives
such as #include or #define it is called HLL. They are closer to humans but
far from machines. These (#) tags are called preprocessor directives. They
direct the pre-processor about what to do.
 Pre-Processor – The pre-processor removes all the #include directives by
including the files called file inclusion and all the #define directives using
macro expansion. It performs file inclusion, augmentation, macro-processing,
etc.
 Assembly Language – It’s neither in binary form nor high level. It is an
intermediate state that is a combination of machine instructions and some
other useful data needed for execution.
 Assembler – For every platform (Hardware + OS) we will have an assembler.
They are not universal since for each platform we have one. The output of
the assembler is called an object file. Its translate assembly language to
machine code.
 Interpreter – An interpreter converts high-level language into low-level
machine language, just like a compiler. But they are different in the way they
read the input. The Compiler in one go reads the inputs, does the processing,
and executes the source code whereas the interpreter does the same line by
line. Compiler scans the entire program and translates it as a whole into
machine code whereas an interpreter translates the program one statement
at a time. Interpreted programs are usually slower with respect to compiled
ones.
 Relocatable Machine Code – It can be loaded at any point and can be run.
The address within the program will be in such a way that it will cooperate
with the program movement.
 Loader/Linker – It converts the relocatable code into absolute code and
tries to run the program resulting in a running program or an error message
(or sometimes both can happen). Linker loads a variety of object files into a
single file to make it executable. Then loader loads it in memory and executes
it.

7
www.upcissyoutube.com O level M3-R5

Differences between Testing and Debugging


Testing:
Testing is the process of verifying and validating that a software or application is bug
free, meets the technical requirements as guided by its design and development and
meets the user requirements effectively and efficiently with handling all the
exceptional and boundary cases.
Debugging:
Debugging is the process of fixing a bug in the software. It can defined as the
identifying, analyzing and removing errors. This activity begins after the software
fails to execute properly and concludes by solving the problem and successfully
testing the software. It is considered to be an extremely complex and tedious task
because errors need to be resolved at all stages of debugging.

Testing Debugging

Testing is the process to find bugs and errors. Debugging is the process to correct the bugs
found during testing.

It is the process to identify the failure of It is the process to give the absolution to code
implemented code. failure.

Testing is the display of errors. Debugging is a deductive process.

Testing is done by the tester. Debugging is done by either programmer or


developer.

There is no need of design knowledge in the Debugging can’t be done without proper design
testing process. knowledge.

Testing can be done by insider as well as Debugging is done only by insider. Outsider can’t
outsider. do debugging.

Testing can be manual or automated. Debugging is always manual. Debugging can’t be


automated.

It is based on different testing levels i.e. unit Debugging is based on different types of bugs.
testing, integration testing, system testing etc.

Testing is a stage of software development life Debugging is not an aspect of software


cycle (SDLC). development life cycle, it occurs as a consequence
of testing.

Testing is composed of validation and While debugging process seeks to match symptom
verification of software. with cause, by that it leads to the error correction.

Testing is initiated after the code is written. Debugging commences with the execution of a
test case.

8
www.upcissyoutube.com O level M3-R5

Algorithms and Flowcharts


Flow Chart Symbols

9
www.upcissyoutube.com O level M3-R5

Let’s see the difference between algorithm and flow chart:

Algorithm Flowchart

Algorithm is step by step Flowchart is a diagram created by different


procedure to solve the problem. shapes to show the flow of data.

Algorithm is complex to
understand. Flowchart is easy to understand.

In algorithm plain text are used. In flowchart, symbols/shapes are used.

Algorithm is easy to debug. Flowchart it is hard to debug.

Algorithm is difficult to construct. Flowchart is simple to construct.

Algorithm does not follow any


rules. Flowchart follows rules to be constructed.

Algorithm is the pseudo code for Flowchart is just graphical representation of


the program. that logic.

Sequential processing algorithms and flowchart.


Algorithm for add two numbers entered by the user.
 Step 1: Start
 Step 2: Declare 3 variables num1, num2 and sum.
 Step 3: Read values num1 and num2.
 Step 4: Add num1 and num2 and assign the result to sum.
sum ← num1+num2
 Step 5: Print sum
 Step 6: Stop
Flowchart for add two numbers entered by the user.

10
www.upcissyoutube.com O level M3-R5

Decision based processing algorithms and flowchart.


Algorithm for find the largest among three different numbers entered by the user.
 Step 1:
Start
 Step 2:
Declare variables a, b and c.
 Step 3:
Read variables a, b and c.
 Step 4:
If a>b
If a>c
Print a is the largest number.
Else
Print c is the largest number.
Else
If b> c
Print b is the largest number.
Else
Print c is the largest number.
 Step 5: Stop

Flowchart for find the largest among three different numbers entered by the user.

Iterative processing algorithms and flowchart.


Algorithm for find the factorial of a number entered by the user.
 Step 1: Start
 Step 2: Declare variables num, fact and i.
 Step 3: Read value of num
 Step 4: initialize variables fact ←1, i ←1
 Step 5: Repeat the steps until i<=num
fact ← fact*i
i ← i+1
 Step 6: Print fact
 Step 7: Stop

11
www.upcissyoutube.com O level M3-R5

Flowchart for find the factorial of a number entered by the user.

Some Examples of algorithm and flowchart


Algorithm and flowchart for exchanging values of two variables.
 Step 1: Start
 Step 2: Declare variables x, y and temp.
 Step 3: Read values x and y.
 Step 4: temp  x
 Step 5: x  y
 Step 6: y  temp
 Step 7: Display x & y
 Step 8: Stop

12
www.upcissyoutube.com O level M3-R5

Algorithm and flowchart for summation of a set of numbers.


 Step 1: Start
 Step 2: Declare variables count, num and sum.
 Step 3: Read the value of num.
 Step 4: Initialize sum as 0 and count as 1.
 Step 5: If count>num (go to step 8)
 Step 6: sum = sum + count
 Step 7: count = count + 1 (go to step 5)
 Step 8: Print the value of sum
 Step 9: Stop

Algorithm for Decimal Base to Binary Base conversion.


1. Store the remainder when the number is divided by 2 in an array.
2. Divide the number by 2
3. Repeat the above two steps until the number is greater than zero.
4. Print the array in reverse order now.
For Example:
If the decimal number is 10.
 Step 1: Remainder when 10 is divided by 2 is zero. (Therefore, arr[0] = 0. )
 Step 2: Divide 10 by 2. New number is 10/2 = 5.
 Step 3: Remainder when 5 is divided by 2 is 1. (Therefore, arr[1] = 1.)
 Step 4: Divide 5 by 2. New number is 5/2 = 2.
 Step 5: Remainder when 2 is divided by 2 is zero. (Therefore, arr[2] = 0.)
 Step 6: Divide 2 by 2. New number is 2/2 = 1.
 Step 7: Remainder when 1 is divided by 2 is 1. (Therefore, arr[3] = 1.)
 Step 8: Divide 1 by 2. New number is 1/2 = 0.
 Step 9: Since number becomes = 0. Print the array in reverse order.
Therefore the equivalent binary number is 1010.

13
www.upcissyoutube.com O level M3-R5

Algorithm and flowchart for reversing digits of an integer.


 Step 1: Start
 Step 2: Read the value of num.
 Step 3: rev_num = 0
 Step 4: if num=0 (go to step 8 )
 Step 5: last_digit = num%10
 Step 6: rev_num=rev_num * 10 + last_digit
 Step 7: num = num / 10 (go to step 4)
 Step 8: Print rev_num
 Step 9: Stop

Algorithm and flowchart for GCD (Greatest Common Divisor) or HCF (Highest Common
Factor) of two numbers.
 Step 1: Start
 Step 2: Read n1, n2
 Step 3: If n1=n2
Then go to step 5
 Step 4: If n1>n2
n1  n1- n2 go to step 3
else
n2  n2 – n1 go to step 3
 Step 5: Print n1
 Step 6: Stop

14
www.upcissyoutube.com O level M3-R5

Algorithm and flowchart for Test whether a number is prime or not.


Step 1: Start
Step 2: Read num from user
Step 3: Initialize variables rem1, i2
Step 4: If num<=1 // any number less than 1 is not a prime number
Display num is not a prime number
Go to step 7
Step 5: Repeat the steps until i<num/2+1
If remainder of number divide i equals to 0,
Set rem=0
Go to step 6
i  i+1
Step 6: If rem=0
Display num is not prime number
Else
Display num is prime number
Step 7: Stop

Algorithm and flowchart for factorial computation.


Step 1: Start
Step 2: Read num from user
Step 3: Initialize variables i1, fact1
Step 4: Repeat this step until i<=num
fact  fact*i
i  i+1
Step 5: Display fact
Step 6: Stop

15
www.upcissyoutube.com O level M3-R5

Algorithm and flowchart for Fibonacci sequence.


Step 1: Start
Step 2: Declare variable x, y, i, feb_seq, num
Step 3: Read num from user
Step 4: Initialize variable x0, y1 and i2
Step 5: Print x and y
Step 6: Repeat until i<=num:
Step 6.1: feb_seq =x + y
Step 6.2: print feb_seq
Step 6.3: x = y, y = feb_seq
Step 6.4: i = i + 1
Step 7: Stop

Algorithm and flowchart for Find largest number in an array.


Step 1: Start
Step 2: input the array element as arr.
Step 3: Initialize large  arr[0] and i  1
Step 4: Repeat this step until i < size of arr
If arr[i] > large
large  arr[i]
i  i+1
Step 5: print large
Step 6: Stop

16
www.upcissyoutube.com O level M3-R5

Algorithm and flowchart for Reverse order of elements of an array.


Step 1: Start
Step 2: Read arr
Step 3: Place the two pointers (let start and end) at the start and end of the array.
Step 4: Swap arr[start] and arr[end] using temp variable.
Step 5: Increment start and decrement end with 1
Step 6: If start reached to the start >= end, then terminate otherwise repeat from
step 4 and step 5.
Step 7: Display arr
Step 8: Stop

Algorithm and flowchart for Tower of Hanoi.


Step 1: Start
Step 2: Let the three towers be the source, dest, aux.
Step 3: Read the number of disks, n from the user.
Step 4: If n=0 go to step 9
Step 5: Move n-1 disks from source to aux.
Step 6: Move nth disk from source to dest.
Step 7: Move n-1 disks from aux to dest.
Step 8: Repeat Steps 5 to 7, by decrementing n by 1.
Step 9: Stop

17
www.upcissyoutube.com O level M3-R5

Introduction to Python
What is Python?
Python is a popular programming language. It was created by Guido van Rossum,
and released in 1991.
It is used for:
 web development (server-side),
 software development,
 mathematics,
 System scripting.

What can Python do?

 Python can be used on a server to create web applications.


 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software
development.

Why Python?

 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,


etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
 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.
 Python can be treated in a procedural way, an object-orientated way or a
functional way.

Good to know

 The most recent major version of Python is Python 3, which we shall be using
in this tutorial. However, Python 2, although not being updated with anything
other than security updates, is still quite popular.
 In this tutorial Python will be written in a text editor. It is possible to write
Python in an Integrated Development Environment, such as Thonny,
Pycharm, Netbeans or Eclipse which are particularly useful when managing
larger collections of Python files.

Python Syntax compared to other programming languages

 Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
 Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
 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.

18
www.upcissyoutube.com O level M3-R5

The Python Command Line

To test a short amount of code in python sometimes it is quickest and easiest not
to write the code in a file. This is made possible because Python can be run as a
command line itself.

Type the following on the Windows, Mac or Linux command line:

From there you can write any python, including our hello world example from
earlier in the tutorial:

Which will write "Hello, World!" in the command line:

Whenever you are done in the python command line, you can simply type the
following to quit the python command line interface:

Python Virtual Machine (PVM)


Python Virtual Machine (PVM) is a program which provides programming
environment. The role of PVM is to convert the byte code instructions into machine
code so the computer can execute those machine code instructions and display the
output.

Interpreter converts the byte code into machine code and sends that machine code
to the computer processor for execution.

19
www.upcissyoutube.com O level M3-R5

Python Variables
Creating Variables

Variables are containers for storing data values.

Unlike other programming languages, Python has no command for declaring a


variable.

A variable is created the moment you first assign a value to it.

Example
x = 5
y = "John"
print(x)
print(y)

Variables do not need to be declared with any particular type and can even change
type after they have been set.

Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)

String variables can be declared either by using single or double quotes:

Example
x = "John"
# is the same as
x = 'John'

Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume). Rules for Python variables:

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different
variables)

Remember that variable names are case-sensitive

20
www.upcissyoutube.com O level M3-R5

Assign Value to Multiple Variables

Python allows you to assign values to multiple variables in one line:

Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

And you can assign the same value to multiple variables in one line:

Example
x = y = z = "Orange"
print(x)
print(y)
print(z)

Output Variables

The Python print statement is often used to output variables.

To combine both text and a variable, Python uses the + character:

Example
x = "awesome"
print("Python is " + x)

You can also use the + character to add a variable to another variable:

Example
x = "Python is "
y = "awesome"
z = x + y
print(z)

For numbers, the + character works as a mathematical operator:

Example
x = 5
y = 10
print(x + y)

If you try to combine a string and a number, Python will give you an error:

21
www.upcissyoutube.com O level M3-R5

Example
x = 5
y = "John"
print(x + y)

Python Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Creating a Comment

Comments starts with a #, and Python will ignore them:


Example
#This is a comment
print("Hello, World!")

Comments can be placed at the end of a line, and Python will ignore the rest of the
line:

Example
print("Hello, World!") #This is a comment

Comments does not have to be text to explain the code, it can also be used to
prevent Python from executing code: Comment shortcut key = ctrl+/

Example
#print("Hello, World!")
print("Cheers, Mate!")

Multi Line Comments

Python does not really have a syntax for multi line comments.

To add a multiline comment you could insert a # for each line:

Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")

Or, not quite as intended, you can use a multiline string.

22
www.upcissyoutube.com O level M3-R5

Since Python will ignore string literals that are not assigned to a variable, you can
add a multiline string (triple quotes) in your code, and place you comment inside it:

Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

As long as the string is not assigned to a variable, Python will read the code, but
then ignore it, and you have made a multiline comment.

Python Numbers
Python Numbers

There are three numeric types in Python:

 int
 float
 complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))

To verify the type of any object in Python, use the type() function:

Int

Int, or integer, is a whole number, positive or negative, without decimals, of


unlimited length.

Example Integers:
x = 1
y = 35656222554887711
z = -3255522

Float

Float, or "floating point number" is a number, positive or negative, containing one


or more decimals.

Example- Floats:

23
www.upcissyoutube.com O level M3-R5

x = 1.10
y = 1.0
z = -35.59
i = 35e3
j = 12E4
k = -87.7e100
Float can also be scientific numbers with an "e" to indicate the power of 10.

Complex
Complex numbers are written with a "j" as the imaginary part:

Example Complex:
x = 3+5j
y = 5j
z = -5j

Type Conversion

You can convert from one type to another with the int(), float(),
and complex() methods:

Example Convert from one type to another:


x = 1 # int
y = 2.8 # float
z = 1j # complex

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

Note: You cannot convert complex numbers into another number type.

Python Strings
String Literals

String literals in python are surrounded by either single quotation marks, or double
quotation marks.

24
www.upcissyoutube.com O level M3-R5

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example
print("Hello")
print('Hello')

Python constants
Sometimes, you may want to store values in variables. But you don’t want to
change these values throughout the execution of the program.

To do it in other programming languages, you can use constants. The constants


like variables but their values don’t change during the program executes.

The bad news is that Python doesn’t support constants.


To work around this, you use all capital letters to name a variable to indicate that
the variable should be treated as a constant. For example:
MY_PHONE_NUMBER = 9100000000
When encountering variables like these, you should not change their values. These
variables are constant by convention, not by rules.

Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal
sign and the string:

Example
a = "Hello"
print(a)

Multiline Strings

You can assign a multiline string to a variable by using three quotes:

Example You can use three double quotes:


a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Or three single quotes:

Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt

25
www.upcissyoutube.com O level M3-R5

ut labore et dolore magna aliqua.'''


print(a)

Note: in the result, the line breaks are inserted at the same position as in the
code.

Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of
bytes representing Unicode characters.

However, Python does not have a character data type, a single character is simply
a string with a length of 1. Square brackets can be used to access elements of the
string.

Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1]) # returns "e"

Example

Substring. Get the characters from position 2 to position 5 (5 position not included):
b = "Hello, World!"
print(b[2:5]) # returns "llo"
print(b[2:5:2]) # returns "lo"
print(b[::-1]) # returns "!dlroW ,olleH"

Example The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
print(a.lstrip()) # returns "Hello, World! " Removes any whitespace from the beginning.
print(a.rstrip()) # returns " Hello, World!" Removes any whitespace from the end.

Example The len() method returns the length of a string:


a = "Hello, World!"
print(len(a)) # returns 13

Example The lower() method returns the string in lower case:


a = "Hello, World!"
print(a.lower())# returns "hello, world!"

Example The upper() method returns the string in upper case:


a = "Hello, World!"
print(a.upper())# returns "HELLO, WORLD!"

Example The title() Converts the first character of each word to upper case:
a = "hello, world!"
print(a.title())# returns "Hello, World!"

26
www.upcissyoutube.com O level M3-R5

Example The count() Returns the number of times a specified value occurs in a string:
a = "hello, world!"
print(a.count("l")) # returns 3

Example The find() Searches the string for a specified value and returns the position of
where it was found:
a = "Hello, World!"
print(a.find("l")) # returns 2
print(a.find("l",4)) # returns 10

Example The replace() method replaces a string with another string:


a = "Hello, World!"
print(a.replace("H", "J")) # returns "Jello, World!"

Example The split() method splits the string into substrings if it finds instances of the
separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

String Format

As we learned in the Python Variables chapter, we cannot combine strings and


numbers like this:

Example
age = 36
txt = "My name is John, I am " + age
print(txt) # returns error

But we can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and places them
in the string where the placeholders {} are:

Example Use the format() method to insert numbers into strings:


age = 36
txt = "My name is John, and I am {}"
print(txt.format(age)) # returns "My name is John, and I am 36"

The format() method takes unlimited number of arguments, and are placed into the
respective placeholders:

Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

27
www.upcissyoutube.com O level M3-R5

You can use index numbers {0} to be sure the arguments are placed in the correct
placeholders:

Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
# returns "I want to pay 49.95 dollars for 3 pieces of item 567."

Example
quantity = 3
itemno = 567
price = 49.95
print(f"I want to pay {price} dollars for {quantity} pieces of item {itemno}.")
# returns "I want to pay 49.95 dollars for 3 pieces of item 567."

Note: All string methods returns new values. They do not change the original
string, because string are immutable in python.

Python Operators
Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Arithmetic Operators

28
www.upcissyoutube.com O level M3-R5

Arithmetic operators are used with numeric values to perform common


mathematical operations:

Operator Name Example Try it

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As Try it

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Python Comparison Operators

29
www.upcissyoutube.com O level M3-R5

Comparison operators are used to compare two values:

Operator Name Example Try it

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example Try it

and Returns True if both statements x < 5 and x <


are true 10

or Returns True if one of the x < 5 or x < 4


statements is true

not Reverse the result, returns False not(x < 5 and x


if the result is true < 10)

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location:

Operator Description Example Try it

is Returns true if both variables are x is y


the same object

is not Returns true if both variables are x is not y


not the same object

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

30
www.upcissyoutube.com O level M3-R5

Operator Description Example Try it

in Returns True if a sequence with the x in y


specified value is present in the object

not in Returns True if a sequence with the x not in y


specified value is not present in the
object

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

<< Zero fill Shift left by pushing zeros in from the right and let the
left shift leftmost bits fall off

>> Signed Shift right by pushing copies of the leftmost bit in from
right shift the left, and let the rightmost bits fall off

Sequence Data Types


Python Collections (Arrays)
There are four collection data types in the Python programming language:

List is a collection which is ordered and changeable. Allows duplicate



members.
 Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
 Set is a collection which is unordered and unindexed. No duplicate members.
 Dictionary is a collection which is unordered, changeable and indexed. No
duplicate members.
When choosing a collection type, it is useful to understand the properties of that
type. Choosing the right type for a particular data set could mean retention of
meaning, and, it could mean an increase in efficiency or security.

Python List
A list is a collection which is ordered and changeable. In Python lists are written
with square brackets.

31
www.upcissyoutube.com O level M3-R5

Example Create a List:


thislist = ["apple", "banana", "cherry"]
print(thislist) # returns ['apple', 'banana', 'cherry']

Access Items

You access the list items by referring to the index number:

Example Print the second item of the list:


thislist = ["apple", "banana", "cherry"]
print(thislist[1]) # returns banana

Change Item Value


To change the value of a specific item, refer to the index number:

Example Change the second item:


thislist = ["apple", "banana", "cherry"]
thislist[1] = "grapes"
print(thislist) # returns ['apple', 'grapes', 'cherry']

Loop through a List

You can loop through the list items by using a for loop:

Example Print all items in the list, one by one:


thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)

Check if Item Exists

To determine if a specified item is present in a list use the in keyword:

Example Check if "apple" is present in the list:


thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")

List Length

To determine how many items a list has, use the len() method:

Example Print the number of items in the list:


thislist = ["apple", "banana", "cherry"]
print(len(thislist)) # returns 3

Add Items

To add an item to the end of the list, use the append() method:

32
www.upcissyoutube.com O level M3-R5

Example Using the append() method to append an item:


thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist) # returns ['apple', 'banana', 'cherry', 'orange']

To add an item at the specified index, use the insert() method:

Example Insert an item as the second position:


thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist) # returns ['apple', 'orange', 'banana', 'cherry']

Remove Item

There are several methods to remove items from a list:

Example The remove() method removes the specified item:


thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist) # returns ['apple', 'cherry']

Example The pop() method removes the specified index, (or the last item if index is not
specified):
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist) # returns ['apple', 'banana']

Example The del keyword removes the specified index:


thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist) # returns ['banana', 'cherry']

Example The del keyword can also delete the list completely:
thislist = ["apple", "banana", "cherry"]
del thislist

Example The clear() method empties the list:


thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist) # returns []

Copy a List

You cannot copy a list simply by typing list2 = list1, because: list2 will only
be a reference to list1, and changes made in list1 will automatically also be
made in list2.

There are ways to make a copy, one way is to use the built-in List method copy().

33
www.upcissyoutube.com O level M3-R5

Example Make a copy of a list with the copy() method:


thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist) # returns ['apple', 'banana', 'cherry']

Another way to make a copy is to use the built-in method list().

Example Make a copy of a list with the list() method:


thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist) # returns ['apple', 'banana', 'cherry']

The list() Constructor

It is also possible to use the list() constructor to make a new list.

Example Using the list() constructor to make a List:


thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist) # returns ['apple', 'banana', 'cherry']

List Methods
Python has a set of built-in methods that you can use on lists/arrays.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of
the current list

index() Returns the index of the first element with the specified
value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

34
www.upcissyoutube.com O level M3-R5

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Python Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets.

Example Create a Tuple:


thistuple = ("apple", "banana", "cherry")
print(thistuple) # returns ('apple', 'banana', 'cherry')

Access Tuple Items

You can access tuple items by referring to the index number, inside square
brackets:

Example Return the item in position 1:


thistuple = ("apple", "banana", "cherry")
print(thistuple[1]) # returns banana

Change Tuple Values

Once a tuple is created, you cannot change its values. Tuples are unchangeable.

Loop through a Tuple

You can loop through the tuple items by using a for loop.

Example Iterate through the items and print the values:


thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)

Check if Item Exists

To determine if a specified item is present in a tuple use the in keyword:

Example Check if "apple" is present in the tuple:


thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

Tuple Length

35
www.upcissyoutube.com O level M3-R5

To determine how many items a tuple has, use the len() method:

Example Print the number of items in the tuple:


thistuple = ("apple", "banana", "cherry")
print(len(thistuple)) # returns 3

Add Items

Once a tuple is created, you cannot add items to it. Tuples are unchangeable.

Example You cannot add items to a tuple:


thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)

Remove Items

Note: You cannot remove items in a tuple.

Tuples are unchangeable, so you cannot remove items from it, but you can delete
the tuple completely:

Example The del keyword can delete the tuple completely:


thistuple = ("apple", "banana", "cherry")
del thistuple

The tuple() Constructor

It is also possible to use the tuple() constructor to make a tuple.

Example Using the tuple() method to make a tuple:


thistuple = tuple(("apple", "banana", "cherry")) # note the double round-
brackets
print(thistuple)

Python Sets
A set is a collection which is unordered and unindexed. In Python sets are written
with curly brackets.

Example Create a Set:


thisset = {"apple", "banana", "cherry"}
print(thisset) # returns {'cherry', 'banana', 'apple'}

Note: Sets are unordered, so you cannot be sure in which order the items will appear.

Access Items
You cannot access items in a set by referring to an index, since sets are unordered
the items has no index.

36
www.upcissyoutube.com O level M3-R5

But you can loop through the set items using a for loop, or ask if a specified value
is present in a set, by using the in keyword.
Example Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)

Example Check if "banana" is present in the set:


thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)

Change Items

Once a set is created, you cannot change its items, but you can add new items.

Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method.
Example Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset) # returns {'apple', 'cherry', 'orange', 'banana'}


Example Add multiple items to a set, using the update() method:
thisset = {"apple", "banana", "cherry"}

thisset.update(["orange", "mango", "grapes"])

print(thisset) # returns {'apple', 'grapes', 'orange', 'banana', 'mango', 'cherry'}

Get the Length of a Set

To determine how many items a set has, use the len() method.

Example Get the number of items in a set:


thisset = {"apple", "banana", "cherry"}

print(len(thisset)) # returns 3

Remove Item

To remove an item in a set, use the remove(), or the discard() method.

Example Remove "banana" by using the remove() method:


thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

37
www.upcissyoutube.com O level M3-R5

print(thisset) # returns {'cherry', 'apple'}

Example Remove "banana" by using the discard() method:


thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset) # returns {'cherry', 'apple'}

You can also use the pop(), method to remove an item, but this method will
remove the last item. Remember that sets are unordered, so you will not know
what item that gets removed.

The return value of the pop() method is the removed item.

Example Remove the last item by using the pop() method:


thisset = {"apple", "banana", "cherry"}

x = thisset.pop()

print(x) # returns apple

print(thisset) # returns {'cherry', 'banana'}

Note: Sets are unordered, so when using the pop() method, you will not know
which item that gets removed.

Example The clear() method empties the set:


thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset) # returns set()

Example The del keyword will delete the set completely:


thisset = {"apple", "banana", "cherry"}

del thisset

The set() Constructor

It is also possible to use the set() constructor to make a set.

Example Using the set() constructor to make a set:


thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)

Python Dictionaries
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.

38
www.upcissyoutube.com O level M3-R5

Example Create and print a dictionary:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict) # returns {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Accessing Items

You can access the items of a dictionary by referring to its key name, inside square
brackets:

Example Get the value of the "model" key:


x = thisdict["model"]
There is also a method called get() that will give you the same result:

Example Get the value of the "model" key:


x = thisdict.get("model")

Change Values

You can change the value of a specific item by referring to its key name:

Example Change the "year" to 2018:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"]=2019 # returns {'brand': 'Ford', 'model': 'Mustang', 'year':
2019}

Loop Through a Dictionary

You can loop through a dictionary by using a for loop.


When looping through a dictionary, the return value are the keys of the dictionary,
but there are methods to return the values as well.
Example Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)

Example Print all values in the dictionary, one by one:


for x in thisdict:
print(thisdict[x])

Example You can also use the values() function to return values of a dictionary:
for x in thisdict.values():
print(x)

Example Loop through both keys and values, by using the items() function:

39
www.upcissyoutube.com O level M3-R5

for x, y in thisdict.items():
print(x, y)

Check if Key Exists

To determine if a specified key is present in a dictionary use the in keyword:

Example Check if "model" is present in the dictionary:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")

Dictionary Length

To determine how many items (key-value pairs) a dictionary has, use


the len() method.

Example Print the number of items in the dictionary:


print(len(thisdict))

Adding Items

Adding an item to the dictionary is done by using a new index key and assigning a
value to it:

Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Removing Items

There are several methods to remove items from a dictionary:

Example The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

Example The popitem() method removes the last inserted item (in versions before 3.7, a
random item is removed instead):

40
www.upcissyoutube.com O level M3-R5

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)

Example The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)

Example The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict

Example The clear() keyword empties the dictionary:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)

Copy a Dictionary

You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will
only be a reference to dict1, and changes made in dict1 will automatically also be
made in dict2.

There are ways to make a copy, one way is to use the built-in Dictionary
method copy().

Example Make a copy of a dictionary with the copy() method:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)

41
www.upcissyoutube.com O level M3-R5

Another way to make a copy is to use the built-in method dict().

Example Make a copy of a dictionary with the dict() method:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)

The dict() Constructor

It is also possible to use the dict() constructor to make a new dictionary:

Example
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)

Python If ... Else


Python Conditions and If statements

Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements"
and loops.

An "if statement" is written by using the if keyword.

Example If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")

In this example we use two variables, a and b, which are used as part of the if
statement to test whether b is greater than a. As a is 33, and b is 200, we know
that 200 is greater than 33, and so we print to screen that "b is greater than a".

Indentation

42
www.upcissyoutube.com O level M3-R5

Python relies on indentation, using whitespace, to define scope in the code. Other
programming languages often use curly-brackets for this purpose.

Example If statement, without indentation (will raise an error):


a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

Elif

The elif keyword is pythons way of saying "if the previous conditions were not
true, then try this condition".

Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

In this example a is equal to b, so the first condition is not true, but


the elif condition is true, so we print to screen that "a and b are equal".

Else

The else keyword catches anything which isn't caught by the preceding conditions.

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print to screen
that "a is greater than b".

You can also have an else without the elif:

Example
a = 200
b = 33
if b > a:
print("b is greater than a")

43
www.upcissyoutube.com O level M3-R5

else:
print("b is not greater than a")

Short Hand If

If you have only one statement to execute, you can put it on the same line as the if
statement.

Example One line if statement:


if a > b: print("a is greater than b")

Short Hand If ... Else

If you have only one statement to execute, one for if, and one for else, you can put
it all on the same line:

Example One line if else statement:


print("A") if a > b else print("B")

You can also have multiple else statements on the same line:

Example One line if else statement, with 3 conditions:


print("A") if a > b else print("=") if a == b else print("B")

And

The and keyword is a logical operator, and is used to combine conditional


statements:

Example Test if a is greater than b, AND if c is greater than a:


if a > b and c > a:
print("Both conditions are True")

Or

The or keyword is a logical operator, and is used to combine conditional


statements:

Example Test if a is greater than b, OR if a is greater than c:


if a > b or a > c:
print("At least one of the conditions is True")

Python While Loops


Python has two primitive loop commands:

 while loops
 for loops

44
www.upcissyoutube.com O level M3-R5

The while Loop

With the while loop we can execute a set of statements as long as a condition is
true.

Example Print i as long as i is less than 6:


i = 1
while i < 6:
print(i)
i += 1

Note: remember to increment i, or else the loop will continue forever.

The while loop requires relevant variables to be ready, in this example we need to
define an indexing variable, i, which we set to 1.

The break Statement

With the break statement we can stop the loop even if the while condition is true:

Example Exit the loop when i is 3:


i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1

The continue Statement

With the continue statement we can stop the current iteration, and continue with
the next:

Example Continue to the next iteration if i is 3:


i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)

Python for Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).

This is less like the for keyword in other programming languages, and works more
like an iterator method as found in other object-orientated programming
languages.

45
www.upcissyoutube.com O level M3-R5

With the for loop we can execute a set of statements, once for each item in a list,
tuple, set etc.

Example Print each fruit in a fruit list:


fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)

The for loop does not require an indexing variable to set beforehand.

Looping Through a String

Even strings are iterable objects, they contain a sequence of characters:

Example Loop through the letters in the word "banana":


for x in "banana":
print(x)

The break Statement

With the break statement we can stop the loop before it has looped through all the
items:

Example Exit the loop when x is "banana":


fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break

Example Exit the loop when x is "banana", but this time the break comes before the print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)

The continue Statement

With the continue statement we can stop the current iteration of the loop, and
continue with the next:

Example Do not print banana:


fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)

46
www.upcissyoutube.com O level M3-R5

The range() Function


To loop through a set of code a specified number of times, we can use
the range() function,

The range() function returns a sequence of numbers, starting from 0 by default,


and increments by 1 (by default), and ends at a specified number.

Example Using the range() function:


for x in range(6):
print(x)

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The range() function defaults to 0 as a starting value, however it is possible to


specify the starting value by adding a parameter: range(2, 6), which means
values from 2 to 6 (but not including 6):

Example Using the start parameter:


for x in range(2, 6):
print(x)

The range() function defaults to increment the sequence by 1, however it is


possible to specify the increment value by adding a third parameter: range(2,
30, 3):

Example Increment the sequence with 3 (default is 1):


for x in range(2, 30, 3):
print(x)

Else in For Loop

The else keyword in a for loop specifies a block of code to be executed when the
loop is finished:

Example Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")

Nested Loops

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example Print each adjective for every fruit:


adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

47
www.upcissyoutube.com O level M3-R5

for x in adj:
for y in fruits:
print(x, y)

Python Keywords
Python has a set of keywords that are reserved words that cannot be used as
variable names, function names, or any other identifiers:

Method Description
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be executed
no matter if there is an exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
while To create a while loop
with Used to simplify exception handling
yield To end a function, returns a generator

48
www.upcissyoutube.com O level M3-R5

Python Functions
A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

Example
def my_function():
print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

Example
def my_function():
print("Hello from a function")

my_function()

Parameters

Information can be passed to functions as parameter.

Parameters are specified after the function name, inside the parentheses. You can
add as many parameters as you want, just separate them with a comma.

The following example has a function with one parameter (fname). When the
function is called, we pass along a first name, which is used inside the function to
print the full name:

Example
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Default Parameter Value

The following example shows how to use a default parameter value.

If we call the function without parameter, it uses the default value:

49
www.upcissyoutube.com O level M3-R5

Example
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Passing a List as a Parameter

You can send any data types of parameter to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.

E.g. if you send a List as a parameter, it will still be a List when it reaches the
function:

Example
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]


my_function(fruits)

Return Values

To let a function return a value, use the return statement:

Example
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Recursion
Python also accepts function recursion, which means a defined function can call
itself.
Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through data
to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip
into writing a function which never terminates, or one that uses excess amounts of
memory or processor power. However, when written correctly recursion can be a
very efficient and mathematically-elegant approach to programming.

50
www.upcissyoutube.com O level M3-R5

Python Lambda
A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one
expression.

Syntax
lambda arguments : expression

The expression is executed and the result is returned:

Example A lambda function that adds 10 to the number passed in as an argument, and print
the result:
x = lambda a : a + 10
print(x(5))

Lambda functions can take any number of arguments:

Example
A lambda function that multiplies argument a with argument b and print the result:
x = lambda a, b : a * b
print(x(5, 6))

Example A lambda function that sums argument a, b, and c and print the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

Why Use Lambda Functions?

The power of lambda is better shown when you use them as an anonymous
function inside another function.

Say you have a function definition that takes one argument, and that argument will
be multiplied with an unknown number:

def myfunc(n):
return lambda a : a * n

Use that function definition to make a function that always doubles the number you
send in:

Example
def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))

51
www.upcissyoutube.com O level M3-R5

Or, use the same function definition to make a function that always triples the
number you send in:

Example
def myfunc(n):
return lambda a : a * n

mytripler = myfunc(3)

print(mytripler(11))

Or, use the same function definition to make both functions, in the same program:

Example
def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11))
print(mytripler(11))

Use lambda functions when an anonymous function is required for a short period of
time.

Python Classes and Objects


Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the keyword class:

Example Create a class named MyClass, with a property named x:


class MyClass:
x = 5

Create Object

Now we can use the class named myClass to create objects:

Example Create an object named p1, and print the value of x:


p1 = MyClass()
print(p1.x)

52
www.upcissyoutube.com O level M3-R5

The __init__() Function

The examples above are classes and objects in their simplest form, and are not
really useful in real life applications.

To understand the meaning of classes we have to understand the built-in __init__()


function.

All classes have a function called __init__(), which is always executed when the
class is being initiated.

Use the __init__() function to assign values to object properties, or other


operations that are necessary to do when the object is being created:

Example Create a class named Person, use the __init__() function to assign values for name
and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

Note: The __init__() function is called automatically every time the class is being
used to create a new object.

Object Methods

Objects can also contain methods. Methods in objects are functions that belong to
the object.

Let us create a method in the Person class:

Example
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

Note: The self parameter is a reference to the current instance of the class, and
is used to access variables that belong to the class.

53
www.upcissyoutube.com O level M3-R5

The self Parameter

The self parameter is a reference to the current instance of the class, and is used
to access variables that belongs to the class.

It does not have to be named self , you can call it whatever you like, but it has to
be the first parameter of any function in the class:

Example Use the words mysillyobject and abc instead of self:


class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()

Modify Object Properties

You can modify properties on objects like this:

Example Set the age of p1 to 40:


p1.age = 40

Delete Object Properties

You can delete properties on objects by using the del keyword:

Example Delete the age property from the p1 object:


del p1.age

Delete Objects

You can delete objects by using the del keyword:

Example Delete the p1 object:

del p1

Python Inheritance

Inheritance allows us to define a class that inherits all the methods and properties
from another class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.

54
www.upcissyoutube.com O level M3-R5

Create a Parent Class

Any class can be a parent class, so the syntax is the same as creating any other
class:

Example Create a class named Person, with firstname and lastname properties, and
a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname
method:

x = Person("John", "Doe")
x.printname()

Create a Child Class

To create a class that inherits the functionality from another class, send the parent
class as a parameter when creating the child class:

Example Create a class named Student, which will inherit the properties and methods from
the Person class:
class Student(Person):
pass

Note: Use the pass keyword when you do not want to add any other properties or
methods to the class.

Now the Student class has the same properties and methods as the Person class.

Example Use the Student class to create an object, and then execute the printname method:
x = Student("Mike", "Olsen")
x.printname()

Add the __init__() Function

So far we have created a child class that inherits the properties and methods from
it's parent.

We want to add the __init__() function to the child class (instead of


the pass keyword).

Note: The __init__() function is called automatically every time the class is being
used to create a new object.

55
www.upcissyoutube.com O level M3-R5

Example Add the __init__() function to the Student class:


class Student(Person):
def __init__(self, fname, lname):
#add properties etc.

When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.

Note: The child's __init__() function overrides the inheritance of the


parent's __init__() function.

To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:

Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)

Now we have successfully added the __init__() function, and kept the inheritance
of the parent class, and we are ready to add functionality in
the __init__() function.

Use the super() Function

Python also have a super() function that will make the child class inherit all the
methods and properties from it's parent:

Example
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)

By using the super() function, you do not have to use the name of the parent
element, it will automatically inherit the methods and properties from it's parent.

Add Properties
Example Add a property called graduationyear to the Student class:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019

In the example below, the year 2019 should be a variable, and passed into
the Student class when creating student objects. To do so, add another parameter
in the __init__() function:

56
www.upcissyoutube.com O level M3-R5

Example Add a year parameter, and pass the correct year when creating objects:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year

x = Student("Mike", "Olsen", 2019)

Add Methods
Example Add a method called welcome to the Student class:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year

def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of",
self.graduationyear)

If you add a method in the child class with the same name as a function in the
parent class, the inheritance of the parent method will be overridden.

Python Iterators
An iterator is an object that contains a countable number of values.

An iterator is an object that can be iterated upon, meaning that you can traverse
through all the values.

Technically, in Python, an iterator is an object which implements the iterator


protocol, which consist of the methods __iter__() and __next__().

Iterator vs Iterable

Lists, tuples, dictionaries, and sets are all iterable objects. They are
iterable containers which you can get an iterator from.

All these objects have a iter() method which is used to get an iterator:

Example Return an iterator from a tuple, and print each value:


mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

Even strings are iterable objects, and can return an iterator:

57
www.upcissyoutube.com O level M3-R5

Example Strings are also iterable objects, containing a sequence of characters:


mystr = "banana"
myit = iter(mystr)

print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))

Looping Through an Iterator

We can also use a for loop to iterate through an iterable object:

Example Iterate the values of a tuple:


mytuple = ("apple", "banana", "cherry")

for x in mytuple:
print(x)

Example Iterate the characters of a string:


mystr = "banana"

for x in mystr:
print(x)

The for loop actually creates an iterator object and executes the next() method for
each loop.

Create an Iterator

To create an object/class as an iterator you have to implement the


methods __iter__() and __next__() to your object.

As you have learned in the Python Classes/Objects chapter, all classes have a
function called __init__(), which allows you do some initializing when the object
is being created.

The __iter__() method acts similar, you can do operations (initializing etc.), but
must always return the iterator object itself.

The __next__() method also allows you to do operations, and must return the next
item in the sequence.

58
www.upcissyoutube.com O level M3-R5

Example Create an iterator that returns numbers, starting with 1, and each sequence will
increase by one (returning 1,2,3,4,5 etc.):
class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
x = self.a
self.a += 1
return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

Stop Iteration

The example above would continue forever if you had enough next() statements, or
if it was used in a for loop.

To prevent the iteration to go on forever, we can use


the StopIteration statement.

In the __next__() method, we can add a terminating condition to raise an error if


the iteration is done a specified number of times:

Example Stop after 20 iterations:


class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
print(x)

59
www.upcissyoutube.com O level M3-R5

Python Scope
A variable is only available from inside the region it is created. This is called scope.

Local Scope

A variable created inside a function belongs to the local scope of that function, and
can only be used inside that function.

Example A variable created inside a function is available inside that function:


def myfunc():
x = 300
print(x)

myfunc()

Function Inside Function

As explained in the example above, the variable x is not available outside the
function, but it is available for any function inside the function:

Example The local variable can be accessed from a function within the function:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()

myfunc()

Global Scope

A variable created in the main body of the Python code is a global variable and
belongs to the global scope.

Global variables are available from within any scope, global and local.

Example A variable created outside of a function is global and can be used by anyone:
x = 300

def myfunc():
print(x)

myfunc()

print(x)

60
www.upcissyoutube.com O level M3-R5

Naming Variables

If you operate with the same variable name inside and outside of a function,
Python will treat them as two separate variables, one available in the global scope
(outside the function) and one available in the local scope (inside the function):

Example The function will print the local x, and then the code will print the global x:
x = 300

def myfunc():
x = 200
print(x)

myfunc()

print(x)

Global Keyword

If you need to create a global variable, but are stuck in the local scope, you can
use the global keyword.

The global keyword makes the variable global.

Example If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = 300

myfunc()

print(x)

Also, use the global keyword if you want to make a change to a global variable
inside a function.

Example To change the value of a global variable inside a function, refer to the variable by
using the global keyword:
x = 300

def myfunc():
global x
x = 200

myfunc()

print(x)

61
www.upcissyoutube.com O level M3-R5

Python Modules
What is a Module?

Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module

To create a module just save the code you want in a file with the file
extension .py:

Example Save this code in a file named mymodule.py


def greeting(name):
print("Hello, " + name)

Use a Module

Now we can use the module we just created, by using the import statement:

Example Import the module named mymodule, and call the greeting function:
import mymodule

mymodule.greeting("Jonathan")

Note: When using a function from a module, use the


syntax: module_name.function_name.

Variables in Module

The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):

Example Save this code in the file mymodule.py


person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example Import the module named mymodule, and access the person1 dictionary:
import mymodule

a = mymodule.person1["age"]
print(a)

Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py

62
www.upcissyoutube.com O level M3-R5

Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Example Create an alias for mymodule called mx:
import mymodule as mx

a = mx.person1["age"]
print(a)

Built-in Modules

There are several built-in modules in Python, which you can import whenever you
like.

Example Import and use the platform module:


import platform

x = platform.system()
print(x)

Using the dir() Function

There is a built-in function to list all the function names (or variable names) in a
module. The dir() function:

Example List all the defined names belonging to the platform module:
import platform

x = dir(platform)
print(x)

Note: The dir() function can be used on all modules, also the ones you create
yourself.

Import from Module

You can choose to import only parts from a module, by using the from keyword.

Example The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

63
www.upcissyoutube.com O level M3-R5

Example Import only the person1 dictionary from the module:


from mymodule import person1

print (person1["age"])

Reloading modules

reload() reloads a previously imported module. This is useful if you have edited
the module source file using an external editor and want to try out the new version
without leaving the Python interpreter. The return value is the module object.

Note: The argument should be a module which has been successfully imported.

Usage:

For Python2.x
reload(module)

For above 2.x and <=Python3.3


import imp
imp.reload(module)

For >=Python3.4
import importlib
importlib.reload(module)

Scope of Object and Names


 The scope refers to the region in the program code where variables and
names are accessible.
 It also determines the visibility and lifetime of a variable in the program
code.
 Assigning a value, defining a function or class (using def or class) or
importing module operation creates a name and its place in the code defines
its scope.
 The names or objects which are accessible are called in-scope.
 The names or objects which are not accessible are called out-of-scope.
 The Python scope concept follows the LEGB (Local, Enclosing, Global and
built-in) rule.
 The scope concept helps to avoid the name collision and use of global names
across the programs.

Names and Objects in Python


 Python is a dynamically types language, so when we assign the value to the
variable for the first time, it creates the variable. Others names or objects
come in existence as given:
Operation Statement
Assignment X=value
Import Operation import module
Function definitions def fun( )
Arguments in the function def fun( x1, x2 , x3 )
Class definition class abc :

64
www.upcissyoutube.com O level M3-R5

 Python uses the location of the name assignment or definition to associate it


with a scope.
 If a variable assigned value in the function, it has a local scope.
 If a variable assigned value at the top level and outside all the functions, it
has a global scope.

Python Scope Vs Namespace


 The scope of a variables and objects are related to the concept of the
namespace.
 The scope determines the visibility of the names and objects in the program.
 A namespace is a collection of names.
 In python, scopes are implemented as dictionaries that maps names to
objects. These dictionaries are called namespaces.
 The dictionaries have the names as key and the objects as value.
 A strings, lists, functions, etc everything in Python is an object.

Searching a name in the Namespace


 Whenever we use a name, such as a variable or a function name, Python
searches through different scope levels (or namespaces) to determine
whether the name exists or not.
 If the name exists, then we always get the first occurrence of it.
 Otherwise, we get an error.

Types of namespace
 Built-in Namespace It includes functions and exception names that are
built-in in the python.
 Global Namespace It includes the names from the modules that are
imported in the code. It lasts till the end of program.
 Local Namespace It includes the names defined in the function. It is
created when the function is called and ends when the value returned.

LEGB Rule for Python Scope


 The LEGB stands for Local, Enclosing, Global and Built-in.
 Python resolves names using the LEGB rules.
 The LEGB rule is a kind of name lookup procedure, which determines the
order in which Python looks up names.
 For example, if we access a name, then Python will look that name up
sequentially in the local, enclosing, global, and built-in scope.

Local (or function) scope


 It is the code block or body of any Python function or lambda expression.
 This Python scope contains the names that you define inside the function.
 These names will only be visible from the code of the function.
 It’s created at function call, not at function definition, so we have as many
different local scopes as function calls.
 It is applicable if we call the same function multiple times, or recursively.
 Each call will result in a new local scope being created.

Enclosing (or nonlocal) scope


 It is a special scope that only exists for nested functions.
 If the local scope is an inner or nested function, then the enclosing scope is
the scope of the outer or enclosing function.
 This scope contains the names that you define in the enclosing function.

65
www.upcissyoutube.com O level M3-R5

 The names in the enclosing scope are visible from the code of the inner and
enclosing functions.

Global (or module) scope


 It is the top-most scope in a Python program, script, or module.
 This scope contains all of the names that are defined at the top level of a
program or a module.
 Names in this Python scope are visible from everywhere in your code.

Built-in scope
 It is a special scope which is created or loaded at script run or opens an
interactive session.
 This scope contains names such as keywords, functions, exceptions, and
other attributes that are built into Python.
 Names in this scope are also available from everywhere in your code.

Example
var1 = 5 #var1 is in the global namespace
def ABC( ):
var2 = 6 # var2 is in the local namespace
def XYZ( ):
var3 = 7 # var3 is in the nested local namespace

 In this example, the var1 is declared in the global namespace because it is


not enclosed inside any function. So it is accessible everywhere in the script.
 var2 is inside the ABC(). So, it can be accessed only inside the ABC() and
outside the function, it no longer exists.
 var3 also has a local scope, the function is nested and we can use var3 only
inside XYZ().

66
www.upcissyoutube.com O level M3-R5

Python Date time


Python Dates

A date in Python is not a data type of its own, but we can import a module
named datetime to work with dates as date objects.

Example Import the datetime module and display the current date:
import datetime

x = datetime.datetime.now()
print(x)

Date Output

When we execute the code from the example above the result will be:

2019-09-24 15:35:35.403417

The date contains year, month, day, hour, minute, second, and microsecond.

The datetime module has many methods to return information about the date
object.

Here are a few examples, you will learn more about them later in this chapter:

Example Return the year and name of weekday:


import datetime

x = datetime.datetime.now()

print(x.year)
print(x.strftime("%A"))

Creating Date Objects

To create a date, we can use the datetime() class (constructor) of the datetime module.

The datetime() class requires three parameters to create a date: year, month,
day.

Example Create a date object:


import datetime

x = datetime.datetime(2020, 5, 17)

print(x)

The datetime() class also takes parameters for time and timezone (hour, minute,
second, microsecond, tzone), but they are optional, and has a default value of 0,
(None for timezone).

67
www.upcissyoutube.com O level M3-R5

The strftime() Method

The datetime object has a method for formatting date objects into readable
strings.

The method is called strftime(), and takes one parameter, format, to specify the
format of the returned string:

Example Display the name of the month:


import datetime

x = datetime.datetime(2018, 6, 1)

print(x.strftime("%B"))

A reference of all the legal format codes:

Directive Description Example

%a Weekday, short version Wed

%A Weekday, full version Wednesday

%w Weekday as a number 0-6, 0 is Sunday 3

%d Day of month 01-31 31

%b Month name, short version Dec

%B Month name, full version December

%m Month as a number 01-12 12

%y Year, short version, without century 18

%Y Year, full version 2018

%H Hour 00-23 17

%I Hour 00-12 05

%p AM/PM PM

%M Minute 00-59 41

%S Second 00-59 08

%f Microsecond 000000-999999 548513

%z UTC offset +0100

%Z Timezone CST

68
www.upcissyoutube.com O level M3-R5

%j Day number of year 001-366 365

%U Week number of year, Sunday as the first 52


day of week, 00-53

%W Week number of year, Monday as the first 52


day of week, 00-53

%c Local version of date and time Mon Dec 31 17:41:00


2018

%x Local version of date 12/31/18

%X Local version of time 17:41:00

%% A % character %

Python Try Except


The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The finally block lets you execute code, regardless of the result of the try- and
except blocks.

Exception Handling

When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.

These exceptions can be handled using the try statement:

Example The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:

Example This statement will raise an error, because x is not defined:


print(x)

69
www.upcissyoutube.com O level M3-R5

Many Exceptions

You can define as many exception blocks as you want, e.g. if you want to execute a
special block of code for a special kind of error:

Example Print one message if the try block raises a NameError and another for other errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

Else

You can use the else keyword to define a block of code to be executed if no errors
were raised:

Example In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")

Finally

The finally block, if specified, will be executed regardless if the try block raises an
error or not.

Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")

This can be useful to close objects and clean up resources:

Example Try to open and write to a file that is not writable:


try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()

70
www.upcissyoutube.com O level M3-R5

except:
print("Something went wrong when opening the file")

The program can continue, without leaving the file object open.

Raise an exception

As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the raise keyword.

Example Raise an error and stop the program if x is lower than 0:


x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

Example Raise a TypeError if x is not an integer:


x = "hello"

if not type(x) is int:


raise TypeError("Only integers are allowed")

File Processing (Handling)


Python too supports file handling and allows users to handle files i.e., to read
and write files, along with many other file handling options, to operate on files.
The concept of file handling has stretched over various other languages, but the
implementation is either complicated or lengthy, but like other concepts of
Python, this concept here is also easy and short. Python treats file differently as
text or binary and this is important. Each line of code includes a sequence of
characters and they form text file. Each line of a file is terminated with a special
character, called the EOL or End of Line characters like comma {,} or newline
character. It ends the current line and tells the interpreter a new one has
begun. Let’s start with Reading and Writing files.

File Handling

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not exist

71
www.upcissyoutube.com O level M3-R5

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

"r+" To read and write data into the file. The previous data in the file will not be deleted

"w+" To write and read data. It will override existing data

"a+" To append and read data from the file. It won’t override existing data

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Syntax

To open a file for reading it is enough to specify the name of the file:

f = open("demofile.txt")

The code above is the same as:

f = open("demofile.txt", "rt")

Because "r" for read, and "t" for text are the default values, you do not need to
specify them.

Note: Make sure the file exists, or else you will get an error.

Python File Open

Assume we have the following file, located in the same folder as Python:

demofile.txt

Hello! Welcome to demofile.txt


This file is for testing purposes.
Good Luck!

To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for reading
the content of the file:

Example
f = open("demofile.txt", "r")
print(f.read())

72
www.upcissyoutube.com O level M3-R5

If the file is located in a different location, you will have to specify the file path, like
this:

Example Open a file on a different location:


f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())

Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify how
many characters you want to return:

Example Return the 5 first characters of the file:


f = open("demofile.txt", "r")
print(f.read(5))

Read Lines

You can return one line by using the readline() method:

Example Read one line of the file:


f = open("demofile.txt", "r")
print(f.readline())

By calling readline() two times, you can read the two first lines:

Example Read two lines of the file:


f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())

By looping through the lines of the file, you can read the whole file, line by line:

Example Loop through the file line by line:


f = open("demofile.txt", "r")
for x in f:
print(x)

Example

Return all lines in the file, as a list where each line is an item in the list object:

f = open("demofile.txt", "r")
print(f.readlines())

Close Files

It is a good practice to always close the file when you are done with it.

Example Close the file when you are finish with it:

73
www.upcissyoutube.com O level M3-R5

f = open("demofile.txt", "r")
print(f.readline())
f.close()

Note: You should always close your files, in some cases, due to buffering, changes
made to a file may not show until you close the file.

Python File Write

Write to an Existing File

To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Example Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())

Example Open the file "demofile3.txt" and overwrite the content:


f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the appending:


f = open("demofile3.txt", "r")
print(f.read())

Note: the "w" method will overwrite the entire file.

Create a New File

To create a new file in Python, use the open() method, with one of the following
parameters:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist
Example Create a file called "myfile.txt":
f = open("myfile.txt", "x")

Result: a new empty file is created!

74
www.upcissyoutube.com O level M3-R5

Example Create a new file if it does not exist:


f = open("myfile.txt", "w")

Python Delete File

To delete a file, you must import the OS module, and run its os.remove() function:

Example Remove the file "demofile.txt":


import os
os.remove("demofile.txt")

Check if File exist:

To avoid getting an error, you might want to check if the file exists before you try
to delete it:
Example Check if file exists, then delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")

Delete Folder

To delete an entire folder, use the os.rmdir() method:


Example Remove the folder "myfolder":
import os
os.rmdir("myfolder")

Note: You can only remove empty folders.

With statement

with statement in Python is used in exception handling to make the code cleaner
and much more readable. It simplifies the management of common resources like
file streams. Unlike the above implementations, there is no need to
call file.close() when using with statement. The with statement itself ensures
proper acquisition and release of resources.

Syntax: with open filename as file:


# Program to show various ways to
# read data from a file.

L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

# Creating a file
with open("myfile.txt", "w") as file1:
# Writing data to a file
file1.write("Hello \n")
file1.writelines(L)
file1.close() # to change file access modes

75
www.upcissyoutube.com O level M3-R5

with open("myfile.txt", "r+") as file1:


# Reading form a file
print(file1.read())

Output:
Hello
This is Delhi
This is Paris
This is London

Python File tell() Method


Example Find the current file position:
f = open("demofile.txt", "r")
print(f.tell())

Definition and Usage

The tell() method returns the current file position in a file stream.

Tip: You can change the current file position with the seek method.

Python File seek() Method


Example Change the current file position to 4, and return the rest of the line:
f = open("demofile.txt", "r")
f.seek(4)
print(f.readline())

Definition and Usage

The seek() method sets the current file position in a file stream.

The seek() method also returns the new postion.

Command Line Arguments

The arguments that are given after the name of the program in the command line
shell of the operating system are known as Command Line Arguments. Python
provides various ways of dealing with these types of arguments. The three most
common are:

 Using sys.argv
 Using getopt module
 Using argparse module

76
www.upcissyoutube.com O level M3-R5

Using sys.argv

The sys module provides functions and variables used to manipulate different parts
of the Python runtime environment. This module provides access to some variables
used or maintained by the interpreter and to functions that interact strongly with
the interpreter.
One such variable is sys.argv which is a simple list structure. It’s main purpose are:

 It is a list of command line arguments.


 len(sys.argv) provides the number of command line arguments.
 sys.argv[0] is the name of the current Python script.

Example Let’s suppose there is a Python script for adding two numbers and the numbers
are passed as command-line arguments.

77
www.upcissyoutube.com O level M3-R5

Using getopt module


Python getopt module is similar to the getopt() function of C. Unlike sys module getopt
module extends the separation of the input string by parameter validation. It allows
both short, and long options including a value assignment. However, this module
requires the use of the sys module to process input data properly. To use getopt
module, it is required to remove the first element from the list of command-line
arguments.

Syntax: getopt.getopt(args, options, [long_options])


Parameters:
args: List of arguments to be passed.
options: String of option letters that the script want to recognize. Options that
require an argument should be followed by a colon (:).
long_options: List of string with the name of long options. Options that require
arguments should be followed by an equal sign (=).
Return Type: Returns value consisting of two elements: the first is a list of (option,
value) pairs. The second is the list of program arguments left after the option list
was stripped.

Example

78
www.upcissyoutube.com O level M3-R5

Using argparse module


Using argparse module is a better option than the above two options as it provides
a lot of options such as positional arguments, default value for arguments, help
message, specifying data type of argument etc.

Note: As a default optional argument, it includes -h, along with its long version –
help.

Example 1: Basic use of argparse module.

79
www.upcissyoutube.com O level M3-R5

Example 2: Adding description to the help message.

NumPy Basics
What is NumPy?
NumPy is a Python library used for working with arrays.
It also has functions for working in domain of linear algebra, fourier transform, and
matrices.
NumPy was created in 2005 by Travis Oliphant. It is an open source project and
you can use it freely.
NumPy stands for Numerical Python.

Why Use NumPy?


In Python we have lists that serve the purpose of arrays, but they are slow to
process.
NumPy aims to provide an array object that is up to 50x faster than traditional
Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting functions
that make working with ndarray very easy.
Arrays are very frequently used in data science, where speed and resources are
very important.
Data Science: is a branch of computer science where we study how to store, use
and analyze data for deriving information from it.

80
www.upcissyoutube.com O level M3-R5

Why is NumPy Faster than Lists?


NumPy arrays are stored at one continuous place in memory unlike lists, so
processes can access and manipulate them very efficiently.
This behavior is called locality of reference in computer science.
This is the main reason why NumPy is faster than lists. Also it is optimized to work
with latest CPU architectures.

Which Language is NumPy written in?


NumPy is a Python library and is written partially in Python, but most of the parts
that require fast computation are written in C or C++.

Installation of NumPy
If you have Python and PIP already installed on a system, then installation of
NumPy is very easy.
Install it using this command:
C:\Users\Your Name>pip install numpy
If this command fails, then use a python distribution that already has NumPy
installed like, Anaconda, Spyder etc.

Import NumPy
Once NumPy is installed, import it in your applications by adding
the import keyword:
import numpy
Now NumPy is imported and ready to use.
Example
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)

NumPy as np
NumPy is usually imported under the np alias.
alias: In Python alias are an alternate name for referring to the same thing.
Create an alias with the as keyword while importing:
import numpy as np
Now the NumPy package can be referred to as np instead of numpy.
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)

Checking NumPy Version


The version string is stored under __version__ attribute.
Example
import numpy as np
print(np.__version__)

81
www.upcissyoutube.com O level M3-R5

NumPy Creating Arrays

Create a NumPy ndarray Object


NumPy is used to work with arrays. The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() function.
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
type(): This built-in Python function tells us the type of the object passed to it.
Like in above code it shows that arr is numpy.ndarray type.
To create an ndarray, we can pass a list, tuple or any array-like object into
the array() method, and it will be converted into an ndarray:
Example Use a tuple to create a NumPy array:
import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)

Dimensions in Arrays
A dimension in arrays is one level of array depth (nested arrays).
Nested array: are arrays that have arrays as their elements.

0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-
D array.
Example Create a 0-D array with value 42
import numpy as np
arr = np.array(42)
print(arr)

1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
These are the most common and basic arrays.
Example Create a 1-D array containing the values 1,2,3,4,5:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)

2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
These are often used to represent matrix or 2nd order tensors.
NumPy has a whole sub module dedicated towards matrix operations
called numpy.mat
Example Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:

82
www.upcissyoutube.com O level M3-R5

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)

3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
These are often used to represent a 3rd order tensor.
Example Create a 3-D array with two 2-D arrays, both containing two arrays with the values
1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)

Check Number of Dimensions?


NumPy Arrays provides the ndim attribute that returns an integer that tells us how
many dimensions the array have.
Example Check how many dimensions the arrays have:
import numpy as np

a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)

Higher Dimensional Arrays


An array can have any number of dimensions.
When the array is created, you can define the number of dimensions by using
the ndmin argument.
Example Create an array with 5 dimensions and verify that it has 5 dimensions:
import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('number of dimensions :', arr.ndim)
In this array the innermost dimension (5th dim) has 4 elements, the 4th dim has 1
element that is the vector, the 3rd dim has 1 element that is the matrix with the
vector, the 2nd dim has 1 element that is 3D array and 1st dim has 1 element that
is a 4D array.

NumPy Array Indexing

Access Array Elements


Array indexing is the same as accessing an array element.
You can access an array element by referring to its index number.

83
www.upcissyoutube.com O level M3-R5

The indexes in NumPy arrays start with 0, meaning that the first element has index
0, and the second has index 1 etc.
Example Get the first element from the following array:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[0])
Example Get the second element from the following array.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[1])
Example Get third and fourth elements from the following array and add them.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[2] + arr[3])

Access 2-D Arrays


To access elements from 2-D arrays we can use comma separated integers
representing the dimension and the index of the element.
Think of 2-D arrays like a table with rows and columns, where the row represents
the dimension and the index represents the column.
Example Access the element on the first row, second column:
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('2nd element on 1st row: ', arr[0, 1])
Example Access the element on the 2nd row, 5th column:
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('5th element on 2nd row: ', arr[1, 4])

Access 3-D Arrays


To access elements from 3-D arrays we can use comma separated integers
representing the dimensions and the index of the element.
Example Access the third element of the second array of the first array:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])

Example Explained
arr[0, 1, 2] prints the value 6.
And this is why:
The first number represents the first dimension, which contains two arrays:
[[1, 2, 3], [4, 5, 6]]
and:
[[7, 8, 9], [10, 11, 12]]
Since we selected 0, we are left with the first array:
[[1, 2, 3], [4, 5, 6]]

84
www.upcissyoutube.com O level M3-R5

The second number represents the second dimension, which also contains two
arrays:
[1, 2, 3]
and:
[4, 5, 6]
Since we selected 1, we are left with the second array:
[4, 5, 6]
The third number represents the third dimension, which contains three values:
4
5
6
Since we selected 2, we end up with the third value:
6

Negative Indexing
Use negative indexing to access an array from the end.
Example Print the last element from the 2nd dim:
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('Last element from 2nd dim: ', arr[1, -1])

NumPy Array Slicing


Slicing arrays
Slicing in python means taking elements from one given index to another given
index.
We pass slice instead of index like this: [start:end].
We can also define the step, like this: [start:end:step].
If we don't pass start its considered 0
If we don't pass end its considered length of array in that dimension
If we don't pass step its considered 1
Example Slice elements from index 1 to index 5 from the following array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5])
Note: The result includes the start index, but excludes the end index.
Example Slice elements from index 4 to the end of the array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[4:])
Example Slice elements from the beginning to index 4 (not included):
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[:4])

85
www.upcissyoutube.com O level M3-R5

Negative Slicing
Use the minus operator to refer to an index from the end:
Example Slice from the index 3 from the end to index 1 from the end:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[-3:-1])

STEP
Use the step value to determine the step of the slicing:
Example Return every other element from index 1 to index 5:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5:2])
Example Return every other element from the entire array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[::2])

Slicing 2-D Arrays


Example From the second element, slice elements from index 1 to index 4 (not included):
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[1, 1:4])
Note: Remember that second element has index 1.
Example From both elements, return index 2:
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 2])
Example From both elements, slice index 1 to index 4 (not included), this will return a 2-D
array:
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 1:4])

NumPy Data Types


Data Types in Python
By default Python have these data types:
 strings - used to represent text data, the text is given under quote marks.
e.g. "ABCD"
 integer - used to represent integer numbers. e.g. -1, -2, -3
 float - used to represent real numbers. e.g. 1.2, 42.42
 boolean - used to represent True or False.
 complex - used to represent complex numbers. e.g. 1.0 + 2.0j, 1.5 + 2.5j

86
www.upcissyoutube.com O level M3-R5

Data Types in NumPy


NumPy has some extra data types, and refer to data types with one character,
like i for integers, u for unsigned integers etc.
Below is a list of all data types in NumPy and the characters used to represent
them.
 i - integer
 b - boolean
 u - unsigned integer
 f - float
 c - complex float
 m - timedelta
 M - datetime
 O - object
 S - string
 U - unicode string
 V - fixed chunk of memory for other type ( void )

Checking the Data Type of an Array


The NumPy array object has a property called dtype that returns the data type of
the array:
Example Get the data type of an array object:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.dtype)
Example Get the data type of an array containing strings:
import numpy as np
arr = np.array(['apple', 'banana', 'cherry'])
print(arr.dtype)

Creating Arrays with a Defined Data Type


We use the array() function to create arrays, this function can take an optional
argument: dtype that allows us to define the expected data type of the array
elements:
Example Create an array with data type string:
import numpy as np
arr = np.array([1, 2, 3, 4], dtype='S')
print(arr)
print(arr.dtype)
For i, u, f, S and U we can define size as well.
Example Create an array with data type 4 bytes integer:
import numpy as np
arr = np.array([1, 2, 3, 4], dtype='i4')
print(arr)
print(arr.dtype)

What if a Value Can Not Be Converted?

87
www.upcissyoutube.com O level M3-R5

If a type is given in which elements can't be casted then NumPy will raise a
ValueError.
ValueError: In Python ValueError is raised when the type of passed argument to a
function is unexpected/incorrect.
Example A non-integer string like 'a' cannot be converted to integer (will raise an error):
import numpy as np
arr = np.array(['a', '2', '3'], dtype='i')

Converting Data Type on Existing Arrays


The best way to change the data type of an existing array, is to make a copy of the
array with the astype() method.
The astype() function creates a copy of the array, and allows you to specify the data
type as a parameter.
The data type can be specified using a string, like 'f' for float, 'i' for integer etc.
or you can use the data type directly like float for float and int for integer.
Example Change data type from float to integer by using 'i' as parameter value:
import numpy as np
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype('i')
print(newarr)
print(newarr.dtype)
Example Change data type from float to integer by using int as parameter value:
import numpy as np
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype(int)
print(newarr)
print(newarr.dtype)
Example Change data type from integer to boolean:
import numpy as np
arr = np.array([1, 0, 3])
newarr = arr.astype(bool)
print(newarr)
print(newarr.dtype)

NumPy Array Copy vs View

The Difference between Copy and View


The main difference between a copy and a view of an array is that the copy is a
new array, and the view is just a view of the original array.
The copy owns the data and any changes made to the copy will not affect original
array, and any changes made to the original array will not affect the copy.
The view does not own the data and any changes made to the view will affect the
original array, and any changes made to the original array will affect the view.

88
www.upcissyoutube.com O level M3-R5

COPY:
Example Make a copy, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42
print(arr)
print(x)
The copy SHOULD NOT be affected by the changes made to the original array.

VIEW:
Example Make a view, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
arr[0] = 42
print(arr)
print(x)
The view SHOULD be affected by the changes made to the original array.

Make Changes in the VIEW:


Example Make a view, change the view, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
x[0] = 31
print(arr)
print(x)
The original array SHOULD be affected by the changes made to the view.

Check if Array Owns its Data


As mentioned above, copies owns the data, and views does not own the data, but
how can we check this?
Every NumPy array has the attribute base that returns None if the array owns the
data.
Otherwise, the base attribute refers to the original object.
Example Print the value of the base attribute to check if an array owns it's data or not:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
y = arr.view()
print(x.base)
print(y.base)
The copy returns none.
The view returns the original array.

89
www.upcissyoutube.com O level M3-R5

NumPy Array Shape


Shape of an Array
The shape of an array is the number of elements in each dimension.
Get the Shape of an Array
NumPy arrays have an attribute called shape that returns a tuple with each index
having the number of corresponding elements.
Example Print the shape of a 2-D array:
import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape)
The example above returns (2, 4), which means that the array has 2 dimensions,
where the first dimension has 2 elements and the second has 4.
Example Create an array with 5 dimensions using ndmin using a vector with values 1,2,3,4
and verify that last dimension has value 4:
import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('shape of array :', arr.shape)

What does the shape tuple represent?


Integers at every index tells about the number of elements the corresponding
dimension has.
In the example above at index-4 we have value 4, so we can say that 5th ( 4 + 1
th) dimension has 4 elements.

NumPy Array Reshaping


Reshaping arrays
Reshaping means changing the shape of an array.
The shape of an array is the number of elements in each dimension.
By reshaping we can add or remove dimensions or change number of elements in
each dimension.

Reshape From 1-D to 2-D


Example Convert the following 1-D array with 12 elements into a 2-D array. The outermost
dimension will have 4 arrays, each with 3 elements:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(4, 3)
print(newarr)

Reshape From 1-D to 3-D


Example Convert the following 1-D array with 12 elements into a 3-D array. The outermost
dimension will have 2 arrays that contains 3 arrays, each with 2 elements:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(2, 3, 2)
print(newarr)

90
www.upcissyoutube.com O level M3-R5

Can We Reshape Into any Shape?


Yes, as long as the elements required for reshaping are equal in both shapes.
We can reshape an 8 elements 1D array into 4 elements in 2 rows 2D array but we
cannot reshape it into a 3 elements 3 rows 2D array as that would require 3x3 = 9
elements.
Example Try converting 1D array with 8 elements to a 2D array with 3 elements in each
dimension (will raise an error):
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
newarr = arr.reshape(3, 3)
print(newarr)

Returns Copy or View?


Example Check if the returned array is a copy or a view:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
print(arr.reshape(2, 4).base)
The example above returns the original array, so it is a view.

Unknown Dimension
You are allowed to have one "unknown" dimension.
Meaning that you do not have to specify an exact number for one of the dimensions
in the reshape method.
Pass -1 as the value, and NumPy will calculate this number for you.
Example Convert 1D array with 8 elements to 3D array with 2x2 elements:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
newarr = arr.reshape(2, 2, -1)
print(newarr)
Note: We can not pass -1 to more than one dimension.

Flattening the arrays


Flattening array means converting a multidimensional array into a 1D array.
We can use reshape(-1) to do this.
Example Convert the array into a 1D array:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
newarr = arr.reshape(-1)
print(newarr)
Note: There are a lot of functions for changing the shapes of arrays in
numpy flatten, ravel and also for rearranging the
elements rot90, flip, fliplr, flipud etc. These fall under Intermediate to Advanced
section of numpy.

91
www.upcissyoutube.com O level M3-R5

NumPy Array Iterating


Iterating means going through elements one by one.
As we deal with multi-dimensional arrays in numpy, we can do this using
basic for loop of python.
If we iterate on a 1-D array it will go through each element one by one.
Example Iterate on the elements of the following 1-D array:
import numpy as np
arr = np.array([1, 2, 3])
for x in arr:
print(x)

Iterating 2-D Arrays


In a 2-D array it will go through all the rows.
Example Iterate on the elements of the following 2-D array:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
for x in arr:
print(x)
If we iterate on a n-D array it will go through n-1th dimension one by one.
To return the actual values, the scalars, we have to iterate the arrays in each
dimension.
Example Iterate on each scalar element of the 2-D array:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
for x in arr:
for y in x:
print(y)

Iterating 3-D Arrays


In a 3-D array it will go through all the 2-D arrays.
Example Iterate on the elements of the following 3-D array:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for x in arr:
print(x)
To return the actual values, the scalars, we have to iterate the arrays in each
dimension.
Example Iterate down to the scalars:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for x in arr:
for y in x:
for z in y:
print(z)

92
www.upcissyoutube.com O level M3-R5

Iterating Arrays Using nditer()


The function nditer() is a helping function that can be used from very basic to
very advanced iterations. It solves some basic issues which we face in iteration,
lets go through it with examples.

Iterating on Each Scalar Element


In basic for loops, iterating through each scalar of an array we need to
use n for loops which can be difficult to write for arrays with very high
dimensionality.
Example Iterate through the following 3-D array:
import numpy as np
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
for x in np.nditer(arr):
print(x)

Iterating Array With Different Data Types


We can use op_dtypes argument and pass it the expected datatype to change the
datatype of elements while iterating.
NumPy does not change the data type of the element in-place (where the element
is in array) so it needs some other space to perform this action, that extra space is
called buffer, and in order to enable it in nditer() we pass flags=['buffered'].
Example Iterate through the array as a string:
import numpy as np
arr = np.array([1, 2, 3])
for x in np.nditer(arr, flags=['buffered'], op_dtypes=['S']):
print(x)

Iterating With Different Step Size


We can use filtering and followed by iteration.
Example Iterate through every scalar element of the 2D array skipping 1 element:
import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
for x in np.nditer(arr[:, ::2]):
print(x)

Enumerated Iteration Using ndenumerate()


Enumeration means mentioning sequence number of somethings one by one.
Sometimes we require corresponding index of the element while iterating,
the ndenumerate() method can be used for those usecases.
Example Enumerate on following 1D arrays elements:
import numpy as np
arr = np.array([1, 2, 3])
for idx, x in np.ndenumerate(arr):
print(idx, x)

93
www.upcissyoutube.com O level M3-R5

Example Enumerate on following 2D array's elements:


import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
for idx, x in np.ndenumerate(arr):
print(idx, x)

NumPy Joining Array


Joining means putting contents of two or more arrays in a single array.
In SQL we join tables based on a key, whereas in NumPy we join arrays by axes.
We pass a sequence of arrays that we want to join to the concatenate() function,
along with the axis. If axis is not explicitly passed, it is taken as 0.
Example Join two arrays
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.concatenate((arr1, arr2))
print(arr)
Example Join two 2-D arrays along rows (axis=1):
import numpy as np
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
arr = np.concatenate((arr1, arr2), axis=1)
print(arr)

Joining Arrays Using Stack Functions


Stacking is same as concatenation, the only difference is that stacking is done
along a new axis.
We can concatenate two 1-D arrays along the second axis which would result in
putting them one over the other, ie. stacking.
We pass a sequence of arrays that we want to join to the stack() method along
with the axis. If axis is not explicitly passed it is taken as 0.
Example
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.stack((arr1, arr2), axis=1)
print(arr)

Stacking Along Rows


NumPy provides a helper function: hstack() to stack along rows.
Example
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.hstack((arr1, arr2))
print(arr)

94
www.upcissyoutube.com O level M3-R5

Stacking Along Columns


NumPy provides a helper function: vstack() to stack along columns.
Example
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.vstack((arr1, arr2))
print(arr)

Stacking along Height (depth)


NumPy provides a helper function: dstack() to stack along height, which is the
same as depth.
Example
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.dstack((arr1, arr2))
print(arr)

NumPy Splitting Array


Splitting is reverse operation of Joining.
Joining merges multiple arrays into one and Splitting breaks one array into
multiple.
We use array_split() for splitting arrays, we pass it the array we want to split
and the number of splits.
Example Split the array in 3 parts:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
print(newarr)
Note: The return value is an array containing three arrays.
If the array has less elements than required, it will adjust from the end accordingly.
Example Split the array in 4 parts:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 4)
print(newarr)
Note: We also have the method split() available but it will not adjust the
elements when elements are less in source array for splitting like in example
above, array_split() worked properly but split() would fail.

Split into Arrays


The return value of the array_split() method is an array containing each of the
split as an array.
If you split an array into 3 arrays, you can access them from the result just like any
array element:

95
www.upcissyoutube.com O level M3-R5

Example Access the splitted arrays:


import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
print(newarr[0])
print(newarr[1])
print(newarr[2])

Splitting 2-D Arrays


Use the same syntax when splitting 2-D arrays.
Use the array_split() method, pass in the array you want to split and the number
of splits you want to do.
Example Split the 2-D array into three 2-D arrays.
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
newarr = np.array_split(arr, 3)
print(newarr)
The example above returns three 2-D arrays.
Let's look at another example, this time each element in the 2-D arrays contains 3
elements.
Example Split the 2-D array into three 2-D arrays.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15],
[16, 17, 18]])
newarr = np.array_split(arr, 3)
print(newarr)
The example above returns three 2-D arrays.
In addition, you can specify which axis you want to do the split around.
The example below also returns three 2-D arrays, but they are split along the row
(axis=1).
Example Split the 2-D array into three 2-D arrays along rows.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15],
[16, 17, 18]])
newarr = np.array_split(arr, 3, axis=1)
print(newarr)
An alternate solution is using hsplit() opposite of hstack()
Example Use the hsplit() method to split the 2-D array into three 2-D arrays along rows.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15],
[16, 17, 18]])
newarr = np.hsplit(arr, 3)
print(newarr)
Note: Similar alternates to vstack() and dstack() are available
as vsplit() and dsplit().

96
www.upcissyoutube.com O level M3-R5

NumPy Searching Arrays


You can search an array for a certain value, and return the indexes that get a
match.
To search an array, use the where() method.
Example Find the indexes where the value is 4:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 4, 4])
x = np.where(arr == 4)
print(x)
The example above will return a tuple: (array([3, 5, 6],)
Which means that the value 4 is present at index 3, 5, and 6.
Example Find the indexes where the values are even:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
x = np.where(arr%2 == 0)
print(x)
Example Find the indexes where the values are odd:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
x = np.where(arr%2 == 1)
print(x)

Search Sorted
There is a method called searchsorted() which performs a binary search in the
array, and returns the index where the specified value would be inserted to
maintain the search order.
The searchsorted() method is assumed to be used on sorted arrays.
Example Find the indexes where the value 7 should be inserted:
import numpy as np
arr = np.array([6, 7, 8, 9])
x = np.searchsorted(arr, 7)
print(x)
Example explained: The number 7 should be inserted on index 1 to remain the sort
order.
The method starts the search from the left and returns the first index where the
number 7 is no longer larger than the next value.

Search from the Right Side


By default the left most index is returned, but we can give side='right' to return
the right most index instead.
Example Find the indexes where the value 7 should be inserted, starting from the right:
import numpy as np
arr = np.array([6, 7, 8, 9])
x = np.searchsorted(arr, 7, side='right')
print(x)

97
www.upcissyoutube.com O level M3-R5

Example explained: The number 7 should be inserted on index 2 to remain the sort
order.
The method starts the search from the right and returns the first index where the
number 7 is no longer less than the next value.

Multiple Values
To search for more than one value, use an array with the specified values.
Example Find the indexes where the values 2, 4, and 6 should be inserted:
import numpy as np
arr = np.array([1, 3, 5, 7])
x = np.searchsorted(arr, [2, 4, 6])
print(x)

NumPy Sorting Arrays


Sorting means putting elements in an ordered sequence.
Ordered sequence is any sequence that has an order corresponding to elements,
like numeric or alphabetical, ascending or descending.
The NumPy ndarray object has a function called sort(), that will sort a specified
array.
Example Sort the array:
import numpy as np
arr = np.array([3, 2, 0, 1])
print(np.sort(arr))
Note: This method returns a copy of the array, leaving the original array
unchanged.
You can also sort arrays of strings, or any other data type:
Example Sort the array alphabetically:
import numpy as np
arr = np.array(['banana', 'cherry', 'apple'])
print(np.sort(arr))
Example Sort a boolean array:
import numpy as np
arr = np.array([True, False, True])
print(np.sort(arr))

Sorting a 2-D Array


If you use the sort() method on a 2-D array, both arrays will be sorted:
Example Sort a 2-D array:
import numpy as np
arr = np.array([[3, 2, 4], [5, 0, 1]])
print(np.sort(arr))

NumPy Filter Array


Getting some elements out of an existing array and creating a new array out of
them is called filtering.
In NumPy, you filter an array using a boolean index list.

98
www.upcissyoutube.com O level M3-R5

A boolean index list is a list of booleans corresponding to indexes in the array.


If the value at an index is True that element is contained in the filtered array, if the
value at that index is False that element is excluded from the filtered array.
Example Create an array from the elements on index 0 and 2:
import numpy as np
arr = np.array([41, 42, 43, 44])
x = [True, False, True, False]
newarr = arr[x]
print(newarr)
The example above will return [41, 43], why?
Because the new filter contains only the values where the filter array had the
value True, in this case, index 0 and 2.

Creating the Filter Array


In the example above we hard-coded the True and False values, but the common
use is to create a filter array based on conditions.
Example Create a filter array that will return only values higher than 42:
import numpy as np
arr = np.array([41, 42, 43, 44])
# Create an empty list
filter_arr = []
# go through each element in arr
for element in arr:
# if the element is higher than 42, set the value to True, otherwise False:
if element > 42:
filter_arr.append(True)
else:
filter_arr.append(False)

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)
Example Create a filter array that will return only even elements from the original array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
# Create an empty list
filter_arr = []
# go through each element in arr
for element in arr:
# if the element is completely divisble by 2, set the value to True,
otherwise False
if element % 2 == 0:
filter_arr.append(True)
else:
filter_arr.append(False)

99
www.upcissyoutube.com O level M3-R5

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)

Creating Filter Directly From Array


The above example is quite a common task in NumPy and NumPy provides a nice
way to tackle it.
We can directly substitute the array instead of the iterable variable in our condition
and it will work just as we expect it to.
Example Create a filter array that will return only values higher than 42:
import numpy as np
arr = np.array([41, 42, 43, 44])
filter_arr = arr > 42
newarr = arr[filter_arr]
print(filter_arr)
print(newarr)
Example Create a filter array that will return only even elements from the original array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
filter_arr = arr % 2 == 0
newarr = arr[filter_arr]
print(filter_arr)
print(newarr)

Array from Numerical Ranges

numpy.arange() in Python
The arange([start,] stop[, step,][, dtype]) : Returns an array with evenly spaced
elements as per the interval. The interval mentioned is half-opened i.e. [Start, Stop)
Parameters :
start : [optional] start of interval range. By default start = 0
stop : end of interval range
step : [optional] step size of interval. By default step size = 1,
For any output out, this is the distance between two adjacent values,
out[i+1] - out[i].
dtype : type of output array
Example:
import numpy as np
print("A\n", np.arange(4).reshape(2, 2), "\n")
print("A\n", np.arange(4, 10), "\n")
print("A\n", np.arange(4, 20, 3), "\n")

100
www.upcissyoutube.com O level M3-R5

numpy.eye() in Python
numpy.eye(R, C = None, k = 0, dtype = type <‘float’>) : –The eye tool returns
a 2-D array with 1’s as the diagonal and 0’s elsewhere. The diagonal can be main,
upper, or lower depending on the optional parameter k. A positive k is for the upper
diagonal, a negative k is for the lower, and a 0 k (default) is for the main diagonal.
Parameters :
R : Number of rows
C : [optional] Number of columns; By default M = N
k : [int, optional, 0 by default]
Diagonal we require; k>0 means diagonal above main diagonal or vice
versa.
dtype : [optional, float(by Default)] Data type of returned array.
Example:
import numpy as np
# 2x2 matrix with 1's on main diagonal
b = np.eye(2, dtype = float)
print("Matrix b : \n", b)

# matrix with R=4 C=5 and 1 on diagonal


# below main diagonal
a = np.eye(4, 5, k = -1)
print("\nMatrix a : \n", a)

101
www.upcissyoutube.com O level M3-R5

Related to Python
eval() Function

Definition and Usage

The eval() function evaluates the specified expression, if the expression is a legal
Python statement, it will be executed.

x='input("Entar a number: ")'


y=eval(eval(x))
print(y)
print(type(y))
Entar a number: 6
6
<class 'int'>

swapcase() Method

Definition and Usage

The swapcase() method returns a string where all the upper case letters are lower
case and vice versa.

x='upciss'
p=x.swapcase()
print(p)
UPCISS

String join() Method

Definition and Usage

The join() method takes all items in an iterable and joins them into one string.

A string must be specified as the separator.

l=['welcome','to','upciss']
msg=' '.join(l)
print(msg)
welcome to upciss

String partition() Method

Definition and Usage

The partition() method searches for a specified string, and splits the string into a
tuple containing three elements.

The first element contains the part before the specified string.

The second element contains the specified string.

102
www.upcissyoutube.com O level M3-R5

The third element contains the part after the string.

l='welcome to upciss youtube channel'


msg=l.partition('upciss')
print(msg)
('welcome to ', 'upciss', ' youtube channel')

islower(), isupper(), istitle(), isspace(), isalpha(), isdigit(), isalnum()

All Function return the Boolean value True/False.

l='Welcome To Upciss Youtube Channel'


msg=l.islower()
print(msg)
False

startswith(), endswith()
l='welcome to upciss'
msg=l.startswith('welcome')
print(msg)
True
ceil, floor, trunc function
import math
k=45.1
print(math.ceil(k)) #return 46 integer not greater than k

k=45.59
print(math.floor(k)) #return 45 integer greater than or equal to k

k=45.59
print(math.trunc(k)) #return 45 simply remove the decimals

DocString
def add(a,b):
"""add 2 number and print with f String method"""
print(f'Total : {a+b}')

add(4,5) # return 9
print(add.__doc__) # return add 2 number and print with f String method

103
www.upcissyoutube.com O level M3-R5

It takes a lot of hard work to make notes, so if you can pay some fee 50, 100,
200 rupees which you think is reasonable, if you are able to Thank you...

नोट् स बनाने में बहुत मेहनत लगी है , इसललए यलि आप कुछ शुल्क 50,100, 200 रूपए जो
आपको उलित लगता है pay कर सकते है , अगर आप सक्षम है तो, धन्यवाि ।

104
O-Level (M4-R5)
Internet of Things and its
UPCISS Applications
Chapter-1
Applications/Devices, Protocols and
Communication Model

Video Tutorial
O-Level M4-R5 Full Video
Playlist Available on
YouTube Channel UPCISS

Free Online Computer Classes on


YouTube Channel UPCISS
www.youtube.com/upciss
For free PDF Notes
Our Website: www.upcissyoutube.com

Copyright © 2022 UPCISS


Contents
Chapter 1- Introduction to Internet of Things --------------------------- 2
Characteristics of IoT............................................................................ 3
How IOT Works .................................................................................... 5
IOT Applications ................................................................................... 6
Building Blocks of IoT ........................................................................... 8
IoT ecosystem ...................................................................................... 9
Component of IoT ecosystem ............................................................ 10
Types of Network ............................................................................... 11
Various technologies and Protocols making up IoT ecosystem. ........ 13
IoT design methodology ..................................................................... 21
The Physical Design/Logical Design of IoT .......................................... 22
IoT Functional Blocks ......................................................................... 22
IoT Communication Models ............................................................... 23
Development Tools used in IoT. ......................................................... 25
Chapter 1 exercise.............................................................................. 27

1
Chapter 1- Introduction to Internet of Things
IoT (Internet of things) ;g ,d ,slk platform gS] tgk¡ regular devices
internet ls tqM+h gksrh gSa] vkSj os ,d&nwljs ds lkFk communicate djrh gSaA IOT
,d network gS tks fcuk fdlh ekuo gLr{ksi ds internet ij data dks store
rFkk exchange dj ldrk gSA ftlesa eq[; #i ls electricity, electronic
components , internet connectivity, software rFkk hardware dh t#jr
gksrh gSA

Internet of things esa things word dk eryc fnu Hkj ds thou esa fdlh Hkh
pht ls gS ftls internet ds ek/;e ls access ;k connect fd;k tk ldrk gSA
IoT ‘kCn dk fodkl lcls igys Kevin Ashton us 1999 esa fd;k FkkA
IoT Advantages IoT Disadvantages
Improved Customer Engagement Security / Privacy
Speed / Automation Complexity
Easy access / M2M Communication Unemployment
Enhanced Data Collection Dependency

2
Characteristics of IoT
Internet of Things (IOT) dk vFkZ ,slh Devices ls gksrh gS tks Internet ls tqM+h
gksrh gSA IOT ds vUnj ,slh Devices vkrh gSa ftuds }kjk Wireless Network esa
Data dks Send rFkk Receive fd;k tkrk gSA

IOT dh Characteristics fuEufyf[kr gSa&

1. Connectivity- IOT dh lcls egRoiw.kZ fo’ks”krk Connectivity gksrh gSA IOT


Devices vkSj muds Components tSls& Sensors, Compute Engine, Data
Hubs vkfn ,d&nwljs ls Connect jgrs gSaA IOT Devices ,d&nwljs ls Radio
Waves, Bluetooth, Wi-Fi, Li-Fi vkfn ds }kjk Connect gks ldrh gSaA
2. Intelligence- IOT esa cgqr lkjh ,slh Algorithms gksrh gSa ftuds }kjk ;g
Intelligent cu tkrk gSA blesa Big Data Analytics vkSj Machine Learning
dk iz;ksx fd;k tkrk gS ftlls fd csgrj Decision fy;k tk ldsA blesa
Situation ds vk/kkj ij Data dks iz;ksx djds mi;ksxh Business Decisions
dks fy;k tkrk gSA blds vk/kkj ij ge dg ldrs gSa fd IOT cgqr gh
Intelligent vkSj Smart gksrk gSA
3. Sensing- fcuk Sensors ds IOT laHko gh ugh gSA Sensors ds ek/;e ls gh
Environment esa gksus okys Changes dks Detect vkSj Measure fd;k tkrk
gSA ge euq”; vius iqjkus vuqHkoksa ds vk/kkj ij viuh ifjfLFkfr;ksa dks vklkuh

3
ls le> ldrs gSa vkSj mUgsa Analyze dj ldrs gSaA ijUrq IOT ds fy, gesa
Analog Signal dks Read djuk iM+rk gS ftlls fd gesa mfpr Insights izkIr
gksaA ge fdlh fo’ks”k Problem ds vk/kkj ij Data dks bdV~Bk djus ds fy,
Electrochemical, Gyroscope, Pressure, Light Sensors, GPS, vkSj RFID
vkfn dk bLrseky djrs gSaA
4. Dynamic Nature- IOT dh ,d fo’ks”krk ;g gS fd bldk Nature Dynamic
gksrk gSA IOT esa Data dks bl izdkj Collect vkSj Convert fd;k tkrk gS
ftlls fd Business Decisions dks fy;k tk ldsA Data dks Collect vkSj
Convert djus ds fy, IOT ds Components dk Nature Dynamic gksuk
pkfg,] vFkkZr~ bldh voLFkk cnyrh jguh pkfg,A
Example- IOT Sensors dks vxj fdlh txg dk Temperature ekiuk gS
rks mls Location vkSj Weather Conditions ds vk/kkj ij Change gksuk
iM+sxkA tSls& Delhi esa vyx Temperature gksxk vkSj Mumbai esa vyx
Temperature gksxkA
5. Scale- IOT vko’;drk ds vuqlkj vius Scale dks cM+k vkSj NksVk dj ldrk
gSA ?kjksa esa IOT dk Scale NksVk gksxk vkSj Factories rFkk Company esa bldk
Scale cM+k gksxkA blds Scale ds vk/kkj ij gh IOT Carriers dks Design
fd;k tkrk gSA
6. Security- IOT dh ,d eq[; fo’ks”krk bldh Security gSA IOT Devices esa
cgqr lkjs Security Threats gksrs gSaA bu Threats ¼[krjksa½ ls cpuk cgqr gh
t:jh gksrk gSA blesa Sensitive Information dks Transfer fd;k tkrk gSA
bl Data dks Hacker ;k Attacker ds }kjk Manipulate vkSj pqjk;k tk
ldrk gSA IOT System dks Design djus ds nkSjku gesa lqj{kk djus pkfg,
tSls& Firewall dks Install djuk] VPN dk Use djuk vkfnA

4
7. Communication- Devices ,d&nqljs ls Communication djus ds fy,
Connect gksrs gSaA Communication cM+h nwjh vkSj NksVk nwjh dk gks ldrk gS
tSls& Wi-Fi vkSj LPWA (Lower Power Wide Area) Network vkfnA
8. Scalability- IOT Infrastructure esa izfrfnu phtsa (Things) c<+rh gh tk jgh
gSaA blfy, IOT dk Setup ,slk gksuk pkfg, tks fd cM+s Expansion ¼foLrkj½
dks Hkh Handle dj ldsA

How IOT Works


iwjh IOT Process Smart Phone, Smart watch, Electronic midj.k tSls TV,
Washing machine tSls midj.kksa ls ‘kq: gksrh gS tks vkidks IOT Platform ds
lkFk Communicate djus esa Help djrh gSaA
Four Fundamental Components of IOT System-
1. Sensors/Devices- Sensor ;k Device ,d izeq[k ?kVd gS tks vkidks
vklikl ds okrkoj.k ls Live Data ,d= djus esa Help djrs gSaA bl Data
esa tfVyrk ds fofHkUu Lrj gks ldrs gSaA ;g ,d Simple Temperature
Monitoring Sensor gks ldrk gS] ;g Video Feed ds :i esa gks ldrk gSA
,d midj.k esa fofHkUu izdkj ds Sensor gks ldrs gSa tks laosnu (Sensing)
ds vykok dbZ dk;Z djrs gSaA
Example- Mobile Phone ,d ,slk midj.k gS ftlesa GPS, Camera tSls
dbZ Sensor gksrs gSaA
2. Connectivity- lHkh Collected Data dks Cloud Infrastructure esa Hkstk
tkrk gSA lapkj ds fofHkUu ek/;eksa dk mi;ksx djds Sensor dks Cloud ls
tksM+k tkuk pkfg,A bu lapkj ek/;eksa esa Satellite Networks, Bluetooth,
Wi-Fi, WAN vkfn ‘kkfey gSaA
3. Data Processing- ,d ckj tc og Data Collect gks tkrk gS] vkSj ;g
Cloud ij ig¡qp tkrk gS] rks Software Collected Data ij Processing

5
djrk gSA ;g izfØ;k dsoy Temperature dh tkap dj ldrh gS vkSj AC ;k
Heater tSls midj.kksa ij mls Read fd;k tk ldrk gSA gkyk¡fd! ;g dHkh&dHkh
cgqr tfVy Hkh gks ldrk gS tSls Video ij Computer Vision dk mi;ksx
djds Objects dh igpku djukA
4. User Interface- Information dks End Users ds fy, fdlh rjg Available
gksuk pkfg, tks muds Phone ij Alarm Trigger djds ;k mUgs E-mail ;k
Text Message ds ek/;e ls Notification Hkstdj izkIr fd;k tk ldsA
Users dks dHkh&dHkh ,d Interface dh vko’;drk gks ldrh gS tks lfØ;
:i ls muds IOT System dh tk¡p djrk gSA
Example- Users ds ?kj esa ,d Camera LFkkfir gSA og Web-Server dh
Help ls Video Recording vkSj lHkh Feeds Access djuk pkgrk gSA gkykafd!
;g ges’kk ,drjQk Communication ugh gksrk gSA IOT Application vkSj
System dh tfVyrk ds vk/kkj ij Users ,d Action ¼fØ;k½ djus esa l{ke
gks ldrk gS tks Cascading Effects iSnk dj ldrk gSA
Example- ;fn dksbZ Users Refrigerator ds Temperature esa fdlh Hkh
cnyko dk irk yxkrk gS] rks IOT rduhd ds }kjk Users dks vius Mobile
Phone dh Help ls Temperature dks Adjust djus esa l{ke gksuk pkfg,A

IOT Applications
Wearable: IoT dk iz;ksx wearable (iguus ;ksX;) esa cgqr T;knk fd;k tkrk
gS tSls fd Smart Watch, Heart rate monitor, Glucose monitoring vkSj
GPS tracking belts etc. ;s devices NksVh gksus dkj.k de energy consume
djrh gS bu devices esa sensor yxk gksrk gS tks fd data dks collect djrk
gSA

6
Health: IoT LokLF; ds {ks= esa ejhtksa vkSj doctors nksuksa ds fy, cgqr
mi;ksxh gSA Hospitals esa Smart beds dk use fd;k tkrk gS] bu beds esa
sensors yxs gksrs gSa tks ejht ds Temperature, Blood pressure vkSj
oximeter etc. dks observe djrs gSaA
Traffic Monitoring: IoT dk bLrseky traffic dks monitor djus esa Hkh fd;k
tkrk gSA blls xkfM+;ksa dh speed dk irk yxk;k tk ldrk gS vkSj traffic
dks Hkh analyze fd;k tk ldrk gS] vkSj ;fn dks okgu traffic rules dk
ikyu ugha djrk rks mls Computer }kjk identify djds mldk challan
dkVk tk ldrk gSA
Agriculture: bldk iz;ksx d`f”k esa Qlyksa vkSj [ksr dh quality dks check
djus esa fd;k tkrk gSA blds fy, [ksr esa sensors yxk;s tkrs gSa tks fd
feÍh fd tkap djrs gSa vkSj data dks collect djrs gSaA tSls& feÍh dk
moisture, acidity, Nutrients and Humidity etc. bl data dks analyze
djds d`f”k dh xq.koRrk dks c<+k;k tk ldrk gS vkSj igys gh fu.kZ; ysdj
Hkfo”; esa uqdlku ls cpk tk ldrk gSA
Smart Home: ?kjksa esa Hkh IoT dk cgqr T;knk use gksrk gSA ?kjksa esa iz;ksx
fd;s tkus okys T;knkrj midj.k smart gks x;s gSa] tSls& AC, Smart TV,
Fridge, LED Bulb, Fan, Smart Door, Washing Machine etc. ftlls
gekjh ftanxh cgqr gh vkjkenk;d gks x;k gSA
Smart City: blesa cgqr lkjs {ks= vkrs gSa tgka ij IoT dk bLrseky fd;k
tkrk gSA tSls&Traffic control, waste management, water distribution,
electricity management, pollution checking etc.
Industrial automation: fdlh Hkh m|ksx esa product dks rst xrh ls vkSj
de [kpZ esa cukuk cgqr t#jh gksrk gSA mlesa IoT cgqr useful lkfcr gksrk
gS] automation dk vFkZ gS fcuk human interaction ds dk;Z djukA IoT
ds ek/;e ls ge automation dks izkIr dj ldrs gSaA

7
Surveillance: bldk iz;ksx Home, Office, Airports, Railway stations
etc. ij fuxjkuh j[kus ds fy, fd;k tkrk gSA CCTV esa [kkl sensor yxk
gksrk gS tks fd fdlh Hkh vlekU; xfrfof/k dks catch dj ldrk gS vkSj
owner dks massage send dj ldrk gSA
bu lc ds vykok vkSj Hkh cgqr ls {ks= gS tgka ij IoT dk use fd;k tkrk gSA

Building Blocks of IoT


pkj phtsa IoT System ds building blocks dks cukrh gSa& Sensors,
Processor, Gateway, Application. ,d mi;ksxh IoT system cukus ds fy,
buesa ls izR;sd node dh viuh ,d fo’ks”krk gksrh gSA

Sensors: Sensors IoT device ds front end gksrs gSaA ftudk eq[; dk;Z
surroundings ;kfu vkl&ikl ls vko’;d data receive djuk vkSj bls
vkxs database ;k processing system rd igaqpkuk gksrk gSA sensors real
time esa data dks collect djrs gSa vkSj fQj vkxs ml data dks process ds
fy, Hkst nsrs gSaA sensor dbZ izdkj ds gksrs ftudk dke vyx&vyx gksrk
gSA Example- gas sensor, water quality sensor, motion sensor,
moisture sensor, image sensor etc.
Processor: Computer vkSj vU; electrical system ds #i esa processor
IoT iz.kkyh dk fnekx gSA Processor dk eq[; dk;Z sensor }kjk collect
row-data dks process djuk vkSj mls lkFkZd tkudkjh vkSj Kku esa cny
nsukA la{ksi esa ge dg ldrs gSa fd bldk dke data dks intelligence nsuk
gSA processor dks application }kjk vklkuh ls control fd;k tk ldrk gS]
vkSj bldk ,d dke data dks lqj{kk iznku djuk Hkh gS] tks fd data dk
encryption and decryption djrs gSaA Example- Microcontroller,

8
embedded hardware devices etc. devices ds Hkhrj yxs processor dk
mi;ksx djds data dks process djrs gSaA

Gateway: bldk eq[; dk;Z process fd;s x;s data dks route djuk vkSj
mfpr mi;ksx ds fy, mfpr database ;k network storage esa transfer
djuk gSA nwljs ‘kCnksa esa gateway data ds lkFk communication es help
djrk gSA IoT system ds fy, communication and network
connectivity vko’;d gSA Example- LAN, WAN, PAN etc.

Application: application IoT system dk nwljk Nksj gSA application


collect fd;s x, lHkh data dk mfpr mi;ksx djrk gS vkSj users dks ml
data ds lkFk interact djus ds fy, interface iznku djrk gSA ;s
application cloud based application gks ldrs gSa tks collect fd;s x,
data dks izLrqr djus ds fy, ftEesnkj gksrs gSaA Application user }kjk
control gksrs gSaA Example- Smart home apps, security system control
application, industrial control hub application etc.
;fn ge IoT ds element dks la{ksi esa le>s rks ge dg ldrs gSa fd
sensor }kjk collect raw data dks processor dks transfer dj fd;k tkrk
gSA processor raw data dks meaningful information esa convert dj
nsrk gS vkSj fQj gateway device connectivity ds ek/;e ls remote
cloud application ;k database system esa transfer dj nsrk gSA

IoT ecosystem
IoT ecosystem different type ds devices dk ,d connection gS] tks
data dks analysis djrk gS vkSj network ij ,d nwljs ds lkFk
communicate djrk gSA IoT ecosystem esa user smart devices tSls fd
Smart phone, tablet, sensors etc. dk iz;ksx network ls tqM+h devices

9
dks command ;k fQj request send djrk gSA devices send fd;s x;s
command ;k request dks analysis djus ds ckn user dks information
okil Hkstrk gSA

Component of IoT ecosystem


IoT ecosystem esa os lHkh element ‘kkfey gSa] tks business,
Government, Consumer dks vius IoT devices ls tqM+us esa l{ke cukrk
gSA IoT u dsoy midj.kksa vkSj oLrqvksa ds chp connectivity dks cny jgk gS]
cYdh ;g yksaxks dks vklkuh ls remote access izkIr djus fd vuqefr Hkh
ns jgk gSA IoT ecosystem esa remote, dashboard, network, gateway,
analytics, data storage vkSj security Hkh ‘kkfey gSA

Gateway: gateway IoT devices vkSj connected network ds chp


internet traffic dks manage djus ds fy, ,d important component
gSA Gateway protocol vkSj network chp move gksus okys data traffic dks
vklkuh ls mange djus esa l{ke gSA Different IoT devices different
network protocol ij dke djrh gSaA Internet application ds fy,
TCP/IP based protocol dk vkerkSj ij iz;ksx fd;k tkrk gSA

Analytics: analytics software IoT devices }kjk generate data dks


analysis djrk gS] vkSj result dks cloud database esa store djrk gSA
Analytics dk mi;ksx fofHkUu izdkj ds ekeyksa ds fy;s fd;k tk ldrk gSA
cM+h companies bulk esa data collect djrh gSa vkSj Hkfo”; ds volj dks
ns[kus ds fy;s bldks analysis djrh gSa] rkfd os vklkuh ls vf/kd O;kikj
mUufr dj ldsa vkSj blesa dqN gkfly dj ldsaA

Cloud: Industry grade IoT lek/kkuksa dks cM+s iSekus ij Row vkSj Process
data dks manage vkSj manipulate dh vko’;drk gksrh gSA vkerkSj ij

10
cloud based architecture dk mi;ksx O;kolkf;d vko’;drkvksa ds vk/kkj
ij mn~ns’; dh iwrhZ ds fy;s fd;k tkrk gSA IoT cloud ecosystem dh en~n
ls company devices vkSj application ls bulk data collect djus esa l{ke
gSA

User Interface: ;g ,d visible vkSj physical fgLlk provide djrk gS]


ftls user }kjk vklkuh ls access fd;k tk ldrk gSA Developer ds fy,
user ds vuqdwy interface cukuk important gS] ftls fcuk fdlh vfrfjDr
iz;kl ds access fd;k tk lds vkSj ;g vklku ckrphr esa en~n dj ldrk
gSA

Dashboard: dashboard user ds fy, IoT ecosystem ds ckjs esa


information display djrk gSA vkSj mUgsa vius IoT ecosystem dks control
djus esa l{ke cukrk gSA ;g vkerkSj ij ,d remote gks ldrk gSA Remote
unit tSls fd mobile application dk mi;ksx djds mUgsa connect vkSj
control djus ds fy;s IoT devices dk mi;ksx laLFkkvksa dks l{ke cukrk gSA
Remote ds mnkgj.k& smart phone, tablet, PC, smart watch vkSj non-
traditional remote gksaxsA

Database: ,d mfpr database system gksuk vko’;d gS] tks different


devices vkSj end-user ls collect fd;s tk jgs data dks store vkSj manage
dj ldsA

Development: IoT technology esa new progress gSA fodkl dh


vko’;drk le; ds lkFk c<+rh vkSj c<+rh tk jgh gSA

Types of Network
Local Lrj ls global Lrj rd] lekt ds fofo/k {ks=ksa esa lHkh Lrjksa ij
networking fodflr dh xbZ gSA blls igys fd ge IoT connectivity

11
protocol dh ckjhfd;ksa ij tk,a] mlls igys ge dqN basic network ds ckjs
esa tku ysrs gSaA Computer network dbZ izdkj ds gksrs gSaA Example- BAN,
PAN, HAN (Home Area Network), NAN (Neighborhood Area
Network ), LAN, MAN, WAN, VPN, CAN (Campus Area Network),
GAN.
BAN (Body Area Network): ,d O;fDr ds ‘kjhj esa igus ;k fQj body
esa dgha ij implanted fd, x, dbZ computing devices dk
interconnection gSA BAN esa vkerkSj ij tsc ;k cSx esa ,d smart phone
‘kkfey gksrk gS] tks mobile data hub ds #i esa dk;Z djrk gS] user data
izkIr djrk gS vkSj bls remote database ;k fQj other system ij
transfer djrk gSA bls WBAN (Wireless Body Area network) ds uke ls
Hkh tkuk tkrk gSA

PAN (Personal Area Network): lcls NksVs network izdkj ds lkFk ‘kq#
gksrk gS] PAN vDlj Laptop, printer, media, system, CCTV etc. bu lc
devices dks tksM+us ds fy, Bluetooth ;k WiFi connectivity ij fuHkZj
jgrk gSA PAN network fdlh dejs ;k ?kj ds vkdkj ftruk NksVk gks ldrk
gS vkSj bls WPAN ds #i esa tkuk tkrk gSA

LAN (Local Area Network): Local Area Network ,d Computer


Network gSA ftldk Use nks ;k nks ls vf/kd Computers dks tksM+us ds fy,
fd;k tkrk gSA ;g ,d dejs ;k ,d Building rd lhfer jgrk gS] ftldh
nwjh yxHkx 1 fdyksehVj rd gks ldrh gSA bls WLAN ds uke ls Hkh tkuk
tkrk gSA WLAN IEEE 802.11 Standard }kjk Define fd;k x;k gSA

MAN (Metropolitan Area Network): Metropolitan Area Network


LAN Network ls cM+k vkSj WAN Network ls NksVk gksrk gSA ;g Network
,d Town ;k City rd lhfer gksrk gS] ftlesa cgqr ls Local Area Network

12
vkil esa tqM+s gksrs gSaA tSls& Cable TV Network. MAN Network dks vkil
esa tksM+us ds fy, Coaxial cables vkSj Fiber Optic Cables dk Use fd;k
tkrk gSA MAN Network Public ;k Private nksuksa rjg dk Network gks
ldrk gSA

WAN (Wide Area Network): Wide Area Network ,d Digital


Communication System gSA WAN Network dk iz;ksx Cities, Countries
vkSj Continents ¼egkn~ohiksa½ dks tksM+us ds fy, fd;k tkrk gSA tSls& Internet.
WAN esa Data Transfer dh Speed LAN dh rqyuk esa yxHkx 10 xquk de
gksrh gSA WAN esa Network dks tksM+us ds fy, Microwave Stations ;k
Communication Satellites dk Use fd;k tkrk gSA

VPN (Virtual Private Network): VPN ,d Virtual Communication


Network gS] tks Computer Network dh cqfu;knh lqfo/kkvksa dk bLrseky
Computer System dks Logical :i ls djrk gSA ;g User ds Connection
izfØ;k dks encrypt djds nwjLFk LFkkuksa ls Network dk mi;ksx djus dh
vuqefr nsrs gq, vkids network rd igqap dks izfrcaf/kr djrk gSA

GAN (Global Area Network): ;g Network vlhfer HkkSxksfyd {ks= dks


Cover djrk gSA ;g ,d Network gS ftldk mi;ksx Wireless LANs,
Satellite coverage {ks=ksa vkfn dh ,d vfu;af=r la[;k esa Mobile dk
leFkZu djus ds fy, fd;k tkrk gSA

Various technologies and Protocols making up IoT ecosystem.

IoT eq[; :i ls Standard Protocol vkSj Networking dk mi;ksx djrk


gSA IoT dh izeq[k l{ke Technologies gSaA Bluetooth, BLE, WiFi, LiFi,
Cellular, ZWave, RFID, NFC, ZigBee, LoRaWAN, 6LoWPAN, GSM,
GPRS, LTE.

13
Bluetooth: Bluetooth ,d Short-range wireless technology gSA ftldk
bLrseky Sort range (approximately 30 feet) esa ,d device ls nwljs
device esa data dks exchange djus ds fy, fd;k tkrk gSA ;g data dks
transfer djus ds fy, ultra high frequency (UHF) radio waves dk
bLrseky djrk gSA ;g ,d personal area network cukrk gSA

Frequency: 2.45 GHz


Maximum data transfer rate: 2.1 Mb/ps
Compatible hardware: Personal computers, Smartphones, Gaming
consoles, Audio devices
Developed by: Bluetooth Special Interest Group
Introduced: 7 May 1998
BLE (Bluetooth low energy): BLE dks vkerkSj ij 4.0 ds :i esa tkuk
tkrk gSA oSls rks Bluetooth cgqr lkjs data dks handle dj ldrk gS] ysfdu
blh ds lkFk ;g Battery dks Hkh cgqr T;knk consume djrk gSA tgka ij
gesa cM+h ek=k esa data dks send ;k receive djus dh vko’;drk ugh gksrh
gS] ogka ij ge BLE dk bLrseky djrs gSaA D;ksa fd ;g lLrk gksus ds lkFk&lkFk
Battery power de yxrh gSA Data transfer rate 1Mb/ps.

14
WiFi (Wireless Fidelity): WiFi ,d wireless technology gS ftldk
mi;ksx Computer, tablet, smartphone vkSj other devices dks ,d nwljs
ls tksM+us ds fy, fd;k tkrk gSA WiFi ,d wireless router ds ikl ds
devices ij Hkstk tkus okyk radio signal gSA WiFi IEEE 802.11 standard
ds family ij based gS vkSj eq[; :i ls ,d LAN technology gSA Data
transfer rate 300Mb/ps.
LiFi (Light Fidelity): LiFi ,d mHkjrh gqbZ technology gS tks data transmit
djus ds fy, radio waves ds ctk; Visible Light Communication (VLC)
technology dk iz;kx djrh gSA ;g light source (Transmitter) }kjk fn,
x, izdk’k dks la’kksf/kr djds fd;k tkrk gS vkSj ,d photodiode (Receiver)
}kjk izkIr fd;k tkrk gSA bldh speed WiFi ls 100 xquk rst gSA

Cellular Network: Cellular network ,d radio network gS tks land


areas ij distribute gksrk gS] ftls cells ds uke ls tkuk tkrk gSA izR;sd
cell fixed location transceiver ij serve ds;k tkrk gSA cellular
technology, mobile phone dk vk/kkj gSA ;s network different
generation esa ekStwn gSa tSls & 2G, 3G, 4G (LTE).

Z-Wave: Z-wave ,d wireless communication technology gS] tks eq[;


#i ls smart home network esa mi;ksx fd;k tkrk gSA ;g mesh network
topology dk mi;ksx djrk gS] vkSj ;g ,d network esa 232 nodes dk
leFkZu djrk gSA bldh data rate yxHkx 30 Meters dh range esa 100
Kbps rd gSA ;g NksVs network ds fy, ZigBee dh rqyuk esa lLrk vkSj
ljy gSA

15
RFID (Radio Frequency Identification): ;g ,d wireless technology
gSA bldk bLrseky fdlh object dks identify ;k fQj Track djus ds fy,
fd;k tkrk gSA blds nks component gksrs gSa] Tag vkSj Reader. ge ftl
object dks track djuk pkgrs gSa ml ij RFID Tag yxk fn;k tkrk gS] fdlh
oLrq ij yxk;s x, RFID Tag dks gh Receiver }kjk detect fd;k tkrk gS]
ftlls ml oLrq dh igpku gksrh gSA bldh range yxHkx 1 miter rd gksrh
gSA RFID Tag nks izdkj ds gksrs gSa Active RFID Tag, Passive RFID Tag.

Active RFID Tag dks viuk work djus ds fy, eryc data transmit djus
ds fy, [kqn dk Power (Electric Supply) gksrk gS] ;kfu ;g self-
Dependent gksrk gSA

Passive RFID Tag ds ikl [kqn dk Power Source ugha jgrk gS cfYd ;g
Receiver ls vkusokyh Radio Wave Signal ls electromagnetic induction
ds fl)kar ij Power cukrk gS] ;kfu ;g Power ds fy, Receiver ij
Depend jgrk gSA

NFC (Near-field communication): ;g ,d wireless technology gSA


;g technology RFID ls izkIr dh xbZ gSA bl technology esa Hkh NFC Tag
vkSj NFC Receiver gksrs gSa] NFC Tag esa tks data Store gksrk gS] mls NFC
Receiver read fd;k tkrk gSA bldh maximum range 10cm rd gh gksrh
gS] vkSj data rate 106, 212, 424 Kbps rd gksrh gSA

ZigBee: ;g ,d wireless technology gS] vkSj eq[; #i ls 802.15.4 ij


based gSA ;g low-cost, low-power dk leFkZu djrk gSA bldk lcls
T;knk bLrseky battry enabled system esa fd;k tkrk gSA ZigBee dbZ
topology dk leFkZu djrk gS tSls& Star, cluster tree, mesh topology.

16
bldh coverage range 100 miter vkSj data transfer rate 250 Kbps rd
gksrh gSA

LoRaWAN (Long Range Wide Area Network): ;g ,d new wireless


technology gSA ;g low-cost, low-power dk leFkZu djrk gS] vkSj bldh
range cgqr T;knk gksrh gS yxHkx 10 ls 15 kilomiter ysfdu data transmit
speed cgqr /kheh gksrh gS (300bps to 37.5 Kbps)A bls fcuk fdlh license
ds radio frequency bands 169 MHz, 433MHz, 868 MHz (Europe) and
915 MHz (North America) and 865 MHz to 867 MHz in India of
LORA.
6LoWPAN (IPv6 over Low power Wireless Personal Area
Networks): ;g ,d wireless sensor network gS] ftldk bLrseky
home-automation, agricultural vkSj industrial monitoring ds fy,
fd;k tkrk gSA ;g IPv6 protocol dk bLrseky djrk gSA

It is used with IEEE 802.15,.4 in the 2.4 GHz band,


Outdoor range: ~200 m (maximum)
Data rate: 200kbps (maximum)
Maximum number of nodes: ~100
GSM (Global System for Mobile communication): GSM ,d open
and digital cellular technology gS] ftldk bLrseky voice and data dks
transmate djus ds fy, fd;k tkrk gS] tks fd 850MHz, 900MHz,
1800MHz and 1900MHz frequency bands ij operate gksrk gSA GSM
technology dks communication purpose ds fy, Time Division
Multiple Access (TDMA) technique dk mi;ksx djds ,d digital system
ds #i esa develop fd;k x;k FkkA

17
GPRS (General Packet Radio Services): GPRS ,d wireless vkSj
cellular network communication services ds fy, lcls vPNk packet-
switching protocol gSA GPRS system GSM network switching dk ,d
integrated part gSA GPRS ls Emails, Multimedia messages, Video
Calls laHko gSA

LTE (Long-Term Evolution): ;g 4G wireless standard gS] tks fd 3G


technology dh rqyuk esa dkQh T;knk Fast gS] ftldh average download
speeds of 15 Mbps to 20 Mbps and average upload speeds of 10
Mbps to 15 Mbps.

18
HTTP ( Hyper Text Transfer Protocol ): HTTP एक ऐसा प्रोटोकॉल है
जिसके द्वारा इं टरनेट में ब्राउज़र से जकसी भी वेबसाइट पर सुरजित कम्युजनकेशन
जकया िा सकता है ।
CoAP (Constrained Application Protocol): The CoAP is an
application layer and web-based protocol designed for constrained
devices like sensors. Sensors have a small memory and limited
processing power. The CoAP is similar to the HyperText Transport
Protocol (HTTP) protocol. CoAP is used as the Representative State
Transfer (REST) architecture.
WebSocket: WebSocket is a computer communications protocol,
providing full-duplex communication channels over a single TCP
connection. The WebSocket protocol was standardized by the IETF
as RFC 6455 in 2011. The current API specification allowing web
applications to use this protocol is known as WebSockets.
MQTT (Message Queuing Telemetry Transport): MQTT (MQ
Telemetry Transport) is a lightweight open messaging protocol that
provides resource-constrained network clients with a simple way to
distribute telemetry information in low-bandwidth environments.
XMPP (Extensible Messaging and Presence Protocol): XMPP is the
Extensible Messaging and Presence Protocol, a set of open
technologies for instant messaging, presence, multi-party chat,
voice and video calls, collaboration, lightweight middleware,
content syndication, and generalized routing of XML data.
DDS (Data Distribution Service): It is an IoT protocol developed for
M2M (Machine to Machine) Communication by OMG (Object
Management Group). It enables data exchange via publish-
subscribe methodology. DDS makes use of brokerless architecture
unlike MQTT and CoAP protocols.

19
AMQP (Advanced Message Queuing Protocol): AMQP a more
advanced protocol than MQTT, more reliable and have better
support for security. AMQP enables encrypted and interoperable
messaging between organizations and applications. The protocol is
used in client/server messaging and in IoT device management.
TCP (Transmission Control Protocol): Transmission Control
Protocol a communications standard that enables application
programs and computing devices to exchange messages over a
network. It is designed to send packets across the internet and
ensure the successful delivery of data and messages over networks
(TCP is a connection-oriented Protocol).
UDP (User Datagram Protocol): In IoT (and data transmission in
general), User Datagram Protocol is less common than TCP. But
UDP often appeals to IoT manufacturers because it uses fewer
network resources to transmit and doesn't have to maintain a
constant connection between the two endpoints (UDP is a
connectionless Protocol).

20
IoT design methodology

IoT design methodology IoT ecosystem esa ,d rjg ls Algorithm dk


dke djrh gSA blesa total 10 step gksrs gSaA IoT ecosystem esa ,d lVhd
result dks ikus ds fy;s gesa bu step dks follow djuk iM+rk gSA

21
The Physical Design/Logical Design of IoT

A physical design of an IoT system refers to the individual node


devices and their protocols that are utilised to create a functional
IoT ecosystem. Each node device can perform tasks such as remote
sensing, actuating, monitoring, etc., by relying on physically
connected devices. It may also be capable of transmitting
information through different types of wireless or wired
connections.
A logical design is a conceptual, abstract design. You do not deal
with the physical implementation details yet; you deal only with
defining the types of information that you need. The process of
logical design involves arranging data into a series of logical
relationships called entities and attributes.

IoT Functional Blocks

एक IoT system में बहुत सारें functional blocks होते है िो जक जसस्टम को indentify,
sensing, actuation, communication और management की िमता प्रदान करते
हैं . इसका जित्र नीिे जदया गया है .

22
IoT Communication Models

अगर communication model प्रभावी होता है तो वह user’s के जलए भी उपयोगी


होता है और इससे business में भी growth होती है . IoT में िार मुख्य
communication models होते हैं िो जक नीिे जदए गये हैं :-
1. Request Response Model
2. Publish Subscribe Model
3. Push Pull Model
4. Exclusive Pair Model
Request Response Model –
Request-Response Model एक कम्युजनकेशन मॉडल होता है जिसमें एक client
(क्लाइं ट), server को एक request भेिता है और server इस request को
respond करता है . इस model को client-server model भी कहते हैं .
इसमें िब भी server जकसी request को receive करता है तो वह request के
आधार पर data को fetch और retrieve करता है तथा उसके बाद response को
client को send कर दे ता है .
उदाहरण के जलए – िब भी कोई client ब्राउज़र में जकसी वेबसाइट को open करने
की request करता है तो server उस request के आधार पर उस वेबसाइट को
open करता है और client को show करता है .

23
Publish Subscribe Model –
यह एक प्रकार का कम्युजनकेशन मॉडल होता है जिसमें publisher, broker और
consumer सम्मिजलत रहते हैं . इसमें publishers डाटा को collect करते हैं और
इस data को publish करते हैं . Broker के द्वारा इस data को manage जकया
िाता है . इस data को consumer के द्वारा subscribe जकया िाता है .
िब भी broker को publisher से कोई data जमलता है तो वह इस data को
subscribe जकये हुए consumer को भेि दे ता है . इसका जित् र नीिे जदया गया है .

Push Pull Model –


इस communication model में , data producer’s के द्वारा data को एक queue
में push जकया िाता है . उसके बाद data collector’s इस data को queue में से
collect करते हैं .
दू सरे शब्ों में कहें तो, “push pull model में data producers डाटा को queue
में push करते हैं और consumers इस data को queue में से pull करते हैं .”
Queue एक buffer की तरह कायय करता है िो जक उन पररम्मथथजतयों में help करता
है िब consumer और producer के rate में असमानता होती है .

24
Exclusive Pair Model –
Exclusive pair एक bi-directional और fully duplex कम्युजनकेशन मॉडल होता
है िो client और server के मध्य एक persistent connection का प्रयोग करता
है .
यह एक fully duplex मॉडल होता है जिसका अथय है जक इसमें client और server
दोनों एक दू सरे को message भेि सकते हैं .

Development Tools used in IoT.

Arduino
यह एक open-source prototyping प्लेटफामय है िो जक आसानी से प्रयोग जकये
िाने वाले हाडय वेयर और सॉफ्टवेयर पर आधाररत होता है . यह एक electronic
board होता है .
Arduino जसस्टम के जदमाग की तरह कायय करता है और sensor में से data को
process करता है . Arduino Board एक छोटा सा CPU होता है जिसमें एक chip
लगी होती है जिसे हम microcontroller या MCU कहते हैं ।
Arduino बोडय का प्रयोग input को read करके electronics को control करने
और इसे output में बदलने के जलए एक उपकरण (device) के रूप में जकया िाता
है ।

25
Tessel 2
इसका प्रयोग बेजसक IoT prototypes और applications को बनाने के जलए जकया
िाता है . Tessel 2 एक development board है जिसके पास wifi की िमताएं
होती है और इसके द्वारा हम Node.js में scripts को बना सकते है .
इसके पास ethernet connectivity, Wi-Fi connectivity, दो USB ports, एक
micro USB ports, 32 MB का flash, और 64MB की RAM होती है . इसमें हम
अजतररक्त modules को भी िोड़ सकते हैं िैसे जक – कैमरा, accelerometers,
RFID और GPS आजद.
इसके पास दो processors होते हैं . पहला प्रोसेसर firmware applications को
बहुत तेि speed में run करने में मदद करता है और दू सरा प्रोसेसर power को
प्रभावी ढं ग से manage करने में और input/output को control करने में मदद
करता है .

26
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.

Chapter 1 exercise
1. ___ “Central Nervous System” gS tks IOT esa global services dk /;ku j[krk gS\
a. Perception Layer
b. Network Layer
c. Application Layer
d. None of these.
2. IOT dh izeq[k fo’ks”krk,a dkSu lh gSa\
a. Heterogeneity ¼fofo/krk½
b. Connectivity
c. Safety
d. All of the above.
3. Dashboards dk mi;ksx djds connect and control djus ds fy, IOT devices dk use djus okyh laLFkkvksa dks l{ke
djrk gS ___\
a. Smartphones
b. Tablet and PC
c. Smart Watches
d. All of the above.
4. fuEu esa ls dkSu short-range wireless network dk example gS\
a. WWW
b. Internet

27
c. Wi-Fi
d. VPN

5. IOT Architecture dh lcls lowest layer ¼fupyh ijr½ dkSu lh gS\


a. Gateway
b. Smart Devices
c. Cloud
d. None of these.
6. WiFi-ah (HaLow) fo’ks”k :i ls ___ ds fy, design fd;k x;k gS\
a. 802.11
b. Long range
c. Low power
d. All of the above.
7. fuEufyf[kr esa ls dkSu lk protocol ,d publish-subscribe architecture gS\
a. CoAP
b. HTTPS
c. MQTT
d. HTTP
8. fuEufyf[kr esa ls IOT esa use dh tkus okyh wireless technology esa ls dkSUk de ls de power consume djrk gS\
a. GSM/CDMA
b. Wi-Fi
c. Bluetooth
d. Zigbee
9. fuEufyf[kr esa ls dkSu IOT dk main element ugh gS\
a. Things
b. Security
c. Process
d. People
10. ZigBee fuEufyf[kr esa ls fdl ekud (standard) ij based gS\
a. IEEE 802.15.4
b. IEEE 802.5
c. IEEE 802.4.13
d. Both (a) and (b).
11. LoRa stands for ___ ?
a. Long Range Radio
b. Low Radio Range
c. Level Range Radio
d. None of these.
12. IOT device dks data ds lkFk tksM+us dk rjhdk fuEu esa ls dkSu lk gS\
a. Network
b. Automata
c. Cloud
d. Internet
13. ___ Resources dh deh okys devices ds fy, ,d application layer protocol gS\
a. TCP / IP
b. MQTT
c. HMTP
d. CoAP
14. IOT esa ,d Entity ?
a. Business

28
b. Government
c. Consumer
d. All of the above.
15. IOT esa lcls vf/kd mi;ksx fd, tkus okys protocol ___ gSa\
a. MQTT
b. ZigBee
c. XMPP
d. All of the above.
16. IOT applications esa Lightweight protocol ds fy, fuEufyf[kr esa ls fdldk mi;ksx fd;k tkrk gS\
a. MQTT
b. WebSocket
c. HTTP
d. All of the above.
17. MQTT Suite ¼lwV½ gS ___\
a. Small and Cheap Equipment
b. Low Memory Device
c. Low Power Equipment
d. All of the above.
18. 6LoWPAN ___ gS\
a. IPv6 over low power wireless personal area network.
b. IPv4 over low power wireless private area network.
c. IPv6 over low energy wired personal area network.
d. IPv4 over long range wireless private area network.
19. Cellular Network esa mi;ksx fd, tkus okys fofHkUu wireless standards ___ gSa\
a. GSM
b. CDMA
c. LTE
d. All of the above.
20. RFID Technique esa ___ fuEufyf[kr ‘kkfey gSa\
a. Antenna
b. Transponder
c. Transceiver
d. All of the above.

29
It takes a lot of hard work to make notes, so if you can pay some fee 100, 200
rupees which you think is reasonable, if you are able, Thank you...
नोट् स बनाने में बहुत मेहनत लगी है , इसजलए यजद आप कुछ शुल्क 100, 200 रूपए िो आपको
उजित लगता है pay कर सकते है , अगर आप सिम है तो, धन्यवाद ।

30
UPCISS
O-Level (M4-R5)
Internet of Things and its
Applications

Chapter-2
Things and Connections

Video Tutorial
O-Level M4-R5 Full Video
Playlist Available on
YouTube Channel UPCISS

Free Online Computer Classes on


YouTube Channel UPCISS
www.youtube.com/upciss
For free PDF Notes
Our Website: www.upcissyoutube.com

Copyright © 2022 UPCISS


Contents
Chapter 2- Things and Connections .................................................... 2
Working of Controlled Systems .......................................................... 2
Types of Control System ..................................................................... 3
Connectivity models – TCP/IP and OSI model .................................... 5
OSI Model ........................................................................................... 5
TCP/IP Model ...................................................................................... 9
Transmission Mode .......................................................................... 11
Wired and Wireless Methodology .................................................... 12
Wired Transmission Media ............................................................... 12
Wireless Transmission Media ........................................................... 14
The process flow of an IoT application. ............................................ 16
Chapter 2 exercise ............................................................................ 16

1
Chapter 2- Things and Connections
Working of Controlled Systems
,d Control System mechanical ;k electronic devices dk ,d lsV gS
tks Control loops ds ek/;e ls other devices ;k systems dks control
djrk gSA IoT esa vkerkSj ij controlled system computerized gksrk gSA

Controlled system ds vkt fofHkUu mi;ksx gSaA Industry esa bu systems


dk mi;ksx vU; machines ds mRiknu ;k dke dks control djus ds fy,
fd;k tkrk gSA fofHkUu izdkj ds controlled system fofHkUu purpose ds
fy, dke djrs gSaA controlled system ,d machine ds O;ogkj vkSj dk;Z
dk management djrh gSA

Programmable logical controllers (PLCs), Programmable


automation controllers (PACs), Remote terminal units (RTUs),
Intelligent electronic devices (IEDs) vkSj Sensors control loops ;s dqN
,sls element gSa] tks control system dk ,d fgLlk gSaA control loop tks
controlled system cukrs gSa] os vkerkSj ij ,d sensor, controller vkSj
controller element ls cus gksrs gSaA

fofHkUu izdkj ds controlled system gSa] ysfdu ;s lHkh output control


djus ds fy, cukbZ xbZ gSaA Situation, Velocity, Acceleration,
Temperature, Pressure, Voltage vkSj Current vkfn dks control djus ds
fy, mi;ksx dh tkus okyh system, controlled system ds mnkgj.k gSaA
system manufacturing process vkSj Activities dks ekirs gSa] fuxjkuh
djrs gSa vkSj control djrs gSaA os Specified value ls ;k rks manual :i
ls ;k automatic :i ls fdlh Hkh vlkekU;rkvksa (Abnormalities) ;k
fofo/krkvksa (Variations) dh igpku djrs gSa vkSj mUgs Bhd djrs gSaA

2
Features of control system: Accuracy, Energy Saving, Improved
Safety, Stability, Speed etc…

Types of Control System


Open Loop Control System.
Open Loop Control System को none feedback control system भी कहा जाता है
क्योकक Open loop control system ककसी भी प्रकार का कोई भी feedback signal या कोई
भी error signal नहीीं दे ता| open loop control system एक बहुत ही कसींपल सा circuit होता
है , जै से की जो हमारे घरोीं में पानी गमम करने वाला हीटर होता है वो हीटर open loop control
system का एक example है | जब हम हीटर को चालू करते है तो वो अपने working के अनुसार
गमम होना चालू हो जाता है ले ककन temperature तब तक बढ़ता जाएगा जब तक हम उसकी
सप्लाई बींद नहीीं कर दे ते क्योकक एक कसींपल से हीटर में feedback दे ने के कलए कोई भी
component नहीीं लगा होता जो temperature को सेंस करके हीटर के सककमट को फीडबैक
दे , कजसकी वजह से हीटर का temperature तब तक बढ़ता जाता है जब तक उसकी supply
को बींद नहीीं ककया जाता| इसी प्रकार हीटर की तरह ही open loop control system के कोई
और भी example है जै से की ceiling fan या कफर table fan.

Closed Loop Control System.


Closed loop control system को feedback control system भी कहााँ जाता है क्योकक जो
circuit closed loop control system में कडज़ाइन ककये जाते है वो सककमट feedback या error
signal दे ते है | अगर हमको closed loop control system को समझना है तो हम अपने घरो
के A.C (Air Conditioner) से समझ सकते है | जै से की अगर हम अपने A.C को चालू करते है
तो सबसे पहले हम A.C में temperature सेट करते है की हमको ककतना temperature चाकहए,
उसके बाद A.C में लगा Temperature Controller Sensor, room के temperature को सेंस
करके A.C के सककमट को feedback भेजता है और कफर A.C तब तक cooling करता रहता है
जब तक room का temperature हमारे द्वारा सेट ककए गए temperature तक नहीीं पहुीं च
जाता| जै से की अगर हमने A.C में 18 कडग्री temperature सेट कर कदया तो A.C तब तक चालू
रहे गा जब तक room का temperature 18 कडग्री तक नहीीं पहुीं च जाता|

3
Difference between Open and Closed Loop Control System.

Open Loop Control System Closed Loop Control System


The feedback element is absent The feedback element is always present
An error detector is not present An error detector is always present
It is a stable one It may become unstable
Easy to construct Complicated construction
It is cost effective It is costly
It is inaccurate It is accurate
Less maintenance More maintenance
It is unreliable It is reliable
Examples: Hand drier, tea maker Examples: voltage stabilizer, AC

Real-time System: Real-time System is a system that is used for


performing some specific tasks. These tasks are related with time
constraints and need to be completed in that time interval.
Common examples of real-time systems include air traffic control
systems, process control systems, and autonomous driving
systems.
रीयल-टाइम कसस्टम एक ऐसी प्रणाली है कजसका उपयोग कुछ कवकिष्ट कायों को करने के कलए
ककया जाता है । ये कायम समय की कमी से सींबींकित हैं और उन्हें उस समय अींतराल में पूरा करने
की आवश्यकता है । रीयल-टाइम कसस्टम के सामान्य उदाहरणोीं में हवाई यातायात कनयींत्रण
प्रणाली, प्रकिया कनयींत्रण प्रणाली और स्वायत्त डराइकवींग कसस्टम िाकमल हैं ।

4
Connectivity models – TCP/IP and OSI model
OSI Model
OSI Model का पूरा नाम Open System Interconnection है इसे ISO (International
Organization for Standardization) ने 1984 में कवककसत ककया था और इस मॉडल में 7 layers
होती है । OSI Model ककसी नेटवकम में दो यूज़सम के मध्य कम्युकनकेिन के कलए एक reference
मॉडल है ।

इस मॉडल की प्रत्येक ले यर दू सरे ले यर पर कनभमर नही रहती है ले ककन एक ले यर से दू सरे ले यर में


डे टा का टर ाीं सकमिन होता है । OSI मॉडल एक रे फेरें स मॉडल है अथाम त् इसका इस्तेमाल real life
में नही होता है बल्कि इसका इस्तेमाल केवल reference (सींदभम) के रूप में ककया जाता है .

OSI model यह बताता है कक ककसी नेटवकम में डे टा या सूचना कैसे send तथा receive होती है ।
इस मॉडल के सभी layers का अपना अलग अलग काम होता है कजससे कक डे टा एक कसस्टम से
दू सरे कसस्टम तक आसानी से पहुाँ च सके। OSI मॉडल यह भी describe करता है कक नेटवकम
हाडम वेयर तथा सॉफ्टवेयर एक दू सरे के साथ ले यर के रूप में कैसे कायम करते है । इस मॉडल की 7
ले यर होती है और प्रत्येक ले यर का अपना एक कविे ष कायम होता है .

7 Layers of OSI Model

5
Physical Layer
OSI model में physical ले यर सबसे नीचे की ले यर है । यह ले यर कफकजकल तथा इले ल्कररकल
कनेक्शन के कलए कजम्मेदार रहता है जै से:- वोल्टे ज, डे टा रे ट् स आकद। इस ले यर में कडकजटल कसग्नल,
इले ल्कररकल कसग्नल में बदल जाता है । इस लेयर में नेटवकम की topology अथामत layout of
network का कायम भी इसी ले यर में होता है ।

कफकजकल ले यर यह भी describe करता है कक कम्युकनकेिन wireless होगा या wired होगा। इस


ले यर को कबट यूकनट भी कहा जाता है ।

Function of Physical Layer


Physical layer यह define करती है कक दो या दो से ज्यादा devices आपस में physically कैसे
connect होती है . इसके द्वारा यह कडफाइन ककया जाता है कक नेटवकम में दो devices के मध्य
कौनसा transmission mode होगा. Simplex, half-duplex, और full duplex में से कौन सा होगा.
यह information को टर ाीं सकमट करने वाले कसग्नल को कनिाम ररत करता है .

Data Link Layer


OSI MODEL में डे टा कलीं क ले यर नीचे से दू सरे नींबर की ले यर है । इस ले यर की दो sub-layers होती
है :- MAC (Media Access Control) & LLC (Logical Link Control).

इस ले यर में नेटवकम लेयर द्वारा भेजे गए डे टा के पैकेटोीं को decode तथा encode ककया जाता है
तथा यह ले यर यह भी ensure करता है कक डे टा के ये पैकेट् स error free हो।

इस ले यर को फ्रेम यूकनट भी कहा जाता है । इस layer में डे टा टर ाीं सकमिन के कलए दो प्रोटोकॉल
प्रयोग होते है . HDLC (High-level data link control) & PPP (Point-to-Point Protocol).

Function of Data Link Layer


यह ले यर, physical raw bit stream को packets में translate करती है . इन packets को हम
frames कहते है . और यह layer इन frames में header और trailer को add करती है .

इसका मुख्य कायम flow control करना है . इसमें receiver और sender दोनोीं तरफ से एक कनयत
data rate को maintain ककया जाता है . कजससे कक कोई भी data corrupt ना हो.

जब दो या दो से अकिक devices एक communication channel से जुडी रहती है तब यह layer


यह कनिाम ररत करती है कक ककस कडवाइस को access कदया जाए.

Network Layer
नेटवकम ले यर OSI model का तीसरा ले यर है इस ले यर में switching तथा routing तकनीक का
प्रयोग ककया जाता है । इसका कायम Logical address अथाम त IP address भी उपलब्ध कराना है ।

6
नेटवकम ले यर में जो डे टा होता है वह पैकेट (डे टा के समूह) के रूप में होता है और इन पैकेटोीं को
source से destination तक पहुाँ चाने का काम नेटवकम ले यर का होता है । इस ले यर को पैकेट यूकनट
भी कहा जाता है ।

Function of Network Layer


नेटवकम ले यर की मुख्य कजम्मेदारी inter-networking की होती है . यह अलग-अलग devices में
logical connection उपलब्ध करवाती है .

यह frame के header में source और destination address को add करती है . Address का


इस्तेमाल इन्टरनेट में devices को identify करने के कलए ककया जाता है .

इस layer का काम routing का भी है . यह सबसे अच्छे path (रास्ते) को कनिाम ररत करती है .

Transport Layer
टर ाीं सपोटम ले यर OSI मॉडल की चौथी ले यर है । इस ले यर का प्रयोग डे टा को नेटवकम के मध्य में से
सही तरीके से टर ान्सफर ककया जाता है । इस ले यर का कायम दो कींप्यूटरोीं के मध्य कम्युकनकेिन को
उपलब्ध कराना भी है । इसे सेगमेंट यूकनट भी कहा जाता है ।

Function of Transport Layer


Transport layer का मुख्य कायम data को एक कींप्यूटर से दू सरे computer तक transmit करना
है . जब यह layer उपरी layers से message को recieve करती है तो यह message को बहुत सारें
segments में कवभाकजत कर दे ती है . और प्रत्येक segment का एक sequence number होता है
कजससे प्रत्येक segment को आसानी से identify ककया जा सके.

यह दो प्रकार की service प्रदान करती है :- Connection Oriented (TCP) और Connection Less


(UDP). यह flow control और error control दोनोीं प्रकार के कायों को करती है .

Session Layer
सेिन ले यर OSI model की पाीं चवी ले यर है जो कक बहुत सारें कींप्यूटरोीं के मध्य कनेक्शन को
कनयींकत्रत करती है । सेिन ले यर दो कडवाइसोीं के मध्य कम्युकनकेिन के कलए सेिन उपलब्ध कराता
है अथामत जब भी कोई यूजर कोई भी वेबसाइट खोलता है तो यूजर के कींप्यूटर कसस्टम तथा
वेबसाइट के सवमर के मध्य तक सेिन का कनमाम ण होता है ।

आसान िब्ोीं में कहें तो सेिन ले यर का मुख्य कायम यह दे खना है कक ककस प्रकार कनेक्शन को
establish, maintain तथा terminate ककया जाता है ।

Function of Session Layer

7
Session layer जो है वह dialog controller की भाीं कत कायम करती है . यह दो processes के मध्य
dialog को create करती है . यह synchronization के कायम को भी पूरा करती है . अथाम त् जब भी
transmission में कोई error आ जाती है तो टर ाीं सकमिन को दु बारा ककया जाता है .

Presentation Layer
Presentation ले यर OSI मॉडल का छटवाीं ले यर है । इस ले यर का प्रयोग डे टा का encryption तथा
decryption के कलए ककया जाता है । इसे डे टा compression के कलए भी प्रयोग में लाया जाता है ।
यह ले यर ऑपरे कटीं ग कसस्टम से सम्बींकित है ।

Function of Presentation Layer


इस layer का कायम encryption का होता है . Privacy के कलए इसका use ककया जाता है .
इसका मुख्य काम compression का भी है . Compression बहुत जरुरी होता है क्योींकक हम data
को compress करके उसके size को कम कर सकते है .

Application Layer
एप्लीकेिन ले यर OSI model का सातवााँ (सबसे उच्चतम) लेयर है । एप्लीकेिन ले यर का मुख्य
कायम हमारी वास्तकवक एप्लीकेिन तथा अन्य Layer के मध्य interface कराना है ।

एप्लीकेिन ले यर end user के सबसे नजदीक होती है । इस ले यर के


अींतगमत HTTP, FTP, SMTP तथा NFS आकद प्रोटोकॉल आते है ।

यह ले यर यह कनयींकत्रत करती है कक कोई भी एप्लीकेिन ककस प्रकार नेटवकम से access करती है ।

Function of Application Layer


Application layer के द्वारा यूजर remote computer से files को access कर सकता है और
files को retrieve कर सकता है . यह email को forward और स्टोर करने की सुकविा भी दे ती है .
इसके द्वारा हम डे टाबेस से directory को access कर सकते हैं .

8
TCP/IP Model
TCP/IP का पूरा नाम Transmission control protocol (TCP) तथा internet protocol (IP) है ।
TCP/IP वर्ल्म वाइड वेब (WWW) का एक प्रोटोकॉल है कजसे हम इीं टरनेट कहते है । इस मॉडल को
internet में packets को send करने के कलए कडजाईन ककया गया है . TCP/IP मॉडल end-to-end
कम्युकनकेिन प्रदान करता है । इसको 1970 तथा 1980 के दिक के मध्य Department of
Defense (D.O.D.) ने कवककसत ककया था।

यह model यह कनिाम ररत करता है कक एक कविेष computer ककस प्रकार से internet से connect
होता है और उनके मध्य data का transmission ककस प्रकार होता है . जब बहुत सारें computer
networks आपस में जुड़े होीं तो यह मॉडल हमें virtual network बनाने में मदद करता है . TCP/IP
model का मुख्य उद्दे श्य बहुत दू री पर communication प्रदान करना है . अथाम त हम इसके द्वारा
बहुत दू री पर ल्कथथत network से भी communicate कर सकते हैं .
4 Layer of TCP/IP Model

Network Access Layer

यह ले यर TCP/IP मॉडल की सबसे कनम्नतम (lowest) ले यर है । नेटवकम एक्से स ले यर यह describe


करती है कक ककस प्रकार डे टा नेटवकम में sent होता है । यह ले यर, OSI model में define ककये गये
data link layer और physical layer का एक combination होता है .

यह layer एक ही network में दो devices के बीच होने वाले data के transmission के कलए
कजम्मेदार होती है . इस layer का कायम नेटवकम के द्वारा transmit ककये गये IP datagram को
frames में encapsulate करना है और IP address को physical address में map करना है . इस
ले यर के द्वारा प्रयोग ककये जाने वाले protocols हैं :- Ethernet, FDDI, token ring, x.25, frame
Relay.

9
Internet Layer

यह ले यर टर ाीं सपोटम लेयर तथा एप्लीकेिन ले यर के मध्य ल्कथथत होती है । इसमें डे टा को IP


datagrams के रूप में पैकेज ककया जाता है यह datagram source तथा destination IP एडर े स
को contain ककये रहते है कजससे कक डे टा को आसानी से sent तथा receive ककया जा सकें। इसको
network layer भी कहते हैं .
Transport Layer (Host to Host)

यह ले यर डे टा के टर ाीं सकमिन के कलए कजम्मेदार होती है यह ले यर एप्लीकेिन ले यर तथा इीं टरनेट


ले यर के मध्य ल्कथथत होती है । यह data की reliability, flow control और correction के कलए भी
कजम्मेदार होता है .

इस ले यर में दो मुख्य प्रोटोकॉल कायम करते है :-


Transmission control protocol (TCP) & User datagram Protocol (UDP)
Application Layer

यह ले यर TCP/IP मॉडल की सबसे उच्चतम ले यर है । यह ले यर ऍल्कप्लकेिन्स को नेटवकम सकवमस


उपलब्ध करने से सम्बींकित होती है । यह ले यर यूजर को कम्युकनकेिन उपलब्ध कराती है ; जै से:-
वेब ब्राउज़र, ई-मेल, तथा अन्य ऍल्कप्लकेिन्स के द्वारा।

Application लेयर टर ाीं सपोटम ले यर को डे टा भेजती है तथा उससे डे टा receive करती है । यह layer
यूजर को application के साथ interact करने की सुकविा प्रदान करती है .
Difference between OSI Model and TCP/IP Model
OSI Model TCP/IP Model
OSI का पूरा नाम open system interconnection इसका पूरा नाम transmission control protocol /
है . internet protocol है .
इसे ISO ने कवककसत ककया है . इसे APRANET ने कवककसत ककया है .

इसमें 7 लेयर होती है . इसमें 4 layer होती है .

यह vertical एप्रोच को follow करता है . यह horizontal एप्रोच को follow करता है .

इस मॉडल का इस्तेमाल बहुत कम ककया जाता है . इस model का उपयोग ज्यादा ककया जाता है .

10
Transmission Mode
वह डायरे क्शन कजस पर डे टा या सूचना एक थथान से दु सरे थथान पर टर ाीं सकमट होती है
transmission mode कहलाती है . यह सूचना के flow होने की कदिा को indicate करता है . इसे
communication mode भी कहते है . यह 3 Types के होते है :

Simplex, Half-duplex and Full-duplex


Simplex
Simplex का अथम है कक कम्युकनकेिन केवल एक ही कदिा में होगा. अथाम त sender केवल डे टा
को send कर सकता है परन्तु recieve नही कर सकता है .

Example: Radio, TV, Remote, etc...

Half-duplex
Half-duplex में हम दोनोीं कदिाओीं में डे टा को send तथा recieve कर सकते है ले ककन एक समय
में केवल एक ही कदिा में. अथामत इसमें एक ही समय में send तथा recieve दोनोीं कायम नही हो
सकते है . इस mode को कभी-कभी semi-duplex भी कहते है .

Example: walkie-talkie

Full-duplex
इसमें हम डे टा को एक ही समय में send भी कर सकते है तथा recieve भी कर सकते है . यह
सबसे ते ज डायरे क्शनल mode है .

Example: Telephone

11
Wired and Wireless Methodology

Wired Transmission Media


वह Transmission Media कजसमे दो Devices के मध्य कनेक्शन Physical Method जै से केबल
या वायर के द्वारा होता है उसे Wired Transmission Media कहते है . इसे Guided Media भी
कहते है . ये कनम्नकलल्कखत प्रकार के होते है :
Twisted Pair Cable
Coaxial Cable
Fiber-Optic Cable

Twisted Pair Cable


Dataके Transmission के कलए उपयोग में लाया जाने वाला सबसे आसान माध्यम Twisted Pair
Wires होते है । इस माध्यम मे दो Copper Wire के Pair को कलया जाता है । इन्हें Plastic Cover कक
सहायता से Insulated कर कदया जाता है । इसके पश्चात दोनो Wire को आपस में Twist कर कदया
जाता है । कजससे यह एक तस्सी के समान आकार मे हो जाते है ।

इन दोनो Wire को समान्तर नही रखा जा सकता है , क्योकक समान्तर रखने पर भेजे गए Signal
आपस में Mix हो सकते है । Twisted Pair में उपयोग मे लाया जाने वाला Copper Wire सामान्यतः
1 Mm कक गोलाई का होता है । इस Media का उपयोग सबसे अकिक Telephone Lines में ककया
जाता है । Computer N/W में Use में लाया जाने वाला यह Media Unshielded Twisted Pair
(UTP) कहलाता है इस माध्यम से 10 Km तक कक Range में Date को 1 MBPS से अकिक की
Speed पर भेजा जा सकता हे ।

12
Coaxial Cable
Twisted Pair Cable पर अकिक मात्रा में Signal नही भेजे जा सकते है यकद Video Signal को
Transmit करना हो, तब Twisted Pair का उपयोग सींभव नही हो सकता है । इस कारण से Heavy
Signal को Transfer करने के कलए Coaxial Cable का उपयोग ककया जाता है । एक Coaxial cable
मे सबसे आीं तररक स्तर पर Copper Wire कक Core Cable होती हें कजस पर Plastic Material का
एक आवरण रहता है । इस Plastic Material Aluminium कक Conductor Layer होती है । जो
जालीदार रूप में रहती है , इस जालीदार Conductor Plastic Material का Cover रहता है ।
Coaxial Cable का अकिकतम उपयोग Cable T.V. Network, CCTV Cable में ककया जाता है ।

Fiber-Optic Cable
Fiber Optics एक ऐसा माध्यम है , कजसमें Digital Data को प्रकाि की गकत से Transmit ककया
जाता है । यहा Date को 0 और 1 के Signal के रूप में भेजना बहुत आसान होता है , क्योकक जब
Signal के रूप में Light भेजी जाए, जब उसे 1 माना जाता है और जब Light ना भेजी जाए तब उसे
0 माना जाता है । Fiber Optic Cable को डाटा भेजने का सबसे ते ज माध्यम माना जाता है ।

Light Source: यह एक कवषेि प्रकार की Frequency पर ककसी Source के माध्यम से प्रकाि कक


ककरण उत्पन्न कक जाती है ।

Fiber Media: Source द्वारा उत्पन्न कक गई प्रकाि कक ककरण को लीं बी दू री तक Transmit करने
के कलए लचीले Glass Material कक Tube कक आीं तररक सतह Glass के समान Smooth होती है ।
परन्तु उपरी सतह को खुदरा कर कदया जाता है कजससे जब भी Source द्वारा प्रकाि के ककरण भेजी
जाती है , वह Tube से बाहर Transmit नही पाती है । जब भी Source द्वारा प्रकाि कक ककरण भेजी
जाती है , वह Tube कक आीं तररक सतह से परावकतम त होकर Transmit होती रहती है ।

Detector: Fiber Tube के दु सरे कसरे पर Photo Detector लगे होते है , जो Light के रूप में आने
वाले Signal को पहचान ले ते है और उन्हें 0 या 1 के रूप में पररवकतम त कर ले ते है ।

13
Wireless Transmission Media
Communication के कलए सभी थथानोीं पर Physical Connection बना पाना सींभव नही है । इसी
कारण से Air में ऐसी तरीं गो का उपयोग ककया जाता है , कजसे हम electromagnetic wave या
electromagnetic spectrum के नाम से जानते हैं , जो वातावरण में Signal को कबना ककसी
नुकसान के एक थथान से दु सरे थथान तक पहुीं चा सके। यह माध्यम Unguided या Wireless
कहलाता है । Wire Less Media के रूप में सबसे पहले Radio Waves का उपयोग ककया गया।
Radio Waves सामान्यतः Circular Wave होती है जो ककसी भी कदिा में प्रसाररत कक जा सकती
है । इस Communication का सबसे मुख्य Advantages यह है कक इससे कमलने वाले Signal को
Unlimited सींख्या में User के द्वारा Access ककया जा सकता है परीं तु इस माध्यम में Data के Loss
होने की सींभावना सबसे अकिक होती है ।

Electromagnetic Waves अपने साथ electromagnetic field की electromagnetic energy को


carry करती हैं space के माध्यम से. Electromagnetic Waves में Gamma Rays , X – Rays,
Ultraviolet Rays, Visible Light, Infrared Rays, Microwave Rays और Radio Waves मुख्य
होते हैं . Electromagnetic Waves (usually Radio Waves) का इस्तमाल wireless
communication में होता है signals को carry करने के कलए.

14
Radio Waves
Radio waves एक प्रकार का form है electromagnetic transmission का कजसका इस्तमाल
wireless communication में होता है . Radio waves signals को आसानी से generate ककया जा
सकता है , ये प्राय तोर से 3 KHz से 300 GHz के range में होता है ।

इनका इस्तमाल wireless communication में इसकलए होता है क्यूींकक इनकी एक ख़ास कविे षता
यह है की ये आसानी से objects में penetrate हो सकते हैं और साथ में ये long distances भी
travel कर सकते हैं .

Radio communication कुछ parameters पर कनभमर करती है जो की हैं wavelength,


transmitter power, receiver quality, type, और antenna की height.

Micro Waves
Microwave का wavelength one meter से one millimetre के भीतर आता है । इसमें
frequency varies करती है 300MHz से 300GHz के भीतर. इन्हें मुख्य रूप से long distance
communications के कलए इस्तमाल ककया जाता है और ये बहुत ही कम expensive होता है .

Infrared Waves
Infrared radiations उन electromagnetic radiations को कहा जाता है कजसमें longer
wavelengths होती है visible light की तुलना में. इनका इस्तमाल मुख्य रूप से short-range
communications के कलए ककया जाता है . ये signals solid objects के through pass नहीीं कर
सकता है ।

उदहारण के कलए Television remote control, mobile data sharing, CCTV तथा कमसाइल
गाइडें स कसस्टम आकद में ककया जाता है .

Wired Network Wireless Network


Faster transmission speed Slow transmission speed
Propagation delay is Low Propagation delay is high
More Secure & hence Reliable Less Secure & hence less Reliable

Devices must be hard-wired Installation is Quick


Less Expensive More Expensive
Installation & maintenance Installation & maintenance cost Low
cost High
Hub, Switch, etc. devices are used Wireless routers, access points, etc. are
used.

15
The process flow of an IoT application.
Internet of Things ,d ,slh Technology gS] ftldk purpose lHkh devices dks
internet ls tksM+uk gS] vkSj ,d ek/;e ds #i esa internet dk mi;ksx djrs gq, mUgsa
,d&nwljs ds lkFk laokn djus esa help djuk gSA

lcls igys Sensor or device vklikl ds okrkoj.k ls data collect djrs gSaA data
collect gksus ds ckn bl data dks fdlh Hkh communication medium ds through
IoT platform ds cloud infrastructure ij send fd;k tkrk gSA cloud ij data
igqapus ds ckn bls csgrj decision ysus ds fy, Big data analytics engine dk mi;ksx
djds lqjf{kr #i ls Store, analyze and manage fd;k tkrk gSA last esa bls Email,
Display, Information or alert ds ek/;e ls bls end-user rd Hkst fn;k tkrk gSA

Chapter 2 exercise
1. ,d system tks feedback dk mi;ksx fd, fcuk process dks control djus ds fy, ,d device dk mi;ksx djrh gS\
a. Open-Loop Control System
b. Closed-Loop Feedback Control System
c. Regulator
d. All of the above.

2. ,d system tks output ds measurement dk mi;ksx djrk gS vkSj bls okafNr output ds lkFk compare djrk gS\
a. Open-Loop Control System
b. Closed-Loop Feedback Control System
c. Both (a) and (b)
d. None of these.

3. ;g ,d control system gS ftlesa dsoy ,d input vkSj ,d output gS\


a. SISO
b. MIMO

16
c. Both (a) and (b)
d. None of these.

4. fuEufyf[kr esa ls dkSu ,d guided medium ugh gS\


a. Twisted Pair Cable
b. Fiber Optic Cable
c. Coaxial Cable
d. Atmosphere

5. Optical Fiber ds Internal core structure esa ___ gS\


a. Glass
b. Non-Metallic
c. Copper
d. Liquid

6. OSI Layer tks lwpukvksa ds logical units esa signals dks O;ofLFkr djrh gS ftls frame dgk tkrk gS ___\
a. Transport
b. Physical
c. Data-Link
d. Application

7. Internet protocol vkerkSj ij fdl OSI Layer ls esy [kkrk gS\


a. Network Layer
b. Transport Layer
c. Data-Link Layer
d. Session Layer

8. Transmission media dks vkerkSj ij bl izdkj classified fd;k tkrk gS\


a. Fixed Or Unfixed
b. Guided Or Unguided
c. fu/kkZfjr ;k vfuf’pr djuk
d. None of these.

9. OSI Model dh dkSu lh layer data compression djrh gS\


a. Network
b. Data-Link
c. Physical
d. Presentation

10. End-to-end connection ___ Protocol }kjk LFkkfir fd;k x;k gS\
a. IP
b. UDP
c. TCP
d. All of the above.

11. Physical layer ls bits dks frame esa ifjofrZr fd;k tkrk gS ___ \
a. Data-Link Layer
b. Network Layer
c. Transport Layer
d. None of these.

17
12. Transport layer dk eq[; dk;Z gS ___ \
a. Node-to-node distribution
b. Process-to-process delivery
c. Routing
d. None of these.

13. Network layer protocol dkSu lk protocol gS\


a. IP
b. Telnet
c. FTP
d. None of these.

14. Closed-loop control system dk vFkZ gS fd blds system dh output bl ij fuHkZj djrh gS ___\
a. Input
b. Processing
c. Feedback
d. None of these.

15. The full form of SSL and TLS is ___?


a. Secure Socket Layout and Transport Layer Session.
b. Session Socket Layer and Transport Layer Session.
c. Secure Socket Layer and Transport Layer Session.
d. Secure Socket Layer and Transport Layer Security.

16. buesa ls dkSu LPWAN rduhd ugh gS\


a. LoRa
b. WiFi
c. SigFox
d. None of these.

17. OSI Model esa fdl layer dks port layer dgk tkrk gS\
a. Application
b. Presentation
c. Transport
d. Session

18. MQTT is ___?


a. Based on publish-subscribe architecture.
b. Based on client-server architecture.
c. Both (a) and (b)
d. None of these.

19. fuEufyf[kr esa ls dkSu lh Layer IOT esa end-to-end communication provide djrh gS\
a. Physical Layer
b. Data-Link Layer
c. Session Layer
d. None of these.

20. Secure MQTT dk ekud (standard) port number gS\


a. 8888 b. 8883 c. 8000 d. 1883

18
It takes a lot of hard work to make notes, so if you can pay some fee 100, 200
rupees which you think is reasonable, if you are able, Thank you...

नोट् स बनाने में बहुत मेहनत लगी है , इसकलए यकद आप कुछ िुि 100, 200 रूपए जो
आपको उकचत लगता है pay कर सकते है , अगर आप सक्षम है तो, िन्यवाद ।

19
UPCISS
O-Level (M4-R5)
Internet of Things and its
Applications

Chapter-3
Sensors, Actuators and
Microcontrollers
Video Tutorial
O-Level M4-R5 Full Video
Playlist Available on
YouTube Channel UPCISS

Free Online Computer Classes on


YouTube Channel UPCISS
www.youtube.com/upciss
For free PDF Notes
Our Website: www.upcissyoutube.com

Copyright © 2022 UPCISS


Contents
Chapter 3- Sensors, Actuators and Microcontrollers ......................... 2
Sensors ............................................................................................... 2
Types of Sensors: ................................................................................ 2
Actuators ............................................................................................ 6
Types of Actuators: ............................................................................. 7
Microcontrollers ................................................................................. 9
Features of Microcontrollers .............................................................. 9
Different types of microcontroller.................................................... 10
Application of Microcontroller ......................................................... 11
Elements of Microcontroller............................................................. 11
Chapter 3 exercise ............................................................................ 12

1
Chapter 3- Sensors, Actuators and
Microcontrollers
Sensors
सेंसर (Sensor) शब्द का Hindi Meaning है कक ककसी भी Data को Sense करना। यानी महसूस
या पता करना। सेंसर एक ऐसा उपकरण है जो प्रकृकत में भौकतक वातावरण से इनपुट (जै से- गकत,
दबाव, तापमान, प्रकाश, गमी, नमी, इत्याकद) का पता करता है और उसका आउटपुट के रूप मे
जवाब दे ता है । आमतौर पर आउटपुट कसग्नल डे टा Human-Readable Display के रूप में
या Electrical Signal में सेंसर पर पररवकति त होता है । जो इले क्ट्रिक कडवाइस कडस्प्ले पर मनुष्य द्वारा
दे खा व पढ़ा जा सकता हैं । सेंसर का इस्तेमाल करके पयाि वरण से ककसी भी डे टा की जानकारी
एकत्र की जाती है और Internet of Things के कलए इस्तेमाल ककया जाता हैं ।

Types of Sensors:
Temperature Sensor कवकभन्न प्रकार वस्तुओं का तापमान या वातावरण मे हुए तापमान मे बदलाव
को मापने का कायि करता है । इसका उपयोग अकिकतर किककत्सा, मोटर वाहन, एयरोस्पेस,
कंप्यूटर, रे किजरे टर, एयर कंडीशकनंग कसस्टम और कृकि क्षेत्रों आकद में ककया जाता है । अभी इस
समय कोकवड-19 की महामारी मे Electronic Thermometer का इस्तेमाल ज़्यादातर शरीर का
तापमान िेक करने के कलए ककया जा रहा हैं । उदाहरण- Thermocouple, Thermometer,
Resistance Temperature Detector, Semiconductor Temperature Sensors आकद कडवाइस
हैं ।

Proximity Sensor

2
Proximity Sensor पास की वस्तुओं को कबना छु ए बड़ी आसानी से पता लगा ले ता है । यह सें सर
स्माटि फोन, टै बले ट कंप्यूटर, मशीनों, रोबोट कसस्टम और इले रिॉकनक उपकरणों इत्याकद में
अकिकतर उपयोग ककया जाता है । यह कई प्रकार की हो सकती है जै से-
 Capacitive Proximity Sensors
 Inductive Proximity Sensors
 Magnetic Proximity Sensors

Infrared Sensor

Infrared Sensor को IR Blaster या Remote Sensor भी कहते है । Infrared Sensor ककसी भी


वस्तु की गमी को मापता है , इसके साथ ही गकत का पता भी लगा सकता है । IR सेंसर Infrared
Light का उत्सजि न करते हैं । IR Sensors की मदद से स्माटि फोन को ररमोट कंटि ोल की तरह
इस्तेमाल कर सकते है । उदाहरण- टीवी ररमोट, सेट टॉप बॉक्स, डीवीडी लेयर, कार ऑकडयो
लेयर, AC ररमोट या ककसी भी ररमोट से िलने वाले इले क्ट्रिक कडवाइस में Infrared Sensors का
इस्तेमाल ककया जाता हैं ।

Light Sensor

Light sensor एक फोटोइले क्ट्रिक (Photoelectric) कडवाइस है । यह Light Energy को Electrical


Signal मे बदलता हैं । इसकलए इसे Photo Sensor भी कहा जाता है । Light Sensors का इस्तेमाल
कवस्ताररूप से सोलर कसस्टम, ऑटोमोबाइल, कृकि क्षेत्र, मोबाइल फोन, कंप्यूटर, टै बले ट और
सेक्युररटी ऍक्ट्लकेशन इत्याकद में ककया जाता हैं । ये तीन प्रकार की होती है ।
 Photodiode
 Phototransistor
 Photo resistor

3
Accelerometer Sensor

Accelerometer Sensor ऐसा उपकरण है जो ककसी कवशे ि कडवाइस या वाहन के गकत त्वरण या
वेग को मापता हैं । यह सेंसर बहुत से ऍक्ट्लकेशन के कलए प्रयोग ककया जाता है । जै से- हाथ के इशारे
से रोबोट कनयंकत्रत करना, कवमान और कमसाइलों के कलए नेकवगेशन सुकविा, वाहन त्वरण, और
टरबाइन, रोलर, पंखे, कंप्रेसर, पंप जै से और दू सरे रोटे कटं ग इले रिॉकनक कडवाइस।

Pressure Sensor

Pressure Sensor को Pressure Transducer/Transmitter या Piezometer के नाम से भी जानते


हैं । Pressure Sensor हवा, गैस, कलक्ट्िड और पानी के दबाव का पता लगाकर Controller को
Electrical Signal प्रदान करता है । Pressure sensors कई सारे कसस्टम में प्रयोग ककया जाता है
जै से- Pneumatic, Hydraulic, Vacuum Systems, इत्याकद।

Ultrasonic Sensor

Ultrasonic Sensor का उपयोग करके Ultrasonic Signals को Transfer करने और Receive


करने के बीि की दू री का पता करते हैं । इनके तीन मुख्य भाग होते
है , ट् रांसमीटर, ररसीवर और ट् रांस ररसीवर। ये सेंसर िीिेंसी में ध्वकन तरं गों का उत्सजि न करते
हैं , जो मनुष्य द्वारा नहीं सुना जा सकता है । इनका उपयोग द्रव स्तर को मापने, सेल्फ डिाइकवंग,
हाइट कनयंत्रण, रोबोट सेंकसंग आकद में ककया जाता है । ये सुरक्षा संबंिी उपकरणों में भी इस्तेमाल
ककया जा सकता हैं ।

4
Touch Sensor

Touch Sensor को Tactile Sensor भी कहते है । इसका उपयोग शारीररक स्पशि का पता करने
और इं डक्ट्स्टियल ऍक्ट्लकेशन में ककया जाता है । जै से लाइट क्ट्िि ऑन/ऑफ, एयर कंडीशनर (AC)
द्वारा ररमोट कंटि ोल, दरवाजे खोलना/बंद करना, रोबोकटक्स, लै पटॉप, स्माटि फोन इत्याकद।

उदाहरण तौर पर- ऑक्सीमीटर (Oximeter) मानव शरीर में ऑक्सीजन के स्तर का पता लगाने
के कलए Touch Sensors का सबसे अच्छा उदाहरण है । इस COVID-19 महामारी में, Pulse
Oximeter का अकिक मां ग हैं । अपने घर पर भी इसका इस्तेमाल करना काफी आसान हैं ।

Smoke or Gas Sensor

गैस या िुंए का पता करने के कलए कजस उपकरण का इस्तेमाल ककया जाता है , उसे स्मोक सेंसर
(Smoke Sensor) कहा जाता है । ये सेंसर कवकभन्न प्रकार के ज़हरीली गैसों या कवस्फोटक गैसें हवा
मे िुएं का पता करती है । Smoke Sensor का प्रयोग इमारतों, जहाजों, लां ट, उद्योगों, हवाई जहाज
आकद में ककया जाता है । Smoke या Gas Sensor को तीन भागों में बां टा गया हैं ।
 Optical Type Smoke Sensors
 Ionization Type Smoke Sensors
 Laser Type Smoke Sensors

Humidity Sensor

Humidity Sensor को एक हाइग्रोमीटर (Hygrometer) के नाम से भी जाना जाता हैं । ये सेंसर


वातावरण में वायु तापमान और कमट्टी में नमी का पता लगाने के कलए बहुत ही सहायकपूणि है ।
ज्यादातर इसका इस्तेमाल एयर कंडीशनर (AC) में ककया जाता हैं । WS1 Pro वायरले स Humidity
Sensor का एक उदाहरण हैं ।

5
Flow Sensor

Flow Sensor ककसी भी तरल पदाथों के प्रवाह और स्तर की जानकारी का पता लगाता है । ये एक
मैगनेकटक कडवाइस होता है , जब पानी का स्तर बढ़ता है तो मैगनेट क्ट्िि को संकेत जाता है ताकक
इसके कंटि ोलर अलामि द्वारा कंटि ोल ककया जा सके। इस सेंसर का इस्तेमाल औद्योकगक क्षेत्र, कबजली
पैदा करने वाले उपकरणों, कबजली लां ट इत्यादी में ककया जाता है ।

Tilt Sensor

Tilt Sensor वस्तुओं के कवकभन्न अक्षों में सतह के झुकाव या घुमाव और कोणीय गकत का पता करता
हैं । इनका उपयोग अकिकतर वाहनों, नावों और एयरक्राफ्ट आकद में सुरक्षा अलामि के रूप में ककया
जाता है ताकक दु घिटना से बिा जा सके।

Actuators
An actuator is a machine component or system that moves or controls the mechanism
or the system. Sensors in the device sense the environment, then control signals are
generated for the actuators according to the actions needed to perform.
A servo motor is an example of an actuator. They are linear or rotatory actuators, can
move to a given specified angular or linear position. We can use servo motors for IoT
applications and make the motor rotate to 90 degrees, 180 degrees, etc., as per our
need.

6
एक्चुएटर एक मशीन घटक या प्रणाली है जो तं त्र या कसस्टम को गकत या कनयंकत्रत करता है । कडवाइस
में सेंसर पयाि वरण को समझते हैं , कफर एक्ट्यूएटसि के कलए आवश्यक कक्रयाओं के अनुसार कनयंत्रण
संकेत उत्पन्न होते हैं ।

एक सवो मोटर एक एक्चुएटर का एक उदाहरण है । वे रै क्ट्खक या घूणिन एक्ट्यूएटर हैं , ककसी कदए
गए कनकदि ष्ट कोणीय या रै क्ट्खक क्ट्स्प्थकत में जा सकते हैं । हम IoT अनुप्रयोगों के कलए सवो मोटसि का
उपयोग कर सकते हैं और अपनी आवश्यकता के अनुसार मोटर को 90 कडग्री, 180 कडग्री आकद
पर घुमा सकते हैं ।

Types of Actuators:
Hydraulic Actuators –
A hydraulic actuator uses hydraulic power to perform a mechanical operation. They
are actuated by a cylinder or fluid motor. The mechanical motion is converted to
rotary, linear, or oscillatory motion, according to the need of the IoT device. Ex-
construction equipment uses hydraulic actuators because hydraulic actuators can
generate a large amount of force.
एक हाइडिोकलक एक्ट्यूएटर एक यां कत्रक ऑपरे शन करने के कलए हाइडिोकलक पावर का उपयोग
करता है । वे एक कसलें डर या द्रव मोटर द्वारा संिाकलत होते हैं । IoT कडवाइस की आवश्यकता के
अनुसार यां कत्रक गकत को रोटरी, लीकनयर या ऑकसले टरी मोशन में बदल कदया जाता है । पूवि-कनमाि ण
उपकरण हाइडिोकलक एक्ट्यूएटसि का उपयोग करते हैं क्योंकक हाइडिोकलक एक्ट्यूएटर बड़ी मात्रा
में बल उत्पन्न कर सकते हैं ।

Pneumatic Actuators –
A pneumatic actuator uses energy formed by vacuum or compressed air at high
pressure to convert into either linear or rotary motion. Example- Used in robotics, use
sensors that work like human fingers by using compressed air.

एक न्यू मेकटक एक्ट्यूएटर उच्च दबाव पर वैक्यूम या संपीकड़त हवा द्वारा बनाई गई ऊजाि का उपयोग
रै क्ट्खक या रोटरी गकत में पररवकति त करने के कलए करता है । उदाहरण- रोबोकटक्स में प्रयुक्त, ऐसे
सेंसर का उपयोग करें जो संपीकड़त हवा का उपयोग करके मानव उं गकलयों की तरह काम करते
हैं ।

7
Electrical Actuators –
An electric actuator uses electrical energy, is usually actuated by a motor that converts
electrical energy into mechanical torque. An example of an electric actuator is a
solenoid based electric bell.

एक इले क्ट्रिक एक्ट्यूएटर कवद् युत ऊजाि का उपयोग करता है , आमतौर पर एक मोटर द्वारा
संिाकलत होता है जो कवद् युत ऊजाि को यां कत्रक टोक़ में पररवकति त करता है । इले क्ट्रिक एक्ट्यूएटर
का एक उदाहरण सोलनॉइड आिाररत इले क्ट्रिक बेल है ।

Mechanical Actuators –
A mechanical actuator executes movement by converting rotary motion into linear
motion. It involves pulleys, chains, gears and other devices to operate.

एक यां कत्रक एक्चुएटर रोटरी गकत को रै क्ट्खक गकत में पररवकति त करके गकत को कक्रयाक्ट्ित करता
है । इसमें संिाकलत करने के कलए पुली, िेन, कगयर और अन्य उपकरण शाकमल हैं ।

8
Microcontrollers
Microcontroller एक छोटा और बहुत ही सस्ता microcomputer होता है कजसको embedded
system के कवशे ि कायों को perform करने के कलए design ककया जाता है . जै से कक – microwave
की सूिना को कडस्प्ले करने, एवं remote signal को receive करने के कलए आकद.

दू सरे शब्दों में कहें तो, “माइक्रोकंटि ोलर एक integrated circuit (IC) है कजसका प्रयोग electronic
system के अन्य भागों को control करने के कलए ककया जाता है .” एक सामान्य माइक्रो-कंटि ोलर में
processor, serial ports, memory (RAM, ROM, EPROM) तथा peripherals होते हैं .

माइक्रो-कंटि ोलर को embedded controller भी कहते है . इनका प्रयोग गाकड़यों में, medical
equipments (उपकरणों) में, robots, vending मशीन, एवं घरे लु उपकरणों आकद में ककया जाता
है .

Features of Microcontrollers
1. इसकी cost तथा size कम होता है .

2. यह कनम्न clock rate frequency पर operate होता है . सामन्यतया यह 4, 8, 16, 32 bit के


होते है , और यह बहुत ही कम power को consume करता है .

3. आमतौर पर यह अन्य उपकरणों में embed (जु ड़ा) रहता है और उन उपकरणों के कायो
को control करता है .

4. Microcontroller के द्वारा प्रयोग ककया जाने वाला प्रोग्राम ROM में स्टोर रहता है .

5. यह उन पररक्ट्स्प्थकतयों में प्रयोग होता है जहां सीकमत कंप्यूकटं ग कायों की आवश्यकता होती
है ।
Microcontroller Microprocessor

इसका प्रयोग एक application में एक single task माइक्रोप्रोसेसर का प्रयोग बड़ी


को execute करने के कलए ककया जाता है . applications में ककया जाता है .

यह embedded system के कदल (heart) के यह computer system के कदल की तरह


समान होता है . होता है .

Microcontroller जो है वह internal memory यह केवल एक processor होता है . और


तथा I/O components के साथ-साथ external इसमें memory और I/O बाहरी रूप से
processor को भी स्टोर ककये रहता है . (externally) जु ड़े रहते हैं .

िूूँकक इसमें memory और I/O आं तररक रूप से िूूँकक इसमें memory और I/O बाहरी रूप
(internally) जुड़े रहते है . इसकलए इसका size से (externally) जु ड़े रहते है . इसकलए
छोटा होता है . इसका size बड़ा होता है .

9
पूरे कसस्टम का मूल्य कम होता है . पूरे system का cost (मूल्य) बढ़ जाता है .

इसमें power (कबजली) कम खिि होती है . इसमें कबजली ज्यादा खिि होती है .

अकिकतर microcontroller’s के पास power ज्यादतर microprocessors के पास


saving mode होता है . power saving mode नहीं होता है .

इसका मुख्यतः प्रयोग washing machines, MP3 इसका मुख्यतः प्रयोग personal
player’s आकद में ककया जाता है . computers में ककया जाता है .

Different types of microcontroller


Microcontroller’s को हम memory, bits तथा instruction sets के आिार पर कवकभन्न
categories में कवभाकजत कर सकते हैं :-

Bit
कबट के आिार पर हम माइक्रो-कंटि ोलर को तीन categories में कवभाकजत कर सकते हैं :-

1. 8 bit microcontroller: - इस प्रकार के माइक्रो-कंटि ोलर का प्रयोग arithmetic तथा


logical ऑपरे शन को execute करने में ककया जाता है जै से:- जोड़ना, घटाना, गुणा करना,
भाग करना आकद. उदाहरण के कलए:- intel 8031 और 8051, 8 कबट माइक्रोकंटि ोलर है .

2. 16 bit: - इस प्रकार के माइक्रोकंटि ोलर का प्रयोग भी arithmetic और logical ऑपरे शनों


में ककया जाता है जहाूँ उच्च accuracy और performance की जरूरत होती है . उदाहरण
के कलए:- intel 8096.

3. 32 bit: - इस प्रकार के माइक्रो-कंटि ोलर का प्रयोग अपने-आप control होने वाले


appliances में ककया जाता है जै से:- automatic operational machine, मेकडकल
उपकरण आकद में.

Memory के आिार पर इसे दो भागों में divide ककया जा सकता है:-


External memory microcontroller: - इस type के माइक्रोकंटि ोलर को इस तरीके से कडजाईन
ककया गया होता है कक chip में program memory नहीं होती है . Example के कलए:- intel 8031.

Embedded memory microcontroller: - इस type के माइक्रो-कंटि ोलर को इस तरीके से


design ककया जाता है कक chip में सभी programs और data memory होती है . Example के
कलए:- 8051.

Instruction Set Instruction set के आिार पर इसे दो parts में divide कर सकते हैं:-
CISC: - CISC का पूरा नाम complex instruction set computer है . यह यूजर को बहुत सारीं सरल
instructions के स्प्थान पर केवल एक instruction को insert करने की अनुमकत दे ता है .

10
RISC: - RISC का पूरा नाम Reduced Instruction Set Computer है . यह प्रत्येक instruction से
clock cycle को छोटा करके operational time को कम कर दे ता है .

Application of Microcontroller
1. Light sensing तथा control devices जै से:- LED में इनका प्रयोग ककया जाता है .

2. Temperature को sense करने वाली devices जै से:- microwave oven, और chimneys


आकद.

3. आग को detect करने वाली कडवाइस तथा safety devices जै से:- fire alarm में.

4. मापने वाली कडवाइस जै से:- volt meter में.


5. Current meter.
6. Industrial instrumentation devices.
7. Hand-held metering systems.

Elements of Microcontroller
CPU (central processing unit) – CPU माइक्रोकंटि ोलर का brain (कदमाग) होता है . यह
instruction को fetch करता है , उसे कडकोड करता है और अंत में उसे execute करता है . अथाि त
यह arithmetic operations को परफॉमि करता है , data flow को मैनेज करता है , control signals
को जनरे ट करता है .

Memory – मैमोरी का प्रयोग data तथा program को स्टोर करने के कलए ककया जाता है . एक
माइक्रोकंटि ोलर में आमतौर पर RAM और ROM (EPROM, EEPROM आकद) या flash memory
की एक कनकित मात्रा होती है .

Parallel input/output ports – parallel input/output ports का प्रयोग बहुत सारीं devices
जै से:- LCD, LED, printer’s आकद को drive करने के कलए ककया जाता है .

Serial Ports – serial ports जो है वह माइक्रोकंटि ोलर तथा अन्य peripheral devices के मध्य
इं टरफ़ेस प्रदान करता है .

Timers / counters – एक microcontroller में एक या एक से ज्यादा timer तथा counter हो


सकते है . Timers तथा counters जो है वह counting और timing के सारें कायों को करने की
सुकविा प्रदान करते हैं .

Analog to Digital converter (ADC) – यह analog कसग्नल को digital कसग्नल में बदल दे ता है .

Digital to Analog converter (DAC) – यह कडकजटल कसग्नल को एनालॉग कसग्नल में बदल दे ता है .

11
Chapter 3 exercise
1. Sensor gks ldrs gSa ___?
a. Temperature
b. Loud ¼ykmM½
c. Motion
d. All of the above.

2. Actuators gks ldrs gSa ___?


a. Display
b. Motors
c. Sound
d. All of the above.

3. Sensor ds mnkgj.k gSa ___?


a. Gas Sensor
b. Water Quality Sensor
c. Moisture Sensor
d. All of the above.

4. dHkh&dHkh laf{kIr (short) :i esa ,d microcontroller ___?


a. uc
b. uC
c. MCU
d. All of the above.

5. ?kVd tks ,d fof’k”V microcontroller IC ij ekStwn gS ___?


a. CPU
b. Memory
c. I/O and Timer
d. All of the above.

6. Tagging Things ___?


a. RFID and NFC
b. Digital Watermarking
c. QR Code
d. All of the above.

7. Actuators esa ‘kkfey gSa ___?


a. Motors, Gear
b. Pumps, Piston
c. okYo] vkSj fLop
d. All of the above.

8. blds }kjk Addition, Subtraction, Division, Multiplication vkSj Logical Operation fd;k tkrk gS ___?
a. Resistor
b. Control System
c. ALU
d. None of these.

12
9. Microprocessor dke djrk gS tks vadksa dk mi;ksx djrk gS ___\
a. 1
b. 0
c. 0 and 1
d. All of the above.

10. RISC ds Characteristic ___\


a. Pipelining
b. Hard-Wired
c. Instructions ,d Clock-Cycle esa Execute gksrs gSaA
d. All of the above.

11. Microprocessor dh fo’ks”krk ___?


a. Instruction Set
b. Clock Speed
c. Memory
d. All of the above.

12. ___ Sensor digital output mRiUu djrs gSa ftUgsa digital controller ds lkFk lh/ks gLr{ksi fd;k tk ldrk gS\
a. Digital
b. Analog
c. Both (a) and (b)
d. None of these.

13. Microcontroller ___?


a. Savings
b. Saves Electricity Consumption
c. Makes the Circuit Compact
d. All of the above.

14. 8051 Microcontroller dk application area ___?


a. Medical Equipment
b. Aeronautical and Space
c. Defense System
d. All of the above.

15. ___ Sensor source }kjk mRikfnr heat energy dks measure djrs gSa\
a. Temperature
b. Proximity
c. Pressure Sensor
d. Humidity Sensor

16. fuEufyf[kr esa ls dkSu lk touch sensor cell phone esa mi;ksx fd;k tkrk gS\
a. Capacitive Touch Sensor
b. Human Sensor
c. Resistive Touch Sensor
d. Flow Sensor

17. DC Motor is a ___?


a. Actuator tks electrical energy dks mechanical energy esa convert djrk gSA
b. Microprocessor

13
c. Device
d. None of these.

18. LDR Sensor dks ___ ds :i esa laf{kIr fd;k x;k gS\
a. Light Dependent Resistor
b. Light Detecting Resistor
c. Light Duplicated Resistor
d. None of these.

19. fuEufyf[kr esa ls dkSu lk IOT esa actuator ugh gS\


a. An LED
b. A Fan
c. Stepper Motor
d. Arduino

20. fuEUfyf[kr esa ls dkSu lk dFku IOT Components ds ckjs esa xyr gS\
a. A keyboard is a digital sensor.
b. A push button is a digital sensor.
c. A light sensor (photo resistor) is an analog sensor.
d. A microphone is a digital sensor.

14
It takes a lot of hard work to make notes, so if you can pay some fee 100, 200
rupees which you think is reasonable, if you are able, Thank you...

नोट् स बनाने में बहुत मेहनत लगी है , इसकलए यकद आप कुछ शुल्क 100, 200 रूपए जो
आपको उकित लगता है pay कर सकते है , अगर आप सक्षम है तो, िन्यवाद ।

15
UPCISS
O-Level (M4-R5)
Internet of Things and its
Applications

Chapter-4
Building IoT applications

Video Tutorial
O-Level M4-R5 Full Video
Playlist Available on
YouTube Channel UPCISS

Free Online Computer Classes on


YouTube Channel UPCISS
www.youtube.com/upciss
For free PDF Notes
Our Website: www.upcissyoutube.com

Copyright © 2022 UPCISS


Chapter 4- Building IoT applications ----------------------------------------------------------------------------------------------- 2
Introduction to Arduino Board and IDE---------------------------------------------------------------------------------------- 2
Embedded ‘C’ Language ----------------------------------------------------------------------------------------------------------- 7
C Introduction ------------------------------------------------------------------------------------------------------------------------- 8
C Syntax ---------------------------------------------------------------------------------------------------------------------------------- 9
C reserved keywords --------------------------------------------------------------------------------------------------------------11
C Variables -----------------------------------------------------------------------------------------------------------------------------11
Data Types --------------------------------------------------------------------------------------------------------------------------15
Basic Format Specifiers ---------------------------------------------------------------------------------------------------------16
Constants ---------------------------------------------------------------------------------------------------------------------------16
Operators ---------------------------------------------------------------------------------------------------------------------------18
Conditions and If Statements ------------------------------------------------------------------------------------------------21
While Loop -------------------------------------------------------------------------------------------------------------------------27
The Do/While Loop --------------------------------------------------------------------------------------------------------------27
For Loop -----------------------------------------------------------------------------------------------------------------------------28
Strings --------------------------------------------------------------------------------------------------------------------------------30
Creating Pointers -----------------------------------------------------------------------------------------------------------------32
Arrays ---------------------------------------------------------------------------------------------------------------------------------34
Access the Elements of an Array --------------------------------------------------------------------------------------------34
Change an Array Element -----------------------------------------------------------------------------------------------------35
Loop through an Array ---------------------------------------------------------------------------------------------------------35
Set Array Size ----------------------------------------------------------------------------------------------------------------------35
C Functions ----------------------------------------------------------------------------------------------------------------------------36
Predefined Functions -----------------------------------------------------------------------------------------------------------36
Create a Function ----------------------------------------------------------------------------------------------------------------36
Parameters and Arguments --------------------------------------------------------------------------------------------------38
Multiple Parameters -------------------------------------------------------------------------------------------------------------39
Function Declaration and Definition---------------------------------------------------------------------------------------40
Function prototype ---------------------------------------------------------------------------------------------------------------42
Recursion ----------------------------------------------------------------------------------------------------------------------------43
Chapter 4 exercise -----------------------------------------------------------------------------------------------------------------44

1
Chapter 4- Building IoT applications
Introduction to Arduino Board and IDE
ARDUINO एक open source हार्ड वेयर और सॉफ्टवेयर कम्पनी और कम्युननटी है , जो र्े वलपमेंट
बोर्ड बनाती है . र्े वलपमेंट बोर्ड यानन एक embedded system नजसमे microcontroller या
microprocessor होता है . साथ ही साथ उसमे पॉवर सप्लाई रे गुलेटसड, मेमोरी, communication
ports, etc. होता है .

Microcontroller ATmega328P
Operating Voltage 5V
Input Voltage 7-12V
(recommended)
Input Voltage (limit) 6-20V
Digital I/O Pins 14 (of which 6 provide PWM output)
PWM Digital I/O Pins 6
Analog Input Pins 6
DC Current per I/O Pin 20 Ma
DC Current for 3.3V Pin 50 Ma

2
Flash Memory 32 KB (ATmega328P) of which 0.5 KB used by boot
loader
SRAM 2 KB (ATmega328P)
EEPROM 1 KB (ATmega328P)
Clock Speed 16 MHz
LED_BUILTIN 13

3
Different Types of Arduino Boards
 Arduino Uno (R3)
 Arduino Nano
 Arduino Micro
 Arduino Due
 LilyPad Arduino Board
 Arduino Bluetooth
 Arduino Diecimila
 RedBoard Arduino Board
 Arduino Mega (R3) Board
 Arduino Leonardo Board
 Arduino Robot
 Arduino Esplora
 Arduino Pro Mic
 Arduino Ethernet
 Arduino Zero
 Fastest Arduino Board
Introduction to Arduino IDE
The Arduino IDE is an open-source software, which is used to write and upload code
to the Arduino boards. The IDE application is suitable for different operating systems
such as Windows, Mac OS X, and Linux. It supports the programming languages C and
C++. Here, IDE stands for Integrated Development Environment.

4
Simple Program LED Blinking

5
Simple Traffic Light Control Program
Code:
int red = 2 ;
int yellow = 3 ;
int green = 4 ;
void setup(){
pinMode(red, OUTPUT);
pinMode(yellow, OUTPUT);
pinMode(green, OUTPUT);
}
void loop(){
digitalWrite(red, 1);
delay(4000);
digitalWrite(yellow, 1);
delay(1000);
digitalWrite(red, 0);
digitalWrite(yellow, 0);
digitalWrite(green, 1);
delay(5000);
digitalWrite(green, 0);
}

6
Embedded ‘C’ Language
Embedded C is most popular programming language in software field for developing
electronic gadgets. Each processor used in electronic system is associated with
embedded software. Embedded C programming plays a key role in performing specific
function by the processor.
The language in which Arduino is programmed is a subset of C and it includes only
those features of standard C that are supported by the Arduino IDE.

Differences between C and Embedded C:


Parameters C Embedded C
 C is a general purpose  Embedded C is simply an
programming language, extension C language and it
which can be used to is used to develop micro-
design any type of controller based
GENERAL
desktop based applications.
applications.  It is nothing but an
 It is a type of high level extension of C.
language.
 C language is hardware  Embedded C is fully
independent language. hardware dependent
DEPENDENCY  C compilers are OS language.
dependent.  Embedded C are OS
independent.
 For C language, the  For Embedded C, a specific
standard compilers can be compilers that are able to
used to compile and generate particular
execute the program. hardware/micro-controller
 Popular Compiler to based output is used.
COMPILER execute a C language  Popular Compiler to execute
program are: a Embedded C language
 GCC (GNU Compiler program are:
collection)  Keil compiler
 Borland turbo C,  BiPOM ELECTRONIC
 Intel C++  Green Hill software
 C language has a free-  Formatting depends upon
format of program the type of microprocessor
USABILITY
coding. that is used.
AND
 It is specifically used for  It is used for limited
APPLICATION
desktop application. resources like RAM and
 Optimization is normal. ROM.

7
 It is very easy to read and  High level of optimization.
modify the C language.  It is not easy to read and
 Bug fixing are very easy in modify the Embedded C
a C language program. language.
 It supports other various  Bug fixing is complicated in a
programming languages Embedded C language
during application. program.
 Input can be given to the  It supports only required
program while it is processor of the application,
running. and not the programming
 Applications of C languages.
Program:  Only the pre-defined input
 Logical programs can be given to the running
 System software program.
programs  Applications of Embedded C
Program:
 DVD
 TV
 Digital camera

C Introduction
What is C?
C is a general-purpose programming language created by Dennis Ritchie at the Bell
Laboratories in 1972.

It is a very popular language, despite being old.

C is strongly associated with UNIX, as it was developed to write the UNIX operating
system.

Why Learn C?
 It is one of the most popular programming language in the world
 If you know C, you will have no problem learning other popular programming
languages such as Java, Python, C++, C#, etc, as the syntax is similar
 C is very fast, compared to other programming languages,
like Java and Python
 C is very versatile; it can be used in both applications and technologies

Difference between C and C++


8
 C++ was developed as an extension of C, and both languages have almost
the same syntax
 The main difference between C and C++ is that C++ support classes and
objects, while C does not

Get Started
It is not necessary to have any prior programming experience.

To start using C, you need two things:

 A text editor, like Notepad, to write C code


 A compiler, like GCC, to translate the C code into a language that the
computer will understand

There are many text editors and compilers to choose from. In this tutorial, we will
use an IDE (see below).

C Install IDE
An IDE (Integrated Development Environment) is used to edit AND compile the
code.

Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free,
and they can be used to both edit and debug C code.

We will use Code::Blocks in our tutorial, which we believe is a good place to start.

You can find the latest version of Codeblocks at http://www.codeblocks.org/.


Download the mingw-setup.exe file, which will install the text editor with a
compiler.

C Syntax
Example
#include <stdio.h>

int main() {
printf("Hello World!");
return 0;
}

Example explained
Line 1: #include <stdio.h> is a header file library that lets us work with input and
output functions, such as printf() (used in line 4). Header files add functionality to
C programs.

9
Don't worry if you don't understand how #include <stdio.h> works. Just think of it
as something that (almost) always appears in your program.

Line 2: A blank line. C ignores white space. But we use it to make the code more
readable.

Line 3: Another thing that always appear in a C program, is main(). This is called
a function. Any code inside its curly brackets {} will be executed.

Line 4: printf() is a function used to output/print text to the screen. In our


example it will output "Hello World".

Note that: Every C statement ends with a semicolon ;

Note: The body of int main() could also been written as:
int main(){printf("Hello World!");return 0;}

Remember: The compiler ignores white spaces. However, multiple lines makes the
code more readable.

Line 5: return 0 ends the main() function.

Line 6: Do not forget to add the closing curly bracket } to actually end the main
function.

Comments in C
Comments can be used to explain code, and to make it more readable. It can also
be used to prevent execution when testing alternative code.

Comments can be singled-lined or multi-lined.

Single-line Comments
Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will not be
executed).

This example uses a single-line comment before a line of code:

Example
// This is a comment
printf("Hello World!");

This example uses a single-line comment at the end of a line of code:

Example
printf("Hello World!"); // This is a comment

10
C Multi-line Comments
Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
printf("Hello World!");

C reserved keywords
The table below lists all keywords reserved by the C language. When the current programming
language is C or C++, these keywords cannot be abbreviated, used as variable names, or used as any
other type of identifiers.

auto else long switch


break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _Packed
double

C Variables
Variables are containers for storing data values.

In C, there are different types of variables (defined with different keywords), for
example:

 int - stores integers (whole numbers), without decimals, such as 123 or -


123
 float - stores floating point numbers, with decimals, such as 19.99 or -
19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded
by single quotes

Declaring (Creating) Variables


11
To create a variable, specify the type and assign it a value:

Syntax
type variableName = value;

Where type is one of C types (such as int), and variableName is the name of the
variable (such as x or myName). The equal sign is used to assign a value to the
variable.

So, to create a variable that should store a number, look at the following
example:

Example
Create a variable called myNum of type int and assign the value 15 to it:

int myNum = 15;

You can also declare a variable without assigning the value, and assign the value
later:

Example
int myNum;
myNum = 15;

Note: If you assign a new value to an existing variable, it will overwrite the
previous value:

Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10

Output Variables
You learned from the output chapter that you can output values/print text with
the printf() function:

Example
printf("Hello World!");

In many other programming languages (like Python, Java, and C++), you would
normally use a print function to display the value of a variable. However, this is
not possible in C:

12
Example
int myNum = 15;
printf(myNum); // Nothing happens

To output variables in C, you must get familiar with something called "format
specifiers".

Format Specifiers
Format specifiers are used together with the printf() function to tell the compiler
what type of data the variable is storing. It is basically a placeholder for the
variable value.

A format specifier starts with a percentage sign %, followed by a character.

For example, to output the value of an int variable, you must use the format
specifier %d or %i surrounded by double quotes, inside the printf() function:

Example
int myNum = 15;
printf("%d", myNum); // Outputs 15

To print other types, use %c for char and %f for float:

Example
// Create variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character

// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);

To combine both text and a variable, separate them with a comma inside
the printf() function:

Example
int myNum = 5;
printf("My favorite number is: %d", myNum);

To print different types in a single printf() function, you can use the following:

13
Example
int myNum = 5;
char myLetter = 'D';
printf("My number is %d and my letter is %c", myNum, myLetter);

You will learn more about Data Types in the next chapter.

Add Variables Together


To add a variable to another variable, you can use the + operator:

Example
int x = 5;
int y = 6;
int sum = x + y;
printf("%d", sum);

Declare Multiple Variables


To declare more than one variable of the same type, use a comma-separated list:

Example
int x = 5, y = 6, z = 50;
printf("%d", x + y + z);

You can also assign the same value to multiple variables of the same type:

Example
int x, y, z;
x = y = z = 50;
printf("%d", x + y + z);

C Variable Names
All C variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).

Note: It is recommended to use descriptive names in order to create


understandable and maintainable code:

14
Example
// Good
int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is


int m = 60;

The general rules for naming variables are:

 Names can contain letters, digits and underscores


 Names must begin with a letter or an underscore (_)
 Names are case sensitive (myVar and myvar are different variables)
 Names cannot contain whitespaces or special characters like !, #, %, etc.
 Reserved words (such as int) cannot be used as names

Data Types
As explained in the Variables chapter, a variable in C must be a specified data
type, and you must use a format specifier inside the printf() function to display
it:

Example
// Create variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character

// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);

Basic Data Types


The data type specifies the size and type of information the variable will store.

In this tutorial, we will focus on the most basic ones:

Data Type Size Description

int 2 or 4 bytes Stores whole numbers, without decimals

float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient
for storing 7 decimal digits

double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient
for storing 15 decimal digits

15
char 1 byte Stores a single character/letter/number, or ASCII values

Basic Format Specifiers


There are different format specifiers for each data type. Here are some of them:

Format Specifier Data Type

%d or %i int

%f float

%lf double

%c char

%s Used for strings, which you will learn more about in a later chapter

Constants
When you don't want others (or yourself) to override existing variable values, use
the const keyword (this will declare the variable as "constant", which
means unchangeable and read-only):

Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'

You should always declare the variable as constant when you have values that are
unlikely to change:

Example
const int minutesPerHour = 60;
const float PI = 3.14;

Notes on Constants
When you declare a constant variable, it must be assigned with a value:

Example
Like this:

const int minutesPerHour = 60;

This however, will not work:

16
const int minutesPerHour;
minutesPerHour = 60; // error

Good Practice
Another thing about constant variables, is that it is considered good practice to
declare them with uppercase. It is not required, but useful for code readability and
common for C programmers:

Example
const int BIRTHYEAR = 1980;

User Input
You have already learned that printf() is used to output values in C.

To get user input, you can use the scanf() function:

Example
Output a number entered by the user:

// Create an integer variable that will store the number we get from the user
int myNum;

// Ask the user to type a number


printf("Type a number: \n");

// Get and save the number the user types


scanf("%d", &myNum);

// Output the number the user typed


printf("Your number is: %d", myNum);

The scanf() function takes two arguments: the format specifier of the variable (%d in
the example above) and the reference operator (&myNum), which stores the memory
address of the variable.

Tip: You will learn more about memory addresses and functions in the next
chapter.

User Input Strings


You can also get a string entered by the user:

Example
Output the name of a user:

17
// Create a string
char firstName[30];

// Ask the user to input some text


printf("Enter your first name: \n");

// Get and save the text


scanf("%s", firstName);

// Output the text


printf("Hello %s.", firstName);

Note that you must specify the size of the string/array (we used a very high
number, 30, but atleast then we are certain it will store enough characters for the
first name), and you don't have to specify the reference operator (&) when working
with strings in scanf().

Operators
Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example
int myNum = 100 + 50;

Although the + operator is often used to add together two values, like in the
example above, it can also be used to add together a variable and a value, or a
variable and another variable:

Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)

C divides the operators into the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators

Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.

18
Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x

Assignment Operators
Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:

Example
int x = 10;

The addition assignment operator (+=) adds a value to a variable:

Example
int x = 10;
x += 5;

A list of all assignment operators:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

19
|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Comparison Operators
Comparison operators are used to compare two values.

Note: The return value of a comparison is either true (1) or false (0).

In the following example, we use the greater than operator (>) to find out if 5 is
greater than 3:

Example
int x = 5;
int y = 3;
printf("%d", x > y); // returns 1 (true) because 5 is greater than 3

A list of all comparison operators:

Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Logical Operators
Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is x < 5 || x < 4


true

20
! Logical not Reverse the result, returns false if the !(x < 5 && x < 10)
result is true

Sizeof Operator
The memory size (in bytes) of a data type or a variable can be found with
the sizeof operator:

Example
int myInt;
float myFloat;
double myDouble;
char myChar;

printf("%lu\n", sizeof(myInt));
printf("%lu\n", sizeof(myFloat));
printf("%lu\n", sizeof(myDouble));
printf("%lu\n", sizeof(myChar));

Conditions and If Statements


You learned from the operators comparison chapter, that C supports the usual
logical conditions from mathematics:

 Less than: a < b


 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

C has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is


true
 Use else to specify a block of code to be executed, if the same condition is
false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

The if Statement
Use the if statement to specify a block of C code to be executed if a condition
is true.

21
Syntax
if (condition) {
// block of code to be executed if the condition is true
}

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an
error.

In the example below, we test two values to find out if 20 is greater than 18. If the
condition is true, print some text:

Example
if (20 > 18) {
printf("20 is greater than 18");
}

We can also test variables:

Example
int x = 20;
int y = 18;
if (x > y) {
printf("x is greater than y");
}

Example explained

In the example above we use two variables, x and y, to test whether x is greater
than y (using the > operator). As x is 20, and y is 18, and we know that 20 is
greater than 18, we print to the screen that "x is greater than y".

The else Statement


Use the else statement to specify a block of code to be executed if the condition
is false.

Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

22
Example
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
// Outputs "Good evening."

Example explained

In the example above, time (20) is greater than 18, so the condition is false.
Because of this, we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".

The else if Statement


Use the else if statement to specify a new condition if the first condition is false.

Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2
is true
} else {
// block of code to be executed if the condition1 is false and condition2
is false
}

Example
int time = 22;
if (time < 10) {
printf("Good morning.");
} else if (time < 20) {
printf("Good day.");
} else {
printf("Good evening.");
}
// Outputs "Good evening."

Example explained

In the example above, time (22) is greater than 10, so the first condition is false.
The next condition, in the else if statement, is also false, so we move on to
the else condition since condition1 and condition2 is both false - and print to the
screen "Good evening".

23
However, if the time was 14, our program would print "Good day."

Another Example
This example shows how you can use if..else if to find out if a number is positive or
negative:

Example
int myNum = 10; // Is this a positive or negative number?

if (myNum > 0)
printf("The value is a positive number.");
else if (myNum < 0)
printf("The value is a negative number.");
else
printf("The value is 0.");

Short Hand If...Else (Ternary Operator)


There is also a short-hand if else, which is known as the ternary
operator because it consists of three operands. It can be used to replace multiple
lines of code with a single line. It is often used to replace simple if else statements:

Syntax
variable = (condition) ? expressionTrue : expressionFalse;

Instead of writing:

Example
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}

You can simply write:

Example
int time = 20;
(time < 18) ? printf("Good day.") : printf("Good evening.");

Switch Statement

24
Instead of writing many if..else statements, you can use the switch statement.

The switch statement selects one of many code blocks to be executed:

Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

This is how it works:

 The switch expression is evaluated once


 The value of the expression is compared with the values of each case
 If there is a match, the associated block of code is executed
 The break statement breaks out of the switch block and stops the execution
 The default statement is optional, and specifies some code to run if there is
no case match

The example below uses the weekday number to calculate the weekday name:

Example
int day = 4;

switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:

25
printf("Sunday");
break;
}

// Outputs "Thursday" (day 4)

The break Keyword


When C reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no need
for more testing.

A break can save a lot of execution time because it "ignores" the execution of all
the rest of the code in the switch block.

The default Keyword


The default keyword specifies some code to run if there is no case match:

Example
int day = 4;

switch (day) {
case 6:
printf("Today is Saturday");
break;
case 7:
printf("Today is Sunday");
break;
default:
printf("Looking forward to the Weekend");
}

// Outputs "Looking forward to the Weekend"

Note: The default keyword must be used as the last statement in the switch, and it
does not need a break.

Loops
Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more
readable.

26
While Loop
The while loop loops through a block of code as long as a specified condition is true:

Syntax
while (condition) {
// code block to be executed
}

In the example below, the code in the loop will run, over and over again, as long as
a variable (i) is less than 5:

Example
int i = 0;

while (i < 5) {
printf("%d\n", i);
i++;
}

Note: Do not forget to increase the variable used in the condition (i++), otherwise
the loop will never end!

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as
the condition is true.

Syntax
do {
// code block to be executed
}
while (condition);

The example below uses a do/while loop. The loop will always be executed at least
once, even if the condition is false, because the code block is executed before the
condition is tested:

Example
int i = 0;

do {

27
printf("%d\n", i);
i++;
}
while (i < 5);

Do not forget to increase the variable used in the condition, otherwise the loop will
never end!

For Loop
When you know exactly how many times you want to loop through a block of code,
use the for loop instead of a while loop:

Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example
int i;

for (i = 0; i < 5; i++) {


printf("%d\n", i);
}

Example explained

Statement 1 sets a variable before the loop starts (int i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.

Statement 3 increases a value (i++) each time the code block in the loop has been
executed.

Another Example
This example will only print even values between 0 and 10:

28
Example
for (i = 0; i <= 10; i = i + 2) {
printf("%d\n", i);
}

Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:

Example
int i;

for (i = 0; i < 10; i++) {


if (i == 4) {
break;
}
printf("%d\n", i);
}

Continue
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

Example
int i;

for (i = 0; i < 10; i++) {


if (i == 4) {
continue;
}
printf("%d\n", i);
}

Break and Continue in While Loop


You can also use break and continue in while loops:

29
Break Example
int i = 0;

while (i < 10) {


if (i == 4) {
break;
}
printf("%d\n", i);
i++;
}

Continue Example
int i = 0;

while (i < 10) {


if (i == 4) {
i++;
continue;
}
printf("%d\n", i);
i++;
}

Strings
Strings are used for storing text/characters.

For example, "Hello World" is a string of characters.

Unlike many other programming languages, C does not have a String type to
easily create string variables. However, you can use the char type and create
an array of characters to make a string in C:

char greetings[] = "Hello World!";


Note that you have to use double quotes.

To output the string, you can use the printf() function together with the format
specifier %s to tell C that we are now working with strings:

Example
char greetings[] = "Hello World!";
printf("%s", greetings);

Access Strings

30
Since strings are actually arrays in C, you can access a string by referring to its
index number inside square brackets [].

This example prints the first character (0) in greetings:

Example
char greetings[] = "Hello World!";
printf("%c", greetings[0]);

Note that we have to use the %c format specifier to print a single character.

Modify Strings
To change the value of a specific character in a string, refer to the index number,
and use single quotes:

Example
char greetings[] = "Hello World!";
greetings[0] = 'J';
printf("%s", greetings);
// Outputs Jello World! instead of Hello World!

Another Way of Creating Strings


In the examples above, we used a "string literal" to create a string variable. This is
the easiest way to create a string in C.

You should also note that you can to create a string with a set of characters. This
example will produce the same result as the one above:

Example
char greetings[] = {'H', 'e', 'l', 'l', 'o', '
', 'W', 'o', 'r', 'l', 'd', '!', '\0'};
printf("%s", greetings);

Why do we include the \0 character at the end? This is known as the "null
terminating character", and must be included when creating strings using this
method. It tells C that this is the end of the string.

Differences
The difference between the two ways of creating strings, is that the first method is
easier to write, and you do not have to include the \0 character, as C will do it for
you.

31
You should note that the size of both arrays is the same: They both have 13
characters (space also counts as a character by the way), including
the \0 character:

Example
char greetings[] = {'H', 'e', 'l', 'l', 'o', '
', 'W', 'o', 'r', 'l', 'd', '!', '\0'};
char greetings2[] = "Hello World!";

printf("%lu\n", sizeof(greetings)); // Outputs 13


printf("%lu\n", sizeof(greetings2)); // Outputs 13

Memory Address
When a variable is created in C, a memory address is assigned to the variable.

The memory address is the location of where the variable is stored on the
computer.

When we assign a value to the variable, it is stored in this memory address.

To access it, use the reference operator (&), and the result will represent where the
variable is stored:

Example
int myAge = 43;
printf("%p", &myAge); // Outputs 0x7ffe5367e044
Note: The memory address is in hexadecimal form (0x..). You probably won't get
the same result in your program.

You should also note that &myAge is often called a "pointer". A pointer basically
stores the memory address of a variable as its value. To print pointer values, we
use the %p format specifier.

Creating Pointers
You learned from the previous chapter, that we can get the memory address of a
variable with the reference operator &:

Example
int myAge = 43; // an int variable

printf("%d", myAge); // Outputs the value of myAge (43)


printf("%p", &myAge); // Outputs the memory address of myAge (0x7ffe5367e044)

In the example above, &myAge is also known as a pointer.

32
A pointer is a variable that stores the memory address of another variable as its
value.

A pointer variable points to a data type (like int) of the same type, and is
created with the * operator. The address of the variable you're working with is
assigned to the pointer:

Example
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the name ptr, that stores the
address of myAge

// Output the value of myAge (43)


printf("%d\n", myAge);

// Output the memory address of myAge (0x7ffe5367e044)


printf("%p\n", &myAge);

// Output the memory address of myAge with the pointer (0x7ffe5367e044)


printf("%p\n", ptr);

Example explained

Create a pointer variable with the name ptr, that points to an int variable (myAge).
Note that the type of the pointer has to match the type of the variable you're
working with.

Use the & operator to store the memory address of the myAge variable, and assign it
to the pointer.

Now, ptr holds the value of myAge's memory address.

Dereference
In the example above, we used the pointer variable to get the memory address of
a variable (used together with the & reference operator).

However, you can also get the value of the variable the pointer points to, by using
the * operator (the dereference operator):

Example
int myAge = 43; // Variable declaration
int* ptr = &myAge; // Pointer declaration

// Reference: Output the memory address of myAge with the pointer


(0x7ffe5367e044)
printf("%p\n", ptr);

// Dereference: Output the value of myAge with the pointer (43)

33
printf("%d\n", *ptr);

Note that the * sign can be confusing here, as it does two different things in our
code:

 When used in declaration (int* ptr), it creates a pointer variable.


 When not used in declaration, it act as a dereference operator.

Why Should I Learn About Pointers? Pointers are important in C, because they
give you the ability to manipulate the data in the computer's memory - this can
reduce the code and improve the performance.

Pointers are one of the things that make C stand out from other programming
languages, like Python and Java.

Note: Pointers must be handled with care, since it is possible to damage data
stored in other memory addresses.

Good To Know: There are three ways to declare pointer variables, but the first
way is mostly used:

int* myNum; // Most used


int *myNum;
int * myNum;

Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.

To create an array, define the data type (like int) and specify the name of the
array followed by square brackets [].

To insert values to it, use a comma-separated list, inside curly braces:

int myNumbers[] = {25, 50, 75, 100};

We have now created a variable that holds an array of four integers.

Access the Elements of an Array


To access an array element, refer to its index number.

Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

This statement accesses the value of the first element [0] in myNumbers:

34
Example
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);

// Outputs 25

Change an Array Element


To change the value of a specific element, refer to the index number:

Example
myNumbers[0] = 33;

Example
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;

printf("%d", myNumbers[0]);

// Now outputs 33 instead of 25

Loop through an Array


You can loop through the array elements with the for loop.

The following example outputs all elements in the myNumbers array:

Example
int myNumbers[] = {25, 50, 75, 100};
int i;

for (i = 0; i < 4; i++) {


printf("%d\n", myNumbers[i]);
}

Set Array Size


Another common way to create arrays, is to specify the size of the array, and add
elements later:

35
Example
// Declare an array of four integers:
int myNumbers[4];

// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;

Using this method, you should know the size of the array, in order for the
program to store enough memory.

You are not able to change the size of the array after creation.

C Functions
A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

Functions are used to perform certain actions, and they are important for
reusing code: Define the code once, and use it many times.

Predefined Functions
So it turns out you already know what a function is. You have been using it the
whole time while studying this tutorial!

For example, main() is a function, which is used to execute code, and printf() is a
function; used to output/print text to the screen:

Example
int main() {
printf("Hello World!");
return 0;
}

Create a Function
To create (often referred to as declare) your own function, specify the name of the
function, followed by parentheses () and curly brackets {}:

36
Syntax
void myFunction() {
// code to be executed
}

Example Explained

 myFunction() is the name of the function


 void means that the function does not have a return value. You will learn
more about return values later in the next chapter
 Inside the function (the body), add code that defines what the function
should do

Call a Function
Declared functions are not executed immediately. They are "saved for later use",
and will be executed when they are called.

To call a function, write the function's name followed by two parentheses () and a
semicolon ;

In the following example, myFunction() is used to print a text (the action), when it is
called:

Example
Inside main, call myFunction():

// Create a function
void myFunction() {
printf("I just got executed!");
}

int main() {
myFunction(); // call the function
return 0;
}

// Outputs "I just got executed!"

A function can be called multiple times:

Example
void myFunction() {
printf("I just got executed!");
}

37
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}

// I just got executed!


// I just got executed!
// I just got executed!

Parameters and Arguments


Information can be passed to functions as a parameter. Parameters act as variables
inside the function.

Parameters are specified after the function name, inside the parentheses. You can
add as many parameters as you want, just separate them with a comma:

Syntax
returnType functionName(parameter1, parameter2, parameter3) {
// code to be executed
}

The following function that takes a string of characters with name as parameter.
When the function is called, we pass along a name, which is used inside the
function to print "Hello" and the name of each person.

Example
void myFunction(char name[]) {
printf("Hello %s\n", name);
}

int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}

// Hello Liam
// Hello Jenny
// Hello Anja

When a parameter is passed to the function, it is called an argument. So, from


the example above: name is a parameter,
while Liam, Jenny and Anja are arguments.

38
Multiple Parameters
Inside the function, you can add as many parameters as you want:

Example
void myFunction(char name[], int age) {
printf("Hello %s. You are %d years old.\n", name, age);
}

int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}

// Hello Liam. You are 3 years old.


// Hello Jenny. You are 14 years old.
// Hello Anja. You are 30 years old.

Note that when you are working with multiple parameters, the function call must
have the same number of arguments as there are parameters, and the arguments
must be passed in the same order.

Return Values
The void keyword, used in the previous examples, indicates that the function should
not return a value. If you want the function to return a value, you can use a data
type (such as int or float, etc.) instead of void, and use the return keyword inside
the function:

Example
int myFunction(int x) {
return 5 + x;
}

int main() {
printf("Result is: %d", myFunction(3));

return 0;
}

// Outputs 8 (5 + 3)

This example returns the sum of a function with two parameters:

39
Example
int myFunction(int x, int y) {
return x + y;
}

int main() {
printf("Result is: %d", myFunction(5, 3));

return 0;
}

// Outputs 8 (5 + 3)

You can also store the result in a variable:

Example
int myFunction(int x, int y) {
return x + y;
}

int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);

return 0;
}
// Outputs 8 (5 + 3)

Function Declaration and Definition


You just learned from the previous chapters that you can create and call a function
it the following way:

Example
// Create a function
void myFunction() {
printf("I just got executed!");
}

int main() {
myFunction(); // call the function
return 0;
}

A function consist of two parts:

 Declaration: the function's name, return type, and parameters (if any)

40
 Definition: the body of the function (code to be executed)

void myFunction() { // declaration


// the body of the function (definition)
}

For code optimization, it is recommended to separate the declaration and the


definition of the function.

You will often see C programs that have function declaration above main(), and
function definition below main(). This will make the code better organized and easier
to read:

Example
// Function declaration
void myFunction();

// The main method


int main() {
myFunction(); // call the function
return 0;
}

// Function definition
void myFunction() {
printf("I just got executed!");
}

Another Example
If we use the example from the previous chapter regarding function parameters
and return values:

Example
int myFunction(int x, int y) {
return x + y;
}

int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);

return 0;
}
// Outputs 8 (5 + 3)

It is considered good practice to write it like this instead:

41
Example
// Function declaration
int myFunction(int, int);

// The main method


int main() {
int result = myFunction(5, 3); // call the function
printf("Result is = %d", result);

return 0;
}

// Function definition
int myFunction(int x, int y) {
return x + y;
}

Function prototype
A function prototype is simply the declaration of a function that specifies
function's name, parameters and return type. It doesn't contain function body.

A function prototype gives information to the compiler that the function may later
be used in the program.

#include <stdio.h>
int addNumbers(int a, int b); // function prototype

int main()
{
int n1,n2,sum;

printf("Enters two numbers: ");


scanf("%d %d",&n1,&n2);

sum = addNumbers(n1, n2); // function call


printf("sum = %d",sum);

return 0;
}

int addNumbers(int a, int b) // function definition


{
int result;
result = a+b;
return result; // return statement
}

42
Recursion
Recursion is the technique of making a function call itself. This technique provides a
way to break complicated problems down into simple problems which are easier to
solve.

Recursion may be a bit difficult to understand. The best way to figure out how it
works is to experiment with it.

Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is more
complicated. In the following example, recursion is used to add a range of numbers
together by breaking it down into the simple task of adding two numbers:

Example
int sum(int k);

int main() {
int result = sum(10);
printf("%d", result);
return 0;
}

int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}

Example Explained
When the sum() function is called, it adds parameter k to the sum of all numbers
smaller than k and returns the result. When k becomes 0, the function just returns
0. When running, the program follows these steps:

10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 +9+8+7+6+5+4+3+2+1+0

Since the function does not call itself when k is 0, the program stops there and
returns the result.

43
The developer should be very careful with recursion as it can be quite easy to slip
into writing a function which never terminates, or one that uses excess amounts of
memory or processor power. However, when written correctly recursion can be a
very efficient and mathematically-elegant approach to programming.

Chapter 4 exercise
1. Arduino sketch esa lHkh code processed gksrs gSa ___\
a. Top to Bottom
b. Bottom to Top
c. Any Order
d. None of these.

2. Arduino esa fy[ks x, yxHkx lHkh statement ___ ds lkFk lekIr gksuk pkfg,\
a. Comma (,)
b. Colon (:)
c. Semicolon (;)
d. Full stop (.)

3. Advantage of Arduino?
a. Easy to Learn
b. Huge Community ¼fo’kky leqnk;½
c. Many Third-Party Libraries ¼dbZ r`rh;&i{k ykbczsjh½
d. All of the above.

4. The full form of GPIO is ___?


a. Ground Pin Input / Output
b. Common Pin Input / Output
c. General Purpose Input / Output
d. None of these.

5. setup() ifjHkkf”kr djrk gS ___\


a. PIN functionality using the pinMode function
b. Initial state of pins ¼fiUl dh izkjafHkd voLFkk½
c. Initial Classes and Variables ¼izkjafHkd Dyklsl vkSj osfj,cy½
d. All of the above.

6. Compiler Error is ___\


a. No Semicolon or Parentheses
b. No Variable Initialization
c. Misspellings and Wrong Capitalization
d. All of the above.

7. fuEufyf[kr esa ls dkSu lk dFku serial communication ds ckjs esa lgh gS\
a. Serial Communication ,d device ls nwljs device dks sequentially data Hkstus dh process gSA
b. Serial Communication esa] data bits dks ,d device ls nwljs device esa sequentially Hkstk tkrk gSA
c. Communication ds rst lk/ku provide djrk gSA
d. All of the above.

8. HC-05 Module esa lapkfyr fd;k tk ldrk gS ___\

44
a. Slave Mode
b. Master Mode
c. Both (a) and (b)
d. None of these.
9. Arduino program esa default method gS ___\
a. Only loop()
b. Only setup()
c. setup() and loop()
d. setup() or loop()

10. Module dh x.kuk djus ds fy, Arduino esa fdl sign dk mi;ksx fd;k tkrk gS\
a. #
b. $
c. %
d. !

11. Arduino UNO is ___\


a. Hardware Device
b. Software
c. Network
d. Protocol

12. Arduino UNO esa mi;ksx fd;k tkus okyk microcontroller D;k gS\
a. ATmega32114
b. ATmega2560
c. ATmega328p
d. None of these.

13. ATmega328p esa p D;k n’kkZrk gS\


a. Power-Pico
b. Pico-Power
c. Production
d. Programmable on chip

14. Arduino IDE esa 2 functions gksrs gSaA os D;k gSa\


a. setup() and loop()
b. setup() and build()
c. build() and loop()
d. None of these.

15. Arduino UNO dk default bootloader D;k gS\


a. UF2 Bootloader
b. Optiboot Bootloader
c. Barebox Bootloader
d. None of these.

16. The full form of PWM is ___?


a. Pulse-width modulation
b. Pulse-width module
c. Pulse-width mode

45
d. None of these.

17. Arduino system ds izR;sd startup ij loop function() fdruh ckj run djrk gS\
a. Depends on setup function()
b. Infinite
c. 3
d. 1

18. Arduino ___ environment provide djrk gS\


a. IDE
b. User-friendly
c. Both (a) and (b)
d. None of these.

19. ,d Arduino UNO board esa fdrus PWM pin gksrs gSa\
a. 6
b. 5
c. 13
d. 14

20. IOT development boards esa PWM signals dk D;k mi;ksx gS\
a. They are used by actuators to have digital input.
b. They are used by sensors to have digital input.
c. They are used by sensors to have analog input.
d. They are used by actuators to have analog output.

46
It takes a lot of hard work to make notes, so if you can pay some fee 100, 200
rupees which you think is reasonable, if you are able, Thank you...

नोट् स बनाने में बहुत मेहनत लगी है , इसनलए यनि आप कुछ शुल्क 100, 200 रूपए जो
आपको उनित लगता है pay कर सकते है , अगर आप सक्षम है तो, धन्यवाि ।

47
UPCISS

Computer Language

 What is Computer Language ?


 Types of Language ?
 What is Programming Language ?
 Difference Between POP and OOP ?
 Assembler, Compiler & Interpreter ?
What is Computer Language

Language :- ftl ds ek/;e ls ge vius fopkj O;Dr djrs gSA 'kCnksa ds ,sls

lewg dks Hkk’kk dgk tkrk gSA ftldk dksbZ vFkZ gksrk gSA dEI;wVj ls dk;Z
djkus ds fy;s ftl Hkk"kk esa vius fopkjksa dks O;Dr djrs gS og ;wtj Hkk"kk
gksrh gSA vkSj dEI;wVj ftl Hkk"kk dks le>rk gS og e”khu Hkk"kk ;k ckbZujh
¼0&1½ dgykrh gSA ;wtj Hkk"kk dks e”khu Hkk"kk esa cnyus ds fy;s ,d flLVe
lk¶Vos;j dh vko”;drk gksrh gSA ftls Translator dgk tkrk gSA
Types of Language

Computer
Language

Low level High level


Language Language

High Level Language


Machine Assembly
Language Language Low Level Language
CPU
What is Programming Language

Programming Language eryc ,d ,slh ySaXost ftls cuk;k


x;k gS fMftVy e’khu ls dk;Z djkus ds fy,A ljy “kCnksa esa dgsa rks
izksxzkfeax ySaXost dk bLrseky Software and Web application
dks Msoyi djus ds fy, fd;k tkrk gSA mu Software
program ds n~okjk igys ls gh r; fd;s dk;Z dj ldrs gSaA
इस समय लगभग 2,500 प्रोग्राममिंग भाषाएिं मौजूद हैं ।
Machine Level Language

Machine Level Language:- ;g og Hkk"kk gksrh gS] tks dEI;wVj le>rk gSA
bls ckbujh Hkk"kk dgk tkrk gSA bldk iz;ksx izFke ih<+h ds dEI;wVjl esa fd;k x;k
Fkk A blesa fy[ks x;s izksxzke rhoz xfr ls ju gksrs gSA D;ksa fd bl ij lh/ks
izkslsaflax dh tkrh gSA blesa dksbZ Hkh Translator lk¶Vos;j dh vko”;drk ugha
gksrh FkhA bldk dk vkmViqV Hkh blh Hkk"kk esa vkrk gSA blesa izksxzkfeax djuk
dfBu gksrk gSA ;g e”khu ij vk/kkfjr gksrh gSA
Assembly Language

Assembly Language :- Machine language dh deh;ksa dks nwj djus ds


fy;s vklsEcyh Hkk"kk dk fodkl fd;k x;k A blesa buiqV ds fy, ckbZujh Hkk"kk ds
LFkku ij mnemonic code dk iz;ksx fd;k x;k FkkA ftudks ;kn j[kuk vklku
Fkk A bu dksM dks ek”khu Hkk"kk es cnyus ds fy;s vklsEcyj dk iz;ksx fd;k tkrk
Fkk tks ,d flLVe Software gSA bl Hkk"kk esa izksxzkfeax djuk e’khu Hkk"kk dh
vis{kk ljy gksrk gSA bldk iz;ksx f}rh; ih<+h ds dEI;wVj esa fd;k x;k FkkA buds
izksxzke dks igys e”khu Hkk"kk esa cnyk tkrk FkkA ftlls budh xfr e”khu Hkk"kk ls
de gksrh gSA Code :- HLT, ADD , CLA , SUB, STA etc..
High Level Language

High Level Language:- Assembly Language dh deh;ksa dks nwj djus ds fy;s
gkbZ ysfoy Hkk"kk dk fodkl fd;k x;k A blesa mnemonic code ds LFkku ij dEI;wVj
dks English Hkk"kk esa funsZ”k fn;s tkus yxs] ftl ls izksxzke dks le>uk ,oa fy[kuk vklku
gks x;k gSA ;g Hkk’kk e’khu ij vk/kkfjr ugh gksrh gSA blesa izksxzke dks e’khu Hkk"kk esa
cnyus ds fy;s compiler and Interpreter dk iz;ksx fd;k tkrk gSA vktdy dEI;wVj
esa izksxzkfeax djus ds fy;s blh Hkk"kk dk iz;ksx fd;k tk jgk gSA bl Hkk"kk dks dk;Z ds
vk/kkj ij nks oxksZ esa ckaVk x;k gSA
1. Procedure-oriented Programming.
2. Object-oriented programming.
Procedure-oriented Programming

POP :- POP esa fdlh programming problem ds gy dks Øec) dk;Z djus tSls&
reading, processing vkSj writing ds :i esa ns[kk tkrk gS vkSj bu dk;ksZ dks iwjk
djus ds fy, cgqr lkjs functions fy[ks tkrs gSaA POP dh ,d cM+h deh ;g gS fd ;g
leL;k ls lacaf/kr entities dk model rS;kj ugha dj ikrk gSA POP dh nwljh xaHkhj
leL;k ;g gS fd blesa dbZ lkjs data items dks global declare fd;k tkrk gS] blls
gekjk MsVk vlqjf{kr gks tkrk gS D;ksa fd bls fdlh Hkh functions ds }kjk vuko”;d :i
ls ifjofrZr fd;k tk ldrk gSA
Example - C, FORTRAN, VB, Pascal.
Object-oriented Programming

OOP :- OOP esa leL;k dks gy djus ds fy, igys ge leL;k ls lacfa /kr entities dk
model rS;kj djrs gS ftUgsa object dgrs gSaA object, lacaf/kr data o functins ds
lewg gksrs gSaA okLrfod nqfu;k esa izR;sd entity ds dqN u dqN data o functions gksrs
gSaA ,d object ds varxZr vkus okys data dks dsoy mlh object ds functions ds
}kjk gh access fd;k tk ldrk gS] fdUrq ,d object ds varxZr vkus okys functions
dks nwljs object ds functions ds }kjk Hkh access fd;k tk ldrk gSA bl izdkj
OOP esa data ckgjh object ls fNik gqvk o lqjf{kr jgrk gSA
Example - C++, JAVA, PYTHON, VB.NET, C#.NET.
Difference Between OOP and POP

POP OOP
blesa cM+s izksxzke NksVs&NksVs Hkkxksa esa foHkkftr jgrs gSa blesa cM+s izksxzke NksVs&NksVs Hkkxksa esa foHkkftr jgrs
ftUgsa function dgk tkrk gSA gSa ftUgsa object dgk tkrk gSA

izksxzke cukrs le; function ij T;knk /;ku fn;k izksxzke cukrs le; data ij T;knk /;ku fn;k
tkrk gSA tkrk gSA

T;knkrj function global data dk iz;ksx djrs gSaA data structure gh objects dh fo”ks’krk gksrh gSA

dksbZ Hkh function data dks izkIr djds ifjofrZr dj dsoy class ds function gh data dks izkIr djds
ldrk gSA ifjofrZr dj ldrs gSaA

izksxzke fMtkbZu esa top down approach dk iz;ksx izksxzke fMtkbZu esa bottom up approach dk
fd;k tkrk gSA iz;ksx fd;k tkrk gSA
Translator

1- Assembler 2- Compiler 3- Interpreter

Assembler :- Assembler , ,d System Software gSA tks assembly


Language Program dks Machine Language esa cnyrk gSA vkSj
Machine Language dks Assembly language esa cnyrk gSA

Assembly
Language
Assembler Machine -01
Source Code Translator Object Code
Compiler & Interpreter

Compiler vkSj Interpreter nksuks gh system Software gS] tks High


level language program dks Machine level Language esa
Translator djus dk dke djrs gSAa compiler iwjs program dks ,d lkFk
Translate djrk gS] tc fd Interpreter Line by Line Translate djrk
gSA

HLL Code C&I Machine -01


Source Code Translator Object Code
Source code & Object code

Programmer Machine
Source Code Object Code
Compiler
Some High Level Language
• Java
• Python
• HTML
• JavaScript
• C#
• C++
• PHP
• Ruby
• Perl
• C - Some consider it a “mid-level” language
Thank you for watching
Microsoft Windows Shortcut Keys and Description
Shortcut Keys Description
Win + R Run
Win + E My Computer
Win + D Desktop
Win + F , (F3) Search
Win + L Log Off
Win + F1 Help
Win + PAUSE BREAK System Properties
Alt + SPACE + R Restore
Alt + SPACE + N Minimize
Alt + SPACE + X Maximize
Alt + SPACE + C Close
Alt + SPACE + M Move
Alt + SPACE + S Size
Alt + F4 Close
Esc Cancel
F5 Refresh
Shift + Delete Delete without moving Recycle Bin
F2 Rename the selected item
Alt + Enter Display properties for the selected item
Alt + F4 Exit the active program
Shift + F10 Display the right-click menu for the selected item
Microsoft Word Shortcut Keys and Description
Shortcut Keys Description
CTRL + A Select All
CTRL + B Selected Text Bold
CTRL + C Selected Text Copy
CTRL + D Open Font Dialog box
CTRL + E Center Alignment
CTRL + F Find
CTRL + G Go to
CTRL + H Replace
CTRL + I Selected Text Italic
CTRL + J Justify Alignment
CTRL + K Insert Hyperlink
CTRL + L Left Alignment
CTRL + M Left Indent the Hanging
CTRL + N Blank New Document
CTRL + O Open
CTRL + P Print
CTRL + R Right Alignment
CTRL + S Save
CTRL + T Paragraphs Hanging Indent
CTRL + U Underline
CTRL + V Paste
CTRL + W (Ctrl+F4) Close The Window
CTRL + X Cut
CTRL + Y Redo
CTRL + Z Undo
CTRL + 1 Single Line Space
CTRL + 2 Double Line Space
CTRL + 5 1.5 Line Space
Microsoft Word
F1 Help
F4 Repeat the last action
F5 Find , Replace, Go to
F7 Spelling and Grammar
F12 Save As
Ctrl + Shift + A UPPER CASE
Ctrl + Shift + K lower case
Ctrl + Shift + C Copy formatting only
Ctrl + Shift + V Paste formatting only
Ctrl + Shift + N Clear All Formatting
Ctrl + Space Clear All Formatting
Ctrl + Shift + G Word Count
Ctrl + Shift + W Underline words but not spaces
Ctrl + Shift + D Double-underline
Ctrl + Shift + H Hidden text formatting
Ctrl + Shift + T Reduce a left hanging indent
CTRL + Shift + L Quickly create a bullet point
CTRL + Shift + F Quickly changed the font
CTRL + Shift + P Quickly changed the font size
CTRL + Shift + > Increase font size 2pt (Up to 12pt)
CTRL + Shift + < Decrease font size 2pt (Up to 12pt)
CTRL + ] Increase font 1pt
CTRL + [ Decrease font 1pt
CTRL + Home Cursor to the beginning of the document
CTRL + End Cursor to the End of the document
CTRL + Backspace To delete the word to the Left of the cursor
CTRL + Delete To delete the word to the Right of the cursor
Microsoft Word
Alt + Ctrl + I (Ctrl+F2) Print preview
Alt + Ctrl + M Insert a comment
Alt + Ctrl + N Switch to Draft (Normal) view
Alt + Ctrl + V Paste special
Alt + Ctrl + Z Switch between the last four places that you have edited

Alt + Shift + D Insert current date


Alt + Shift + T Inert current time
Ctrl + F10 Maximize and Restore program window
Ctrl + Shift + = Superscript
Ctrl + = Subscript

Keyboard Symbol
+ Plus " Double Quote
- Minus & Ampersand
* Asterisk # Hash
/ Slash $ Dollar
\ Back slash ^ Caret
% Percent < Lesser than
| Vertical bar > Greater than
~ Tilde = Equal to
? Question mark ( Open Parenthesis
! Exclamation mark ) Close Parenthesis
, Comma [ Open bracket
. Full stop ] Close bracket
; Semicolon { Open Set bracket
: Colon } Close Set bracket
' Apostrophe _ Underscore
Microsoft Excel Shortcut Keys and Description
Shortcut Keys Description
CTRL + D Fill down
CTRL + R Fill to the right
F2 Edit the active cell
CTRL + F3 Define a name
CTRL + 1 Format Cells Dialog box
CTRL + F5 Restore the active workbook window
CTRL + F6 Switch to the next workbook window
CTRL + F9 Minimize the workbook
CTRL + F10 Maximize or restore the workbook
SHIFT + ENTER Move up in the selection
ALT + ENTER Start a new line in the same cell
SHIFT + F2 Edit a cell comment
CTRL + ; Insert current date
CTRL + SHIFT + ; Inert current time
Ctrl + Space Select the entire column
Shift + Space Select the entire row
Ctrl + Shift + Space Select the entire worksheet
Ctrl + - Delete the selected cells
Ctrl + Shift + ~ Apply the General number format
Ctrl + Shift + $ Apply to the Currency format
Ctrl + Shift + % Apply to the Percentage format
Ctrl + Shift + ^ Exponential number format
Ctrl + Shift + # Apply the Date format
Ctrl + Shift + @ Apply the Time format
Ctrl + 9 Hide the selected rows
Ctrl + 0 Hide the selected columns
Ctrl + Shift + ( Unhide any hidden rows
Ctrl + Shift + ) Unhide any hidden columns
Ctrl + Shift + & Apply the outline border
Ctrl + Shift + _ Remove the outline border

You might also like