Professional Documents
Culture Documents
Ilovepdf Merged
Ilovepdf Merged
Ilovepdf Merged
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
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
..
2
www.upcissyoutube.com O level M3-R5
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”.
4
www.upcissyoutube.com O level M3-R5
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.
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
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.
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.
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 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
9
www.upcissyoutube.com O level M3-R5
Algorithm Flowchart
Algorithm is complex to
understand. Flowchart is easy to understand.
10
www.upcissyoutube.com O level M3-R5
Flowchart for find the largest among three different numbers entered by the user.
11
www.upcissyoutube.com O level M3-R5
12
www.upcissyoutube.com O level M3-R5
13
www.upcissyoutube.com O level M3-R5
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
15
www.upcissyoutube.com O level M3-R5
16
www.upcissyoutube.com O level M3-R5
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.
Why Python?
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 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
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.
From there you can write any python, including our hello world example from
earlier in the tutorial:
Whenever you are done in the python command line, you can simply type the
following to quit the python command line interface:
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
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)
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:
20
www.upcissyoutube.com O level M3-R5
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
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)
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 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!")
Python does not really have a syntax for multi line comments.
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
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
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
Example Integers:
x = 1
y = 35656222554887711
z = -3255522
Float
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:
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
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.
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
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
25
www.upcissyoutube.com O level M3-R5
Note: in the result, the line breaks are inserted at the same position as in the
code.
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 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 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
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:
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.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
28
www.upcissyoutube.com O level M3-R5
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= 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
29
www.upcissyoutube.com O level M3-R5
== Equal x == y
!= Not equal x != y
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:
30
www.upcissyoutube.com O level M3-R5
<< 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
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
Access Items
You can loop through the list items by using a for loop:
List Length
To determine how many items a list has, use the len() method:
Add Items
To add an item to the end of the list, use the append() method:
32
www.upcissyoutube.com O level M3-R5
Remove Item
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 can also delete the list completely:
thislist = ["apple", "banana", "cherry"]
del thislist
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
List Methods
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
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
34
www.upcissyoutube.com O level M3-R5
Python Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets.
You can access tuple items by referring to the index number, inside square
brackets:
Once a tuple is created, you cannot change its values. Tuples are unchangeable.
You can loop through the tuple items by using a for loop.
Tuple Length
35
www.upcissyoutube.com O level M3-R5
To determine how many items a tuple has, use the len() method:
Add Items
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Remove Items
Tuples are unchangeable, so you cannot remove items from it, but you can delete
the tuple completely:
Python Sets
A set is a collection which is unordered and unindexed. In Python sets are written
with curly brackets.
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)
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")
To determine how many items a set has, use the len() method.
print(len(thisset)) # returns 3
Remove Item
thisset.remove("banana")
37
www.upcissyoutube.com O level M3-R5
thisset.discard("banana")
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.
x = thisset.pop()
Note: Sets are unordered, so when using the pop() method, you will not know
which item that gets removed.
del 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
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square
brackets:
Change Values
You can change the value of a specific item by referring to its key name:
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)
Dictionary Length
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
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
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().
41
www.upcissyoutube.com O level M3-R5
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)
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.
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.
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")
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".
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.
If you have only one statement to execute, one for if, and one for else, you can put
it all on the same line:
You can also have multiple else statements on the same line:
And
Or
while loops
for loops
44
www.upcissyoutube.com O level M3-R5
With the while loop we can execute a set of statements as long as a condition is
true.
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.
With the break statement we can stop the loop even if the while condition is true:
With the continue statement we can stop the current iteration, and continue with
the next:
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.
The for loop does not require an indexing variable to set beforehand.
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", but this time the break comes before the print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
With the continue statement we can stop the current iteration of the loop, and
continue with the next:
46
www.upcissyoutube.com O level M3-R5
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
The "inner loop" will be executed one time for each iteration of the "outer loop":
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.
Creating a Function
Example
def my_function():
print("Hello from a function")
Calling a Function
Example
def my_function():
print("Hello from a function")
my_function()
Parameters
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")
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")
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)
Return Values
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
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))
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))
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.
Create a Class
Create Object
52
www.upcissyoutube.com O level M3-R5
The examples above are classes and objects in their simplest form, and are not
really useful in real life applications.
All classes have a function called __init__(), which is always executed when the
class is being initiated.
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.
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 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:
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Delete Objects
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
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()
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()
So far we have created a child class that inherits the properties and methods from
it's parent.
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
When you add the __init__() function, the child class will no longer inherit 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.
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
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.
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:
print(next(myit))
print(next(myit))
print(next(myit))
57
www.upcissyoutube.com O level M3-R5
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
for x in mytuple:
print(x)
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
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.
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.
myfunc()
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.
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?
Create a Module
To create a module just save the code you want in a file with the file
extension .py:
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")
Variables in Module
The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):
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.
x = platform.system()
print(x)
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.
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
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 >=Python3.4
import importlib
importlib.reload(module)
64
www.upcissyoutube.com O level M3-R5
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.
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.
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
66
www.upcissyoutube.com O level M3-R5
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:
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
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.
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 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:
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%Z Timezone CST
68
www.upcissyoutube.com O level M3-R5
%% A % character %
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.
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:
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")
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
if x < 0:
raise Exception("Sorry, no numbers below zero")
You can define what kind of error to raise, and the text to print to the user.
File Handling
The key function for working with files in Python is the open() function.
"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
"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
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
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.
Assume we have the following file, located in the same folder as Python:
demofile.txt
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:
By default the read() method returns the whole text, but you can also specify how
many characters you want to return:
Read Lines
By calling readline() two times, you can read the two first lines:
By looping through the lines of the file, you can read the whole file, line by line:
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.
To write to an existing file, you must add a parameter to the open() function:
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()
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")
74
www.upcissyoutube.com O level M3-R5
To delete a file, you must import the OS module, and run its os.remove() function:
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
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.
# 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
Output:
Hello
This is Delhi
This is Paris
This is London
The tell() method returns the current file position in a file stream.
Tip: You can change the current file position with the seek method.
The seek() method sets the current file position in a file stream.
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:
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
Example
78
www.upcissyoutube.com O level M3-R5
Note: As a default optional argument, it includes -h, along with its long version –
help.
79
www.upcissyoutube.com O level M3-R5
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.
80
www.upcissyoutube.com O level M3-R5
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)
81
www.upcissyoutube.com O level M3-R5
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)
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)
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])
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])
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])
86
www.upcissyoutube.com O level M3-R5
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')
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.
89
www.upcissyoutube.com O level M3-R5
90
www.upcissyoutube.com O level M3-R5
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.
91
www.upcissyoutube.com O level M3-R5
92
www.upcissyoutube.com O level M3-R5
93
www.upcissyoutube.com O level M3-R5
94
www.upcissyoutube.com O level M3-R5
95
www.upcissyoutube.com O level M3-R5
96
www.upcissyoutube.com O level M3-R5
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.
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)
98
www.upcissyoutube.com O level M3-R5
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)
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)
101
www.upcissyoutube.com O level M3-R5
Related to Python
eval() Function
The eval() function evaluates the specified expression, if the expression is a legal
Python statement, it will be executed.
swapcase() Method
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
The join() method takes all items in an iterable and joins them into one string.
l=['welcome','to','upciss']
msg=' '.join(l)
print(msg)
welcome to upciss
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.
102
www.upcissyoutube.com O level M3-R5
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
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
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
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
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.
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
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
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
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
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
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
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
16
bldh coverage range 100 miter vkSj data transfer rate 250 Kbps rd
gksrh gSA
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
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
21
The Physical Design/Logical Design of IoT
एक IoT system में बहुत सारें functional blocks होते है िो जक जसस्टम को indentify,
sensing, actuation, communication और management की िमता प्रदान करते
हैं . इसका जित्र नीिे जदया गया है .
22
IoT Communication Models
23
Publish Subscribe Model –
यह एक प्रकार का कम्युजनकेशन मॉडल होता है जिसमें publisher, broker और
consumer सम्मिजलत रहते हैं . इसमें publishers डाटा को collect करते हैं और
इस data को publish करते हैं . Broker के द्वारा इस data को manage जकया
िाता है . इस data को consumer के द्वारा subscribe जकया िाता है .
िब भी broker को publisher से कोई data जमलता है तो वह इस data को
subscribe जकये हुए consumer को भेि दे ता है . इसका जित् र नीिे जदया गया है .
24
Exclusive Pair Model –
Exclusive pair एक bi-directional और fully duplex कम्युजनकेशन मॉडल होता
है िो client और server के मध्य एक persistent connection का प्रयोग करता
है .
यह एक fully duplex मॉडल होता है जिसका अथय है जक इसमें client और server
दोनों एक दू सरे को message भेि सकते हैं .
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
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
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
2
Features of control system: Accuracy, Energy Saving, Improved
Safety, Stability, Speed etc…
3
Difference between Open and Closed Loop Control System.
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 model यह बताता है कक ककसी नेटवकम में डे टा या सूचना कैसे send तथा receive होती है ।
इस मॉडल के सभी layers का अपना अलग अलग काम होता है कजससे कक डे टा एक कसस्टम से
दू सरे कसस्टम तक आसानी से पहुाँ च सके। OSI मॉडल यह भी describe करता है कक नेटवकम
हाडम वेयर तथा सॉफ्टवेयर एक दू सरे के साथ ले यर के रूप में कैसे कायम करते है । इस मॉडल की 7
ले यर होती है और प्रत्येक ले यर का अपना एक कविे ष कायम होता है .
5
Physical Layer
OSI model में physical ले यर सबसे नीचे की ले यर है । यह ले यर कफकजकल तथा इले ल्कररकल
कनेक्शन के कलए कजम्मेदार रहता है जै से:- वोल्टे ज, डे टा रे ट् स आकद। इस ले यर में कडकजटल कसग्नल,
इले ल्कररकल कसग्नल में बदल जाता है । इस लेयर में नेटवकम की topology अथामत layout of
network का कायम भी इसी ले यर में होता है ।
इस ले यर में नेटवकम लेयर द्वारा भेजे गए डे टा के पैकेटोीं को decode तथा encode ककया जाता है
तथा यह ले यर यह भी ensure करता है कक डे टा के ये पैकेट् स error free हो।
इस ले यर को फ्रेम यूकनट भी कहा जाता है । इस layer में डे टा टर ाीं सकमिन के कलए दो प्रोटोकॉल
प्रयोग होते है . HDLC (High-level data link control) & PPP (Point-to-Point Protocol).
इसका मुख्य कायम flow control करना है . इसमें receiver और sender दोनोीं तरफ से एक कनयत
data rate को maintain ककया जाता है . कजससे कक कोई भी data corrupt ना हो.
Network Layer
नेटवकम ले यर OSI model का तीसरा ले यर है इस ले यर में switching तथा routing तकनीक का
प्रयोग ककया जाता है । इसका कायम Logical address अथाम त IP address भी उपलब्ध कराना है ।
6
नेटवकम ले यर में जो डे टा होता है वह पैकेट (डे टा के समूह) के रूप में होता है और इन पैकेटोीं को
source से destination तक पहुाँ चाने का काम नेटवकम ले यर का होता है । इस ले यर को पैकेट यूकनट
भी कहा जाता है ।
इस layer का काम routing का भी है . यह सबसे अच्छे path (रास्ते) को कनिाम ररत करती है .
Transport Layer
टर ाीं सपोटम ले यर OSI मॉडल की चौथी ले यर है । इस ले यर का प्रयोग डे टा को नेटवकम के मध्य में से
सही तरीके से टर ान्सफर ककया जाता है । इस ले यर का कायम दो कींप्यूटरोीं के मध्य कम्युकनकेिन को
उपलब्ध कराना भी है । इसे सेगमेंट यूकनट भी कहा जाता है ।
Session Layer
सेिन ले यर OSI model की पाीं चवी ले यर है जो कक बहुत सारें कींप्यूटरोीं के मध्य कनेक्शन को
कनयींकत्रत करती है । सेिन ले यर दो कडवाइसोीं के मध्य कम्युकनकेिन के कलए सेिन उपलब्ध कराता
है अथामत जब भी कोई यूजर कोई भी वेबसाइट खोलता है तो यूजर के कींप्यूटर कसस्टम तथा
वेबसाइट के सवमर के मध्य तक सेिन का कनमाम ण होता है ।
आसान िब्ोीं में कहें तो सेिन ले यर का मुख्य कायम यह दे खना है कक ककस प्रकार कनेक्शन को
establish, maintain तथा terminate ककया जाता है ।
7
Session layer जो है वह dialog controller की भाीं कत कायम करती है . यह दो processes के मध्य
dialog को create करती है . यह synchronization के कायम को भी पूरा करती है . अथाम त् जब भी
transmission में कोई error आ जाती है तो टर ाीं सकमिन को दु बारा ककया जाता है .
Presentation Layer
Presentation ले यर OSI मॉडल का छटवाीं ले यर है । इस ले यर का प्रयोग डे टा का encryption तथा
decryption के कलए ककया जाता है । इसे डे टा compression के कलए भी प्रयोग में लाया जाता है ।
यह ले यर ऑपरे कटीं ग कसस्टम से सम्बींकित है ।
Application Layer
एप्लीकेिन ले यर OSI model का सातवााँ (सबसे उच्चतम) लेयर है । एप्लीकेिन ले यर का मुख्य
कायम हमारी वास्तकवक एप्लीकेिन तथा अन्य Layer के मध्य interface कराना है ।
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
यह 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
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 ने कवककसत ककया है .
इस मॉडल का इस्तेमाल बहुत कम ककया जाता है . इस model का उपयोग ज्यादा ककया जाता है .
10
Transmission Mode
वह डायरे क्शन कजस पर डे टा या सूचना एक थथान से दु सरे थथान पर टर ाीं सकमट होती है
transmission mode कहलाती है . यह सूचना के flow होने की कदिा को indicate करता है . इसे
communication mode भी कहते है . यह 3 Types के होते है :
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
इन दोनो 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 को डाटा भेजने का सबसे ते ज माध्यम माना जाता है ।
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
होने की सींभावना सबसे अकिक होती है ।
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 कर सकते हैं .
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 तथा कमसाइल
गाइडें स कसस्टम आकद में ककया जाता है .
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.
16
c. Both (a) and (b)
d. None of these.
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
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.
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.
17. OSI Model esa fdl layer dks port layer dgk tkrk gS\
a. Application
b. Presentation
c. Transport
d. Session
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.
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
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
Light Sensor
3
Accelerometer Sensor
Accelerometer Sensor ऐसा उपकरण है जो ककसी कवशे ि कडवाइस या वाहन के गकत त्वरण या
वेग को मापता हैं । यह सेंसर बहुत से ऍक्ट्लकेशन के कलए प्रयोग ककया जाता है । जै से- हाथ के इशारे
से रोबोट कनयंकत्रत करना, कवमान और कमसाइलों के कलए नेकवगेशन सुकविा, वाहन त्वरण, और
टरबाइन, रोलर, पंखे, कंप्रेसर, पंप जै से और दू सरे रोटे कटं ग इले रिॉकनक कडवाइस।
Pressure Sensor
Ultrasonic Sensor
4
Touch Sensor
Touch Sensor को Tactile Sensor भी कहते है । इसका उपयोग शारीररक स्पशि का पता करने
और इं डक्ट्स्टियल ऍक्ट्लकेशन में ककया जाता है । जै से लाइट क्ट्िि ऑन/ऑफ, एयर कंडीशनर (AC)
द्वारा ररमोट कंटि ोल, दरवाजे खोलना/बंद करना, रोबोकटक्स, लै पटॉप, स्माटि फोन इत्याकद।
उदाहरण तौर पर- ऑक्सीमीटर (Oximeter) मानव शरीर में ऑक्सीजन के स्तर का पता लगाने
के कलए Touch Sensors का सबसे अच्छा उदाहरण है । इस COVID-19 महामारी में, Pulse
Oximeter का अकिक मां ग हैं । अपने घर पर भी इसका इस्तेमाल करना काफी आसान हैं ।
गैस या िुंए का पता करने के कलए कजस उपकरण का इस्तेमाल ककया जाता है , उसे स्मोक सेंसर
(Smoke Sensor) कहा जाता है । ये सेंसर कवकभन्न प्रकार के ज़हरीली गैसों या कवस्फोटक गैसें हवा
मे िुएं का पता करती है । Smoke Sensor का प्रयोग इमारतों, जहाजों, लां ट, उद्योगों, हवाई जहाज
आकद में ककया जाता है । Smoke या Gas Sensor को तीन भागों में बां टा गया हैं ।
Optical Type Smoke Sensors
Ionization Type Smoke Sensors
Laser Type Smoke Sensors
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 कम होता है .
3. आमतौर पर यह अन्य उपकरणों में embed (जु ड़ा) रहता है और उन उपकरणों के कायो
को control करता है .
4. Microcontroller के द्वारा प्रयोग ककया जाने वाला प्रोग्राम ROM में स्टोर रहता है .
5. यह उन पररक्ट्स्प्थकतयों में प्रयोग होता है जहां सीकमत कंप्यूकटं ग कायों की आवश्यकता होती
है ।
Microcontroller Microprocessor
िूूँकक इसमें memory और I/O आं तररक रूप से िूूँकक इसमें memory और I/O बाहरी रूप
(internally) जुड़े रहते है . इसकलए इसका size से (externally) जु ड़े रहते है . इसकलए
छोटा होता है . इसका size बड़ा होता है .
9
पूरे कसस्टम का मूल्य कम होता है . पूरे system का cost (मूल्य) बढ़ जाता है .
इसमें power (कबजली) कम खिि होती है . इसमें कबजली ज्यादा खिि होती है .
इसका मुख्यतः प्रयोग washing machines, MP3 इसका मुख्यतः प्रयोग personal
player’s आकद में ककया जाता है . computers में ककया जाता है .
Bit
कबट के आिार पर हम माइक्रो-कंटि ोलर को तीन categories में कवभाकजत कर सकते हैं :-
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 में इनका प्रयोग ककया जाता है .
3. आग को detect करने वाली कडवाइस तथा safety devices जै से:- fire alarm में.
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 के मध्य
इं टरफ़ेस प्रदान करता है .
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.
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.
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.
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
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.
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
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.
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.
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
Get Started
It is not necessary to have any prior programming experience.
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.
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.
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 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.
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).
Example
// This is a comment
printf("Hello World!");
Example
printf("Hello World!"); // This is a comment
10
C Multi-line Comments
Multi-line comments start with /* and ends with */.
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.
C Variables
Variables are containers for storing data values.
In C, there are different types of variables (defined with different keywords), for
example:
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:
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.
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
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.
Example
int x = 5;
int y = 6;
int sum = x + y;
printf("%d", sum);
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.
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
14
Example
// Good
int minutesPerHour = 60;
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);
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
%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:
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.
Example
Output a number entered by the user:
// Create an integer variable that will store the number we get from the user
int 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.
Example
Output the name of a user:
17
// Create a string
char firstName[30];
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)
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
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;
Example
int x = 10;
x += 5;
= 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
19
|= 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
== Equal to x == y
!= Not equal x != y
Logical Operators
Logical operators are used to determine the logic between variables or values:
&& Logical and Returns true if both statements are true x < 5 && x < 10
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));
You can use these conditions to perform different actions for different decisions.
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");
}
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".
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".
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.");
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:
Example
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
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.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
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;
}
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.
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");
}
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!
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 3 is executed (every time) after the code block has been executed.
Example
int i;
Example explained
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.
Example
int 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.
Example
int i;
29
Break Example
int i = 0;
Continue Example
int i = 0;
Strings
Strings are used for storing text/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:
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 [].
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!
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!";
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.
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
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
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.
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
33
printf("%d\n", *ptr);
Note that the * sign can be confusing here, as it does two different things in our
code:
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:
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 [].
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
Example
myNumbers[0] = 33;
Example
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
Example
int myNumbers[] = {25, 50, 75, 100};
int i;
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.
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
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;
}
Example
void myFunction() {
printf("I just got executed!");
}
37
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
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
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;
}
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)
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)
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)
Example
// Create a function
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the function
return 0;
}
Declaration: the function's name, return type, and parameters (if any)
40
Definition: the body of the function (code to be executed)
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();
// 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)
41
Example
// Function declaration
int myFunction(int, int);
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;
return 0;
}
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.
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.
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. !
12. Arduino UNO esa mi;ksx fd;k tkus okyk microcontroller D;k gS\
a. ATmega32114
b. ATmega2560
c. ATmega328p
d. None of these.
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
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
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
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
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
Assembly
Language
Assembler Machine -01
Source Code Translator Object Code
Compiler & Interpreter
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
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