0% found this document useful (0 votes)
5 views49 pages

XI Python Basics Notes

Uploaded by

Nischaya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views49 pages

XI Python Basics Notes

Uploaded by

Nischaya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

ID of an object

All objects in Python has its own unique id. Object means any String, Number, List, Class
etc.

The id is assigned to the object when it is created.

The id is the object's memory address, and will be different for each time you run the
program. (except for some object that has a constant unique id, like integers from -5 to
256).

Syntax to find id of an object


id(object)

Ex:- x=10

id(x) will give you the id of an object.for ex:- 2062607264

Note:- Output varies with different runs.

# This program shows various identities Output:-


str1 = "geek" 140252505691448
print(id(str1)) 140252505691448
True
str2 = "geek" 140252505691840
print(id(str2)) 140252505739928
False
# This will return True
print(id(str1) == id(str2))

# Use in Lists
list1 = ["aakash", "priya", "abdul"]
print(id(list1[0]))
print(id(list1[2]))

# This returns false


print(id(list1[0])==id(list1[2]))

is keyword
This keyword is used to test object identity. The “is keyword” is used to test whether two variables belong to
the same object. The test will return True if the two objects are the same else it will return False even if the
two objects are 100% equal.

Note: The == operator is used to test if two objects are the same.

Syntax: a is b

# Using if statement

if a is b:
statement(s)

Example 1:

# Python program to demonstrate Output :


# is keyword False
True

x = ["a", "b", "c", "d"]

y = ["a", "b", "c", "d"]


print(x is y)
print(x == y)

Conditional Statements:-
Types of If Statements

1) 2)
If <condition>: If <condition>:
Statements….. Statements…..
……………………. …………………….
else:
Ex: Statements…..
…………………….
if a>b: Ex:
print(“a is greater”)
if a>b:
print(“a is greater”)
else:
print(“b is greater”)

3) Ex:-
if <condition1>: if a>b:
Statements….. print(“a is greater”)
……………………. elif b>a:
elif <condition2>: print(“b is greater”)
else:
Statements…..
print(“both are equal”)
…………………….
elif <condition3>:
Statements…..
…………………….
else:
Statements…..
…………………….
LOOPS:-

For loop While loop

Different Forms while <condition>:


statements……
1)for i in [1,2,3,4]: increment or decrement
statements……
Ex:- To Print all odd no.’s from 1 to 10
2)for i not in [1,2,3,4]:
statements…… i=1
while i<=10:
3)for i in range(1,11): print i
statements…… i+=2

Ex:- To Print all odd no.’s from 1 to 10

for i in range(1,11,2):
print i

for i in range(10,0,-2):
print i

JUMP statements-break and continue


break:- A break statement skips the rest of the loop and jumps over to
the statement following the loop.
continue:-a continue statement skips the current loop step and causes
the next iteration or step of the loop to takes place.
for i in range(1,6): for i in range(1,6):
if i==3: if i==3:
break continue
else: else:
print (i) print (i)
Output:- Output:-
1 1
2 2
4
5
Loop else statement
It executes only in the case of normal termination of
loop. So, it will not be executed when break is used
as a break statement terminates the loop
abnormally.
For Ex:-
for i in range (1,11,2): i=1
print(i) while(i<11):
else: print(i)
print(“printing odd values i=i+2
from 1 to 10”) else:
print("printing odd values
from 1 to 10")

The loop else part thus will not be executed when the
loop is infinite or the loop is prematurely exited due
to break statement.
Nested Loops
When a loop contains another loop in its body, it is
called nested loop.
For Ex:-
for i in range(1,6): i=1
for j in range(1,i+1): while i<=5:
print(“*”,end=’ ’) j=1
print() while j<i:
print('*',end=' ')
output:- j=j+1
* print()
** i=i+1
*** output:-
**** *
***** **
***
****

Random Number generation in Python


Python has inbuilt function for random number generation as
random.randint (lower limit, upper limit)
ex:-num=random.randint(10,50)
It will generate random values for num from 10 to 50 (including 10 and
50).

for i in range(1,10): To generate 10 random


num=random.randint(10,50) numbers from10 to 50.
print(num)

Q:-WAP in Python to find smallest among 3 integers.


import math
smallest=math.inf
for i in range(1,4):
num1=int(input("Enter Number"))
if i==1:
smallest=num1
elif num1<smallest:
smallest=num1
print("Smallest Nu. is",smallest)

Q:-WAP in Python to find greatest among 3 integers.


import math
largest=-math.inf
for i in range(1,4):
num1=int(input("Enter Number"))
if i==0:
largest=num1
elif num1>largest:
largest=num1
print("Largest Number. is",largest)
PROGRAM LOGIC DEVELOPMENT TOOLS:-
Algorithm:-An algorithm is a step by step procedure
to solve a given problem.
For Ex:- Algorithm to divide 2 no’s.
Step1:-Input first number say num1
Step2:-Input second number say num2
Step3:- Check value of num2 is equal to 0.
i) If Yes:-Display message as Numbers are not
divisible.
ii) If No:- Display message Numbers are Divisible
and Go to Step 4.
Step 4:-Divide both the numbers and store the result
into third number say div.
Step5:-Display the value of div as answer.

You can represent an algorithm of a problem by any


of the following program development tool:-
1. Flow Charts
2. Pseudo code
3. Decision Tree
Flow Charts:- A flow chart is a graphical
representation of steps of an algorithm to solve a
given problem.
Common symbols
ANSI/ISO Shape Name Description

Flowline (Arrowhead) Shows the process's order of


operation.
Terminal Indicates the beginning and ending of
a program or sub-process.

Process Represents a set of operations that


changes value, form, or location of
data
Decision Shows a conditional operation that
determines which one of the two
paths the program will take

Input/Output Indicates the process of inputting and


outputting data, as in entering data or
displaying results.
Predefined Process Shows named process which is
defined elsewhere

Document

Ex:-
PSEUDOCODE:-It is an informal way of describing the
steps of a program’s solution without using any strict
programming language syntax.
Ex:-
If students marks is greater than or equal to 33
Display “passed”
else
Display “failed”

DECISION TREES
These are the ways of presenting rules in a hierarchical
and sequential structure where based on the hierarchy
of rules, certain outcomes are predicted.
LISTS FUNCTIONS IN PYTHON
If L1= ['1','2',3,'4',5] L2=[8,’z’]
Accessing List Elements:- L1[0]=’1’…… L1[4]=5
L2[0]=8…… L2[1]=’z’
List Function Example Output
list.append(item)
L1.append(16) ['1', '2', 3, '4', 5, 16]
list.extend(list)
L1.extend(L2) ['1', '2', 3, '4', 5, 8,
'z']
list.insert(pos,elt)
L1.insert(3,’k’) ['1', '2', 3, 'k', '4', 5]
list.remove(value)
L1.remove(3) L1= ['1','2',’4’,5]
del list[index]
Or
del L1[3] L1= ['1','2',3,5]
del list[start:stop] or del L1[1:3] L1=['1', '4', 5]
or
del <list name> or del L1 No list named L1
list.clear()
L1.clear() []-Make list empty
list.pop(index)
OR
L1.pop(2) ['1', '2', '4', 5]
Or Or
List.pop() Deletes last elt. [1,2,3,4]
list.index(value)
L1.index(‘4’) 3-Gives index of specified
elt.
list.sort()
L1=[3,81,12,1] [1, 3, 12, 81]
L1.sort()
list.sort(reverse=True) L1.sort(reverse=True) [81, 12, 3, 1]
list.reverse()
L1.reverse() [ 81, 12, 3,1]
len(list) L1.Len() or len(L1) 5
max(list)
max(L1) 81
min(list)
min(L1) 1
list(seq)
l1=list(input("Ent ['1', '2', '3', '4', '5']
er List Elements"))
if input is 12345
Making copy of List
L1=[1,2,3,4,5] L2=[1,2,3,4,5]
L2=L1 L2 is alias of L1
(Both L2 and L1 shares same
memory location. Any change
in L1will also reflected in L2
and vice versa.)
Making copy of List
(independent)
L2=list(L1) L2=[1,2,3,4,5]

L1.count(value)
L1=[1,2,1,3,1,4] L1.count(1) - 3
L1.count(5) - 0

NESTED LIST
When a list contains another list as a member element.
Ex:-lst=[4,5,6,[1,2],8]
Accessing Nested List Elements:-
lst[0]=4, lst[1]=5,lst[2]=6,
lst[3]=[1,2], lst[3][0]=1, lst[3][1]=2, lst[4]=8

TUPLE FUNCTIONS IN PYTHON


If T1= ('1','2',3,'4',5,5) AND T2=(8,’z’)
Function Example Output
len(tuple)
Len(t1) 5
max(tuple)
max(t1) 5
min(tuple)
min(t1) 1
tuple.index(<value
>) T1.index(‘2’) 1
tuple.count(valu
e) T1.count(5) 2
tuple(seq)
T1=tuple(input("Ent ('1', '2', '3', '4', '5')
er List Elements"))
if input is 12345
concatenatio
n
T1+T2 ('1','2',3,'4',5,5,8,’z
’)
Repetitio
n
T2*3 (8,’z’, 8,’z’, 8,’z’)
Slicing a
tuple
T1[3:-1] (‘4’,5)
del tuple
del T1 >>>T1
NameError: name 'T1' is
not defined
Compairing
T1>T2 If 1st element of T1
Tuples
is greater it returns
true.If T1 and T2
have 1st element
equal then check
for 2nd element and
so on.

SLICING A LIST/TUPLE
forward indexing 0 1 2 3 4 5 6
Elements(L1) 23 46 12 5 67 8 29
Backward Indexing -7 -6 -5 -4 -3 -2 -1

Display elements of List L1 from start to


Seq=L1[start:stop:step
stop-1 and skipping step-1 elements in
]
between.
L1[1:5:2] [46,5]
L1[1:4] [46,12,5] (Default step is 1)
L1[::3] [23,5,29] (Default start=0 and stop=n+1)
L1[5:2:] []
L1[2:] [12, 5, 67, 8, 29] (Default stop=n and step=1)
L1[1:-2:] [46, 12, 5, 67] (Default step is 1)
L1[-1:-5:-1] or
[29, 8, 67, 5] (Backward Listing)
L1[-1:2:-1]
L1[-1::-2] [29, 67, 12, 23]
STRING MANIPULATION
Compairing Strings
The uppercase letters are considered as smaller than
lower case letters.
Python compare two strings through relational
operators using character by character comparison of
their Unicode (ASCII)values.

How to determine Unicode value of a single character


Ord(‘A’)- 65 (To return ordinal value of a character)
Chr(65)-A (It will return character equivalent of ordinal value)

Common Characters and Ordinal(Unicode/ASCII) values)

Characters Ordinal Values


‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122

String Slicing
Same as have done in Lists and Tuples
Traversing a String
It means iterations through elements of a string, one character at
a time.
name=”pawan”name
for i in name:
print(i)
Operators used in Strings

Concatenation str1=”pawan” str1+str2 will return


Operators str2=”kumar” pawan kumar
(Both operands should
be string)
Replication Operators str1=”pawan” str1*2 will return
(one argument should be string pawanpawan
and other as numeric)
Membership Operators in returns True if a “a” in “japan”- True
character or a substring “12” not in “123”-False
(in, not in) exists in a given string
and vice versa for not in.
Comparison (>,<,==,!=,<=,>=) “a”==”a” -True
Operators “a”!=”abc” -True
“abc”<”Abc” -
False
'abc'<='abc' -True
STRING FUNCTIONS AND METHODS
If str1=”compsc123” and s2=”345”
str1.capitalize() If str1=”compsc123” Compsc123
Returns copy of string with first letter
capital str1.capitalize()
Str1.find(sub,start,end) str1.find(“om”,0,10) 1
Returns lowest index in the string
where substring found first.
str1.find(“lo”,0,5) -1
str.isalnum() If str="comp 123" False(spaces or special
symbols not considered as
Returns True if the string contains
alphabets or numbers
If str=”comp” alphanumeric)

If str=”123” True
True
If str=”comp123” True
Str1.isalpha() If str="comp 123" False
Returns true if all characters in a string
are alphabets and have minimum 1
If str=”comp” True
character otherwise returns False If str=”123” False
If str=”comp123” False
Str1.isdigit() If str="comp 123" False
Returns true if all characters in a string
are digits and have minimum 1 digit
If str=”comp” False
otherwise return False If str=”123” True
If str=”comp123” False
str.islower() If str="comp 123" True
Returns True if all the characters are
lowercase. There should be at least one
If str=”123” False
alphabet else would return False If str="CO123" False
str.isupper() If str="comp 123" False
Returns True if all the characters are False
uppercase. There should be at least
If str=”123”
one alphabet else would return False If str="CO123" True
str.isupper() If str="comp 123" False
Returns True if all the characters are False
white spaces. There should be at least
If str=” ”
one character. If str=”” False
Str1.lower() If str=”Comp” comp
Returns a copy of string converted to comp
lowercase
If str=”COMP”
If str=”comp” comp
Str1.upper() If str=”Comp” COMP
Returns a copy of string converted to COMP
uppercase
If str=”COMP”
If str=”comp” COMP
str.lstrip([chars]) If str=”There”
Returns string with leading
characters(as specified) removed from
str2=” There”
left. If no argument is mention then str.lstrip(‘The’) re
remove whitespaces.
Checks from left…all possible str.lstrip(‘Te’) here
combination of the characters of the
string passed and if found any of it’s
str.lstrip(‘the’) There
combination then remove it from left. str2.lstrip() There
str.rstrip([chars]) If str=”There”
Returns string with leading
characters(as specified) removed from
str2=”There ”
right. If no argument is mention then str.rstrip(‘ere’) Th
remove whitespaces.
Checks from left…all possible str.rstrip(‘Te’) Ther
combination of the characters of the
string passed and if found any of it’s
str.rstrip(‘the’) Ther
combination then remove it from left. str2.rstrip() There
str.rstrip(“er”) Th (Removes all possible
combinatns of er)
str.rstrip(“care”) Th (Removes all possible
combinatns of re)
('I eat', 'bananas', ' all
Str.partition(str2) Ex:- day')
txt="I eat banana all
It always returns a tuple with three elts: day"
1 - everything before the "match" x=txt.partition("banana"
2 - the "match"
3 - everything after the "match"
)
print(x)
Debugging:- It refers to the process of locating the place of error,
cause of error and correcting the code accordingly.
Errors:- Error is a bug in the code which causes irregular output or
stops a program from executing.
Exception:- It is an irregular unexpected situation occurring during
execution on which programmer has no control.
Types of Error:-

Some Built In Exceptions

Exception,SystemExit,OverflowError,
FloatingPointError,ZeroDivisonError, EOFError,
KeyboardInterrupt, IndexError,IOError, ,IndentationError,
SystemExit, ValueError,TypeError, RuntimeError.
Debugging a program using Spyder IDE
Debugging of Programs using coding
import pdb
i=1
while i<=5:
pdb.set_trace() #Tracing of code starts from here
j=1
while j<i:
print('*',end=' ')
j=j+1
print()
i=i+1
Basic pdb commands
Python Function Types:
Built In Functions(Ex:-len, input())
Functions defined in In Built modules(Ex:- pow(),
sqrt())
User Defined functions

Python Modules
A module in general is independent grouping of code and
data i.e grouping of variables, definitions, statements and
functions which can be reused in other programs and may
also depend upon other modules.

Importing modules in Python


1) Importing entire module
Import math
Import math,time (Importing multiple modules)

By using such declaration you can use all defined


functions, variables etc. from math module but by
adding prefix module’s name to the imported item
name
2) Importing selected objects from a module
Ex:-
Importing single objects Importing multiple objects of
of a module a module
from math import pi from math import pi,sqrt,pow
print(pi) print(pi)
print(sqrt(25))
print(pow(2,3))
3) To Import all objects of a module
from math import *
By using such declaration you can use all defined functions,
variables etc. from math module without having to prefix
module’s name to the imported item name.

EXAMPLE 1:-

File name:- ModMain1

def label(str1):
print("----------------------------------------------")
print(str1)
print("----------------------------------------------")

File name:- ModChild1


import ModMain1
s=input("enter your school name")
ModMain1.label(s)

Output:- if string entered is kv1 adampur

enter your school name kv1Adampur


----------------------------------------------
kv1Adampur
----------------------------------------------
Example2:-

File name:- ModMain2

def RectArea(l,b):
print("Area of Rectangle is:-",l*b)

File name:- ModChild2

import ModMain2
m=int(input("enter length of rectangle"))
n=int(input("enter breadth of rectangle"))
ModMain2.RectArea(m,n)
Output:-

enter length of rectangle 2


enter breadth of rectangle 3
Area of Rectangle is:- 6

DICTIONARY FUNCTIONS
dict= {'Subject': 'Informatics Practices', 'Class': 11}
dict2={22:'RollNo',67:'Marks'}
m=dict2.get(22) To get the value of RollNo
or required dictionary item.
m=dict2[22]
k=len(dict) It is equal to the 2
number of items in the
dictionary.
m=type(dict) If variable is <class 'dict'>
dictionary,then it would
return a dictionary type.
p=dict.copy() Returns a copy of {'Subject': 'Informatics
dictionary dict Practices', 'Class': 11}
q=dict.items() dict_items([('Subject',
Returns a list of 'Informatics Practices'),
dict's(key,value) tuple ('Class', 11)])
pairs
r=dict.keys() Returns list of dictionary dict_keys(['Subject',
dict's keys 'Class'])
s=dict.values() Returns list of dictionary dict_values(['Informatics
dict's values Practices', 11])
Adds dictionary dict2's {'Subject': 'Informatics
dict.update(dict2 key-values pairs to dict Practices', 'Class': 11, 22:
) 'RollNo', 67: 'Marks'}
To delete a dictionary {67: 'Marks'}
del dict2[<key>] element for the specified
del dict2[22] key.
or Or Not found.(As dictionary
del dict2 To delete the whole is deleted).
dictionary.
Delete the particular {67: 'Marks'}
dict2.pop(<Key>) element from the
dict2.pop(22) Dictionary whose key is
mention.
It will deletes all the {}
elements of the Dictionary
dict.clear() and left only empty
Dictionary.
str=kv 1 adampur Splits the string into words Wrd
['kv', '1', 'adampur']
wrd=str.split()
Dictionary:-
It is an unordered collection of items where each item consist of a
key and a value.

In dictionary keys are immutable but corresponding values are


mutable. So, if you want to change a key then it will produce an
error.

Updating Existing Elements in a Dictionary


dictionary[<key>]=<value>
dict[‘name’]=’kamal’

Counting Frequency of Elements in a list using Dictionary


import json
str="kv 1 adampur kv 2 AFS adampur"
wrd=str.split() # Creates a list of words
dict={}
for i in wrd:
key=i
if key not in dict:
cnt=wrd.count(key)
dict[key]=cnt
print(json.dumps(dict, indent=2))
NUMBER SYSTEMS
Conversions
Similar conversion categories

Binary to Decimal a) For Integer Portion:-


Multiply by 2n and add(Moving from right to left starting
with 20)
For Decimal Portion:-
Multiply by 2-n and add(Moving from right to left starting
with 2-1)
1 Octal To Decimal a) For Integer Portion:-
Multiply by 8n and add(Moving from right to left starting
with 80)
For Decimal Portion:-
Hexa To Decimal Multiply by 8-n and add(Moving from right to left starting with
8-1)
a) For Integer Portion:-
Multiply by 16n and add(Moving from right to left starting
with 160)
For Decimal Portion:-
Multiply by 16-n and add(Moving from right to left starting
with 16-1)
2 Decimal To Binary a) For Integer Portion:-
Divide by 2 and note remainder(Write the remainder in
reverse)
Decimal to Octal For Decimal Portion:-
Multiply the fraction by 2 and note the integer portion till
fraction part ends or upto 4 steps only.(Write integer portion in
Decimal to Hexa same order).

Vice Versa for others


3 Binary to Octal a) For Integer Portion:-
Pairs of 3 while moving from right to left and add 0’s in
the beginning for any unpaired digit.
For Decimal Portion:-
Pairs of 3 while moving from left to right and add 0’s in
the end for any unpaired digit.
Binary to Hexa Vice Versa for others i.e pair of 4
4 Octal to Binary Convert each Octal digit into equivalent 3 bit binary and write
Hexa to Binary together.
Convert each Hexa digit into equivalent 4 bit binary and write
together.
5 Octal to Hexa Octal to Binary then Binary to Hexa
Hexa to Octal Hexa to Binary then Binary to Hexa.

Binary to Decimal
For Integer Portion:-
Multiply by 2n and add(Moving from right to left starting with 20)
For Decimal Portion:-
Multiply by 2-n and add(Moving from right to left starting with 2-1)

Mobile System Organization

1. Mobile are like tiny computers with lesser computing power.


2. They can handle diverse applications like
a) making/receiving calls through radio signals,
b) camera utility,
c)display audio/video/graphical content.
d) little battery based power.

Functional Components of Mobiles

1. Mobile Processor or CPU


It is responsible for receiving commands, making calculations, playing audio/video
etc. It has two sub parts:-
a) Communication Processing unit:- It is responsible for making and receiving phone
calls. It has a digital signal processor that helps it work with Radio Frequency
Transceiver(Transmitter + Receiver) and Audio Subsystem.
Radio Frequency Transceiver is responsible for connecting SIM(a kind of modem) to
the base stations through radio signals.
Audio Subsystem:-It is responsible for converting analog voice signals into digital
signals and vice versa. It can receive voice input through in built mic and can produce
audio output through in built speakers. So, it has two parts:-
ADC(Analog to Digital converter)
DAC(Digital to Analog Converter)

b) Application Processing Unit:- It is responsible for governing and controlling all


types of operations in a mobile system like connecting with other devices, saving
data, making calculations, playing audio/videos etc.
One of its subcomponent to enhance its power and performance is GPU(Graphics
processing Unit) which handles all visuals/graphics related operations.

SoC(System on a Chip)
Major components of a mobile system are integrated on a single chip called SoC.
It includes CPU, GPU, Modem, etc. It consumes less power as compare to other
alternatives.

Display Subsytem
It is responsible for providing display facilities and touch sensitive interface.

Camera Subsystem
It is responsible for providing all image related processings like image capture,
high resolution support and other image enhancements.

Mobile System Memory


Like computer, a mobile system also consist of two types of memories:-
a)RAM:- All installed app needs to get loaded in RAM for their execution. RAM is
only functional when phone is switched on.
b)ROM:- Its mobile internal storage and it is not accessible by the user to write on.
Operating system and other preinstalled Apps resides in it.

Storage:-
The external storage of a Mobile phone is called expandable storage. It is provided
by means of SD Cards. You can store your files in it.

Power management Subsystem


Battery unit is responsible for providing power to a mobile system. It also contains
auto turn on and off feature to optimize the power consumption and battery life.

SOFTWARES
It is a set of programs that governs operations of a computer system and makes
the hardware Run.

System Software:- A software that controls the internal operations of a computer and is
necessary to make a computer run is called system software.
Ex:- Operating system, Language processors

Operating System:- It is a system software which acts as an interface between a user and
the computer system.
Ex:- Windows, DoS, Linux, Unix etc.
Language Processors:- These are the system softwares which are used to convert a
source code program into machine code.
a) Assembler:-It converts an assembly language program into machine language. Ex:-
Program written in Assembly language or Low language.
b) Compiler:-It converts a high level language into machine language in one single step.
Ex:- Program written in C++ or VB or Java etc. language.
c) Interpreter:- It converts a high level language into machine language through line by
line compilation. Ex:- Program written in Python language.

Application Software:-
It is a set of programs necessary to carry out operations for a specified application.
a)Packages:-These are the general purpose software used to fulfill general requirements
of many people.For Ex:-MsWord, MsExcel, DBMS, MsPowerpoint.

b)Utilities:-These are the application programs that assist the computer by performing
housekeeping functions like scanning, cleaning virus, backing up disks etc.
For Ex:- Compression tools, Disk defragmentor, Text Editor, Backup utility, Antivirus etc.

c)Business Software:- These are the specially created software applications according to
a particular business environment. These are customized ot tailor made softwares. For
Ex:- Accounting software made for a company.

Software Libraries

It is a predefined and available to use data and programming code in the form of
functions/scripts etc. that can be used in the development of new software programs and
applications. For Ex:- Panda library in python used for Data base applications.

Representing Unsigned integers in Binary


Unsigned integer can be either a positive number or zero but can never be negative.
So, they are represented by storing their equivalent binary code through n bits, where n
can be 8 or 16 or 32 or 64.
Using 8 bits we can represent values between 0 to 28-1 ie 0 to 255.
Similarly for 16 bits we can represent values between 0 to 2 16-1 ie 0 to 65535.
Binary Addition
X Y Z Sum Carry
0 0 0 0 0
0 1 0 1 0
1 0 0 1 0
1 1 0 0 1
1 1 1 1 1

Representing Characters in Binary

A computer should also be able to handle or recognize alphanumeric codes. It includes 26


uppercase alphabets, 26 lowercase alphabets, 10 numeric digits, 7 Punctuation marks
and nearly 20 to 40 other characters like special symbols i.e all characters present on a
keyboard.
So, to represent alphanumeric codes, we can use following codings:-

ASCII(American Standard code for information Interchange)


It is a 7 bit code. So it can represent 27=128 characters ie 0 to 127.
For Ex:-
ASCII values of Common Characters

Characters ASCII Values


‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122
ISCII (Indian Standard Code for Information Interchange)
It is 8 bit code. So, it can represent 28=256 characters i.e 0 to 255. It retains all ASCII
characters and allow coding for indian scripts like Devnagri, Gurumukhi, Oriya, Bengali,
Assamese etc. also.

Unicode:-
Unicode provides a unique number for every character, no matter what the platform, no
matter what the program, no matter what the language.

It has been adopted by all modern software providers and now allows data to be
transported through many different platforms, devices and applications without
corruption.
It is a superset of all other character sets and encode majority of known languages. Most
importantly it encodes different characters of different languages with the same
encoding scheme unlike previous encodings in which no single encoding is capable of
representing all languages.
Unicode Encoding Schemes
Unicode represents characters with multiple encoding systems like UTF-8, UTF-16 and
UTF-32.
UTF-8(Unicode Transformation Format)-8
It uses code Unit of 8 bits called an octet. It can use 1 to maximum 6 octets to represents
code points depending on their size. Although it uses 4 octets till date to represent any
character.
How would one know that whether 16 bits or 2 octets are representing single two byte
character or two one byte characters?

Unicode Code Unicode Code Points Numbers of Octets Used


Points(In Decimal) (In HexaDecimal)
0-127 U+00 to U+07 1 Octet or 8 Bits
128-2047 U+80 to U+7FF 2 Octet or 16 Bits
2048-65535 U+800 to U+07 3 Octet or 24 Bits
65536-2097151 U+00 to U+07 4 Octet or 32 Bits
a) UTF-8 (1 Octet) 8 bits representation
It uses left most bit as control bit which stores control code 0 and so, rest of the 7 bits can
store 27 =128 values
0
For Ex:- we can represent Letter ‘B’ having Binary
1000010 as 0 1 0 0 0 0 1 0
Value storage starts from right most bit and left most bits
will carry 0 if doesn’t have any value. For Ex:- to store value 5 (Binary 101)
0 in the first bit indicates 1 Byte encoding. 0 0 0 0 0 1 0 1
b) UTF-8 (2 Octet)- 16 Bit Representation

For 2 Byte or 2 Octet or 16 Bit representation, UTF-8 uses


a) Left most 3 bits of first octet as control code 110
b) Left most 3 bits of second octet as control code 10

1 1 0 1 0

5 BITS+6 BITS=11 BITS are free for storing actual data

110 in the Leftmost 3 bits of first byte and 10 in the Leftmost 2 bits of second byte
indicate 2 Byte encoding.
Value storage starts from right most bit and left most bits will carry 0 if doesn’t
have any value. For Ex:- to store value 130 (Binary 10000010).We can

1 1 0 0 0 0 1 0 1 0 0 0 0 0 1 0

c) UTF-8 (3 Octet)- 24 Bit Representation


For 3 Byte or 3 Octet or 24 Bit representation, UTF-8 uses

a) Left most 4 bits of first octet as control code 1110


b) Left most 2 bits of second octet as control code 10
c) Left most 2 bits of third octet as control code 10

1 1 1 0 1 0 1 0

4+6+6 BITS=16 BITS for actual data is free


Value storage starts from right most bit and left most bits will carry 0 if doesn’t
have any value. For Ex:- to store value 2050 i.e 2048+2 (Binary 10000000000100)
1 1 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0

d) UTF-8 (4 Octet)- 32 Bit Representation


For 4 Byte or 4 Octet or 32 Bit representation, UTF-8 uses

a) Left most 5 bits of first octet as control code 11110


b) Left most 2 bits of the next three octet as control code 10

1 1 1 1 0 1 0 1 0 1 0

3+6+6+6 BITS=21 BITS for actual data is free


Value storage starts from right most bit and left most bits will carry 0 if doesn’t have
any value. For Ex:- to store value 65540 i.e 65536+4 (Binary 1000000000000000001)

1 1 1 1 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0

UTF-8 is the most popular encoding scheme and more than 90% websites are using it.

UTF-32

It is a multi-byte encoding that represents each character with 4 bytes


*Makes it space inefficient

It is a fixed length encoding scheme that uses exactly 4bytes to represent all Unicode
code points. E.g. to store value 36(Binary Code:-00100100)

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0
PROGRAM EXECUTION
This topic explains the process of converting Program code into computer
understandable code i.e machine code.
Source code:- It refers to the original code written in a programming language by the
programmer. Ex:-.cpp file in C++, .py file in python etc.
Machine code:- It refers to the code converted into computer understandable form
that a computer can understand and can directly execute.
Translators or Translation Softwares:- Compiler, Interpreter.

STEPS OF TRANSLATION PROCESS


A. COMPILATION PROCESS:-
It further involves following sub processes:-
1. Preprocessing:-It removes all comments from source code and adds all that is to
be added/expanded like preprocessor directives(header files, macros in C++) to
make the code ready for next phase.

2. Compilation:-
i) Analysis(Front End phase):-It identifies all the tokens in the source code
and creates a symbol table with it.
ii) Synthesis Phase(Back End Phase):-It parses the source code and
generates syntax tree out of it i.e the order of execution of the expression.

These steps are repeated until all the errors (Syntax and Semantics) are
removed from the source code. Once the errors are removed, the compiler
converts the source code into intermediate code which are Assembly
language instructions.

3. Assembly Phase:-It converts theAssembly level instructions into object code,


which is a form of machine code.It does works of a assembler i.e converts
assembly code into machine code.

4. Linking:-This step performs the linking of libraries, resolves all memory


references and code is converted into a form which further requires nothing to
execute i.e the code becomes executable now(.exe file)

5. Loader:-It loads the .exe file created above into memory for execution.

B. INTERPRETATION PROCESS:-
It translates a single line at a time, makes it executable and runs immediately. It
means that interpreter follows the process of compiler for each line of code and
then moves to process the next line.
It requires less amount of memory then compiler as only a single line of code is
executed at a time. However unlike compilerit is required always in memory to
run the code.
Also, a compiler generates intermediate object code of the whole program
whereas interpreter does not generate any intermediate object code.

Once a compiler compiles the program successfully, it is not required for running
the code again and again(if no changes are made to the code), however
interpreter is required always.

PROCESS:-whenever a program runs it has to be loaded in RAM first and then it is


executed by the CPU. So, the program under execution is called a PROCESS.

ROLE OF AN OPERATING SYSTEM IN RUNNING A PROGRAM

OS as a Resource Manager
As a computer may have multiple processes to run upon, so management of
resources including RAM, secondary memory devices, Input/Output devices etc. is
required so that they can be used efficiently. This work is performed by the
Operating System.

Performance of a CPU
It is measured through “Throughput”which is calculated as
Throughput=No. of Jobs completed/Time Taken

1. PROCESS MANAGEMENT:-
A program have different states. These are:-

Start State:-Initial state of a program when a program is first loaded into the
memory to make it a process.

Ready State:-When after loading into memory a process is ready to be executed by


the CPU.

Waiting State:-If during execution, the has to wait for some resource like waiting
for user input, or waiting for any resource(printer etc.) to be available, then the CPU
takes up the next process and the current process state becomes waiting state.

Terminated or Exit State:-Once all the instructions of a process get successfully


executed, the state of the process changed to terminated state.

Steps of Program Execution by CPU


1. Program is loaded in main memory.
2. Control Unit fetches the first instruction of the program
3. CU determines the type of instruction by decoding it ie
a) Mathematical work
b) Logical work
c) Simple from input/output devices
d) Write to memory or output devices.
4. Based on kind of instruction, CU either instructs ALU or execute the instructions.
5. ALU produces some results, which are thenstored in the main memory.
6. For the next instruction in the program, again steps 2 to 4 are carried out.
The fetch-decode-execute cycle is also known as instruction cycle.
2. PROCESS SCHEDULING
In order to execute multiple programs by the CPU, proper management of these
ready or waiting processes is needed. It could be achieved through scheduling.
Some of these are:-
a)FCFS(First come first Serve):-Process entering first in the queue gets CPU first.
b)Round Robin Scheduling:-Every process gets CPU for fixed amount of time
called time slice on rotation basis and the
c)Shortest Job Next:-CPU picks the next job that will take shortest time out of all
ready processes.

3. MEMORY MANAGEMENT
The OS needs to check how much memory is to be allocated to processes and
how it is to be allocated. Keep track of and keep updating freed or unallocated
memory etc.
The memory manager part of OS allocate memory to different processes using
different techniques such as:-
a) Single memory allocation:-In it the available free memory is allocated to
single application at a time.
b) Partitioned Allocation:-In this technique, primary memory is divided into
contiguous are of memory called partitions. A running application is allocated
one or more partitions depending upon its requirement.
c) Paged Memory management:-In it, primary memory is divided into fixed size
units called pages. A running application is allocated one or more pages
depending upon its requirement.
d) Segment memory management:-In it, memory is divided into logical units
called segment. Segments may not be contiguous in physical memory but
logically different chunks of memory may belong to one segment.A running
application is allocated some segments depending upon its requirement.

4. I/O MANAGEMENT
Whenever a process requires some I/O, the OS sends I/O request to the physical
device and passes the received response back to the process.

PARALLEL COMPUTING
It refers to the simultaneous working of multiple processors to solve a
computational problem.
A parallel computing may be achieved through :-
a) A single computer with multiple processors
b) Multiple computers connected by a network.
Advantages of parallel computing
1. It saves time and cost too.
2. Provides efficient use of hardware.
3. May utilize remotely available resources.
4. It may solve large and complex problems easily.

CLOUD COMPUTING(Storage space over internet)


It refers to storing and accessing data and programs over the internet insteadof computer’s
hard drive.
There are two types of clouds:-
a) Public cloud:-In it, all hardware, software is owned and managed by the cloud
provider and shared by all cloud subscribers. Ex:- Google Drive.
b) Private Cloud:-In it, computing resources used exclusively by a business or
organization. Services are maintained on a private network and the hardware ,
software are dedicated solely to one organization.
NOSQL DATABSE (Not Only SQL)

Non relational databases are the unstructured databases where arrangements of the records in the
database can be in any undefined manner.These are termed as NoSQL databases.

Non relation databases are more suitable to manage huge or big data for business organizations.One such
non-relational DBMS is MongoDB.

MongoDB

1. It is a cross platform(Platform independent), simple document-oriented NOSQL database.


2. It provides high performance, high availability and easy scalability.
3. It is used for high volume data storage. For Ex:-Banking applications, Facebook login accounts etc.
4. It is an open source product, developed using C++ by Eliot Storing and Dwight Merriman in 2007.

JSON(JavaScript Object Notation) :-It is an open, human and machine readable standard that facilitates
data interchange on the web.
MongoDB uses JSON documents in order to store documents like table uses rows to store records in
RDBMS.

Features of MongoDB

Document Oriented storage:- Data is stored in the form of JSON style documents.

High Speed & Performance:- It is so because it uses internal memory for storing the working data set, thus
fast access.

High availability:- It is due to replication facility in MongoDB.

Auto Sharing:-

Rich Query Language:- To do all major read/write operations(CRUD).

CRUD Stands for Create, Retrieve, Update, Delete operations.

MongoDB Components:-

Database:-It is a physical container for collections(like tables). A single MongoDB server has multiple
databases.

Collection:-It is a group of MongoDB documents. It is equivalent to RDBMS tables. All documents in a


collection are of similar purpose.

Document:-It is a set of key-value pairs. Documents have dynamic scheme i.e different documents in a
collection may have different set of fields, structure and also common fields in a collection’s documents
may hold different types of data.

For Ex:- a student document may have following data:-


{
Stud_id:”abc123”,
Age:-25,
grade:’A’
}

Comparison between MongoDB and RDBMS

RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
Column Field
Table Join Embedded Documents
Primary Key Primary Key(Provided by default in

MongoDB)
Database schema

It is the structure that represents the logical view of the entire database.It defines how the data is
organized and how the relation among them are associated. It defines table ,views and integrity constraints
in RDBMS.

Advantages of MongoDB

1. It is schema less, so it is flexible enough as number of fields content and size of the document may
differ from one to another.
2. Unlike SQL, no complex Joins are there.
3. It is very easy to scale.
4. It is easy to use.
5. It uses internal memory for storing working sets;so it accesses data very fast.
6. It is lightweight so occupies less memory.
7. It is much faster than RDBMS.

Some common problems that comes during MongoDB installation on windows 7 32 bit.

Common Error1:-the default storage engine 'wiredtiger' is not available

Solution Type the following command in the MongoDB path upto bin as
mongod.exe --storageEngine=mmapv1

Common Error2:- hotfix kb2731284 or later update is not installed


Solution:-just create a folder structure in your C catalog like this one: C:\data\db.

COMMANDS IN MongoDB

To create database

use<databasename> Ex:- use school

To Create Table

db.createCollection(‘tablename’) Ex:-db.createCollection(‘student’)

*Note:-Although you need not to create collection explicitly as MongoDB creates collection
automatically when you insert the data using insert or insert many command.

To Insert Record
db.student.insert({“RollNo”:1,”class”:”8A”,”Marks”:90})

db.student.insert({“RollNo”:7,”class”:”11A”,”Marks”:94,”Age”:11})

You can also have different no. of columns in different insert query.For Ex:-

db.student.insert({“RollNo”:7,”class”:”11A”,”Marks”:94,”Age”:11}) ----Here 4 columns are used.

To Display Record
db.student.find():- To list all records of the student table.

Ex:-

To Update Records:-

db.student.update({‘RollNo’:1},{$set:{“CLASS”:”9C”}})

To Delete Records i.e removing JSON document:-

db.student.remove({“class”:”11A”})

Steps to install MongoDB on windows 32 bit

Install mongoDB 3.2 and either install complete variant (Path will be C:\Program Files\Server\
3.2\bin\)
or
Select custom variant and you can select easy accessible path C:\MongoDB\

Now go to command prompt by cmd-> now depending upon your python path go to that path
through cd C:\MongoDB\bin\

Type command (if on executing mongod command error comes as:-


“the default storage engine 'wiredtiger' is not available)”

mongod.exe --storageEngine=mmapv1

Now without closing this window open another cmd window and once again goto MongoDB path as
cd C:\MongoDB\bin\
and type command as cd C:\MongoDB\bin\mongod
and then as cd C:\MongoDB\bin\mongo
you will get prompt as >
and now you can start typing your commands.

STATE AND TRANSITION

STATE:- A state is one of the internal configuration of a hardware/software which is caused by some
external inputs or some internal actions.

Transition:- A Transition is a marked change from one state to another in response to some external
input or actions.

State Transition Diagram


It describes all the states that a computer system can undergo along with the events under which
the computation system behaves in a certain way and changes state. The change in state are
marked as transition.
DATA TYPES IN PYTHON

Numbers None Sequences Mappings


1) Integer 1)String Dictionary
** Boolean 2)Tuple
2) Floating Point 3)List
3) Complex

MUTABLE AND IMMUTABLE DATA TYPES

x=10 (20345-Memory address) x=20 (34567-Memory Address)

Mutability means that you can store new value at the same memory address i.e
overwriting contents.

For immutable data type you are unable to overwrite contents but instead every
time you assign new value to an immutable data type, it simply refer to a
different memory location.
IMMUTABLE DATA TYPES MUTABLE DATA TYPES
 Integers  List
 Boolean  Dictionary
 Floating Point Numbers  Set
 Strings
 Tuples
For Ex:- As string is immutable data type, So

If name=”welcome”

Then name[1]=’k’ generates error i.e not allowed.

However, name=”hello” is permissible because in that case the variable name is


now pointing towards, a completely different string.

String Data Type


String is taken as a sequence of characters in which individual characters are stored in
contiguous location. So, Every character has a unique index value.

Str=”PYTHON”

STR[0]=P STR[1]=Y STR[2]=T STR[5]=N or STR[-1]=N

Forward
0 1 2 3 4 5 6
indexing
P Y T H O N \0
Backwar
d -6 -5 -4 -3 -2 -1 0
indexing

List In Python Tuple In Python


List are collections of items and each List and tuple,both are same except,a list is
mutable python object and tuple is immutable
item has its own index value.They are Python objects i.e you cannot overwrite
mutable ie values within a List can be values within a tuple.
over write.

e.g. of tuple [Using round braces ( ) ]


e.g.of list Using rectangular braces [] tup=(66,99,”sumit”,56.78,”h”)
list=[6,9,23,”PARAM”,23.89,”k”]
list[0]=55 #first value of list is replaced tup[0]=3 # error message will be displayed
print(list[0])
print(list[1]) print(tup[0])
print(tup[1])
OUTPUT print(tup[3]) 56.78
55 OUTPUT
9 66
99

Dictionary In Python
It is an unordered set of comma separated
Key:Value pairs, within { } with the condition
that within a dictionary, no two keys can be
the same.

Eg.Using Dictionary[Using curly braces { } ]


Dict={‘a’:1,’e’:2,’i’:3}
Here ‘a’,’e’,’i’ are the keys of dictionary dict
having 1,2,3 as respective values.
So, Dict[‘a’] --will give 1
Dict[‘i’] - will give 3

You might also like