Você está na página 1de 259

Chapter 1 :

Informatics
Practices
Class XI ( As per Computer
CBSE Board) System
Overview
New
Syllabus
2018-19

Visit : python.mykvs.in for regular updates


Introduction
A computer is an electronic device, under the control of instructions
stored in its memory that can accept data (input), process the data
according to specified rules(Program), produce information (output),
and store the information for future use

Data vs Information
Data are raw numbers or other findings which, by themselves, are
of limited value.
Information is data that has been converted into a meaningful and
useful context.

Computers are being used extensively nowadays in everyday life/every field


In the form of laptop, desktop, smartphone,gadgets etc.

Visit : python.mykvs.in for regular updates


Functionalities of a computer
Any digital computer performs five functions in gross term.

1. Take data as input


2. Stores data/instructions
3. Process those stored data
4. Generate the output
5. Control all above steps

Visit : python.mykvs.in for regular updates


Basic Computer Organization
Functional components of a computer

Visit : python.mykvs.in for regular updates


Basic Computer Organization
Input/Output Units
Input Unit
A device through which data and programs from the
outside world enter the computer system.
Suggest –any 3 name of input devices.
Output unit
A device through which results stored in the computer
memory are made available outside the computer
system.
Suggest –any 3 name of output devices.

Visit : python.mykvs.in for regular updates


Basic Computer Organization
Control Unit
Control unit
It organizes the computer to work computer as single unit
Arithmetic/Logic Unit
Performs basic arithmetic operations such as addition and subtraction
Performs logical operations such as AND, OR, and NOT.Most modern ALUs
have a small amount of special storage units called registers that can be
accessed faster than main memory.
Memory
A collection of cells, each with a unique physical address
Most computers are byte-addressable
Cell at address 11111110 contains 10101010

Visit : python.mykvs.in for regular updates


Basic Computer Organization
Memory Units

Visit : python.mykvs.in for regular updates


Basic Computer Organization
RAM and ROM
Random Access Memory (RAM)
Memory in which each location can be accessed and changed
Read Only Memory (ROM)
Memory in which each location can be accessed but not changed
RAM is volatile, ROM is not

Secondary Storage Devices


Magnetic Tape
mass auxiliary storage device

Visit : python.mykvs.in for regular updates


Basic Computer Organization
Secondary Storage Devices
Hard disk
Fixed Head HDD / Movable head HDD

A hard disk is a set of stacked disks. Each disk has data recorded
electromagnetically in concentric circles, or tracks, on the disk
Hard Drive Types
1. Parallel Advanced Technology Attachment (PATA)
2. Serial ATA (SATA)
3. Small Computer System Interface (SCSI)
4. Solid State Drives (SSD)

Upto 12 TB sized HDD is available in the market

Visit : python.mykvs.in for regular updates


Basic Computer Organization
Mobile System
a Mobile Phone is essentially a two-way radio, consisting of
a radio transmitter and a radio receiver.

Visit : python.mykvs.in for regular updates


Basic Computer Organization
Mobile Phone Components
1. A circuit board as brains of the phone
2. An antenna
3. A liquid crystal display (LCD)
4. A keyboard / A touch screen
5. A microphone
6. A speaker
7. A battery

Visit : python.mykvs.in for regular updates


Basic Computer Organization
Different types of touchscreen
1.TFT (Thin Film Transistor) LCD display is used for better image quality and high
resolution. Since they are cheap to manufacture, they are found in budget phones
usually.

2. IPS (In-Place Switching) LCDs are somewhat the advanced version of TFT LCDs in
a way that they offer improved displays and are more battery friendly. Hence, they are
found in high end phones.

3. RESISTIVE AND CAPACITIVE


There are generally two types of touchscreen LCD displays; Resistive and Capacitive.
Resistive touchscreen has two layers of conductive material with a small gap
between them while capacitive touchscreen consists of a layer of glass coated with
transparent conductor. Capacitive screens tend to be more responsive than resistive
screens and are therefore found in high end phones mostly.

4.OLED (Organic Light Emitting Diode) is a newer technology used in mobiles and
monitors for display. They are better than LCDs because they offer fast response
times, wider viewing angles and higher brightness. AMOLED (Active-Matrix Organic
Light-Emitting Diode) and SUPER AMOLED displays are types of OLED display.
OLED types include passive-matrix OLEDs, active-matrix LEDs and transparent OLEDs

Visit : python.mykvs.in for regular updates


Basic Computer Organization
Smartphone Batteries and Their Types
Battery plays a huge role in any smartphone
Lithium Polymer batteries are the most advanced batteries available in the market right
now. They are made up of plastic instead of metal, which makes them usable on a
smartphone of any type.The Lithium Polymer batteries do not suffer from memory effect and
offer 40 percent more battery life than others

Lithium ion batteries are advanced and allow for a high charge capacity based on the size
and weight of the battery. However, these these are slightly expensive. these lithium ion
batteries will not remember the charge cycle, and as a result, the battery capacity will not be
reduced.

Nickel Cadmium These are the cells that suffer from memory effect. And, the memory
effect will result in reducing the capacity of the battery and its lifespan as well.

Nickel Metal Hydride batteries are kind of an upgrade to the Nickel Cadmium batteries,
and they boast of the same size as the latter. Nickel Metal Hydride batteries offer 30 to 40
percent more battery juice than the others

Battery Size : Measured in mAh.like 2000 mAh,4000 mAh etc.

Visit : python.mykvs.in for regular updates


Basic Computer Organization
DEVELOPMENT OF COMPUTER
Abacus is known to be the first mechanical calculating device. Which was used to
be performed addition and subtraction easily and speedily? This device was a first
develop Ed by the Egyptians in the 10th centaury B.C, but it was given it final
shape in the 12th centaury A.D. by the Chinese educationists.
NAPIER’S BONES John Napier’s of Scotland invented a calculating device, in the
year 1617 called the Napier Bones. In the device, Napier’s used the bone rods of
the counting purpose where some no. is printed on these rods. These rods that
one can do addition, subtraction, multiplication and division easily.
Pascal's calculator In the year 1642, Blaise Pascal a French scientist invented an
adding machine called Pascal’s calculator, which represents the position of digit
with the help of gears in it.
Leibnz Calculator In the year 1671, a German mathematics, Gottfried Leibniz
modified the Pascal calculator and he developed a machine which could perform
various calculation based on multiplication and division as well.
Analytical EngineIn the year 1833, a scientist form England knows to be Charles
Babbage invented such a machine. Which could keep our data safely? This
device was the first mechanical computer. Charles Babbage is also known as the
father of the computer.

Visit : python.mykvs.in for regular updates


Basic Computer Organization
GENERATION OF COMPUTER

Visit : python.mykvs.in for regular updates


Chapter 2 :

Informatics
Practices Getting
Class XI ( As per
CBSE Board)
Started
With
Python

Visit : python.mykvs.in for regular updates


Introduction
It is widely used general purpose,high level programming
language.Developed by Guido van Rossum in 1991.

It is used for:
software development,
web development (server-side),
system scripting,
Mathematics.

Visit : python.mykvs.in for regular updates


Features of Python

1. Easy to use – Due to simple syntax rule


2. Interpreted language – Code execution &
interpretation line by line
3. Cross-platform language – It can run on
windows,linux,macinetosh etc. equally
4. Expressive language – Less code to be written
as it itself express the purpose of the code.
5. Completeness – Support wide rage of library
6. Free & Open Source – Can be downloaded
freely and source code can be modify for
improvement
Visit : python.mykvs.in for regular updates
Shortcomings of Python

1. Lesser libraries – as compared to other


programming languages like c++,java,.net
2. Slow language – as it is interpreted languages,it
executes the program slowly.
3. Weak on Type-binding – It not pin point on use
of a single variable for different data type.

Visit : python.mykvs.in for regular updates


Installing Python

Two Steps Only –

1. Download Python distribution


2. Python installation process

Visit : python.mykvs.in for regular updates


Installing Python
1. Download Python distribution
You can download python distribution from the link given below
https://www.python.org/downloads/

Note – Download only that python distribution/MSI Installer, which is best


suited for the Operating system on which you want to install it.
Visit : python.mykvs.in for regular updates
Installing Python
2. Python installation process
1. Double-click the icon labeling the file <version>.exe
Popup window will appear

Click on Run option

Visit : python.mykvs.in for regular updates


Installing Python
2. Setup popup window will appear

If the Python Installer finds an earlier version of Python installed on your


computer, the Install Now message will instead appear as Upgrade Now(and
the checkboxes will not appear).
Highlight the Install Now (or Upgrade Now) message, and then click it

Visit : python.mykvs.in for regular updates


Installing Python

3. User Account Conrol pop-up window will appear

Click the Yes button.

Visit : python.mykvs.in for regular updates


Installing Python

4. A new Python <version> Setup pop-up window will appear with a Setup
Progress message and a progress bar.

Visit : python.mykvs.in for regular updates


Installing Python

5. Soon, a new Python <version> Setup pop-up window will appear with
a Setup was successfully message

Click the close button

Visit : python.mykvs.in for regular updates


How to work in Python

After installation of python ,we can work on it in following ways

(i) in Interactive mode


(ii) in Script mode

Visit : python.mykvs.in for regular updates


How to work in Python

(i) in Interactive mode


* Search the python.exe file in the drive in
which it is installed.
If found double click it to start python in
interactive mode

Visit : python.mykvs.in for regular updates


How to work in Python
* Click start button -> All programs
->
python<version>->IDLE(Python GUI)

Visit : python.mykvs.in for regular updates


How to work in Python
Python command
prompt >>>

Type the following at prompt


print “hello”
print 8*3
print 3**3
k=3+4*3
print k

Visit : python.mykvs.in for regular updates


How to work in Python

(ii) in Script mode


Step 1 (Create program file)
Below steps are for simple hello world program
a. Click Start button->All Programs ->
Python<version>->IDLE
b. Now click File->New in IDLE Python Shell
Now type
print “hello”
print “world”
print “python is”,”object oriented programming lang.”
c. Click File->Save and then save the file with
filename and .py extension
Visit : python.mykvs.in for regular updates
How to work in Python

(ii) in Script mode


Step 2 (Run program file)
a. Click Open command from IDLE’s File menu and
select the file you have already saved
b. Click Run-> Run Module
c. It will execute all the commands of program file
and display output in separate python shell
window
Note :- Python comes in 2 flavours – python 2.x and python 3.x . Later
one is Backward incompatible language as decide by Python Software
foundation(PSF). Mean code written in 2.x will not execute on 3.x . Visit
the below link for difference between 2.x & 3.x
https://www.geeksforgeeks.org/important-differences-between-python-
2-x-and-python-3-x-with-examples/

Visit : python.mykvs.in for regular updates


Chapter 3 :

Informatics
Practices
Class XI ( As per
Python
CBSE Board)
Fundamentals

Visit : python.mykvs.in for regular updates


Introduction
Python 3.0 was released in 2008. Although this version is
supposed to be backward incompatibles, later on many of its
important features have been back ported to be compatible
with version 2.7
Python Character Set
A set of valid characters recognized by python. Python uses the traditional
ASCII character set. The latest version recognizes the Unicode character set.
The ASCII character set is a subset of the Unicode character set
Letters :– A-Z,a-z
Digits :– 0-9
Special symbols :– Special symbol available over keyboard
White spaces:– blank space,tab,carriage return,new line, form feed
Other characters:- Unicode

Visit : python.mykvs.in for regular updates


Input and Output
var1=‘Computer Science'
var2=‘Informatics Practices'
print(var1,' and ',var2,' )
Output :-
Computer Science and Informatics Practices

raw_input() Function In Python allows a user to give input to a program


from a keyboard but in the form of string.
NOTE : raw_input() function is deprecated in python 3
e.g.
age = int(raw_input(‘enter your age’))
percentage = float(raw_input(‘enter percentage’))
input() Function In Python allows a user to give input to a program from a
keyboard but returns the value accordingly.
e.g.
age = int(input(‘enter your age’))
C = age+2 #will not produce any error
NOTE : input() function always enter string value in python 3.so on
need int(),float() function can be used for data conversion.
Visit : python.mykvs.in for regular updates
Token

Smallest individual unit in a program is known as token.


1. Keywords
2. Identifiers
3. Literals
4. Operators
5. punctuators

Visit : python.mykvs.in for regular updates


Keywords
Reserve word of the compiler/interpreter which can’t be
used as identifier.

and exec not

as finally or

assert for pass

break from print

class global raise

continue if return

def import try

del in while

elif is with

else lambda yield

except

Visit : python.mykvs.in for regular updates


Identifiers
A Python identifier is a name used to identify a variable,
function, class, module or other object.
* An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores
and digits (0 to 9).
* Python does not allow special characters
* Identifier must not be a keyword of Python.
* Python is a case sensitive programming language.
Thus, Rollnumber and rollnumber are two different identifiers
in Python.
Some valid identifiers : Mybook, file123, z2td, date_2, _no
Some invalid identifier : 2rno,break,my.book,data-cs

Visit : python.mykvs.in for regular updates


Identifiers-continue
Some additional naming conventions
1. Class names start with an uppercase letter. All other
identifiers start with a lowercase letter.

2. Starting an identifier with a single leading underscore


indicates that the identifier is private.

3. Starting an identifier with two leading underscores


indicates a strong private identifier.

4. If the identifier also ends with two trailing


underscores, the identifier is a language-defined
special name.

Visit : python.mykvs.in for regular updates


Literals
Literals in Python can be defined as number, text, or
other data that represent values to be stored in variables.

Example of String Literals in Python


name = ‘Johni’ , fname =“johny”

Example of Integer Literals in Python(numeric literal)


age = 22

Example of Float Literals in Python(numeric literal)


height = 6.2

Example of Special Literals in Python


name = None
Visit : python.mykvs.in for regular updates
Literals
Escape sequence
Escape Sequence Description

\\ Backslash (\)

\' Single quote (')

\" Double quote (")

\a ASCII Bell (BEL)

\b ASCII Backspace (BS)

\f ASCII Formfeed (FF)

\n ASCII Linefeed (LF)

\r ASCII Carriage Return (CR)

\t ASCII Horizontal Tab (TAB)

\v ASCII Vertical Tab (VT)

\ooo Character with octal value ooo

\xhh Character with hex value hh

Visit : python.mykvs.in for regular updates


Operators
Operators can be defined as symbols that are used to perform
operations on operands.

Types of Operators

1. Arithmetic Operators.
2. Relational Operators.
3. Assignment Operators.
4. Logical Operators.
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

Visit : python.mykvs.in for regular updates


Operators continue
1. Arithmetic Operators
Arithmetic Operators are used to perform arithmetic operations like
addition, multiplication, division etc.
Operators Description Example

+ perform addition of two number a+b

- perform subtraction of two number a-b

/ perform division of two number a/b

* perform multiplication of two number a*b

% Modulus = returns remainder a%b

Floor Division = remove digits after the


// a//b
decimal point

** Exponent = perform raise to power a**b

Visit : python.mykvs.in for regular updates


Operators continue
2. Relational Operators
Relational Operators are used to compare the values.

Operators Description Example

== Equal to, return true if a equals to b a == b

!= Not equal, return true if a is not equals to b a != b

Greater than, return true if a is greater than


> a>b
b

Greater than or equal to , return true if a is


>= a >= b
greater than b or a is equals to b

< Less than, return true if a is less than b a<b

Less than or equal to , return true if a is


<= a <= b
less than b or a is equals to b

Visit : python.mykvs.in for regular updates


Operators continue
3. Assignment Operators
Used to assign values to the variables.
Operators Description Example

= Assigns values from right side operands to left side operand a=b

+= Add 2 numbers and assigns the result to left operand. a+=b

/= Divides 2 numbers and assigns the result to left operand. a/=b

*= Multiply 2 numbers and assigns the result to left operand. A*=b

-= Subtracts 2 numbers and assigns the result to left operand. A-=b

%= modulus 2 numbers and assigns the result to left operand. a%=b

//= Perform floor division on 2 numbers and assigns the result to left operand. a//=b

**= calculate power on operators and assigns the result to left operand. a**=b

Visit : python.mykvs.in for regular updates


Operators continue
4. Logical Operators
Logical Operators are used to perform logical operations on the
given two variables or values.

Operators Description Example

and return true if both condition are true x and y

or return true if either or both condition are true x or y

not reverse the condition not(a>b)

a=30
b=20
if(a==30 and b==20):
print('hello')

Output :-
hello

Visit : python.mykvs.in for regular updates


Operators continue
6. Membership Operators
The membership operators in Python are used to validate whether a
value is found within a sequence such as such as strings, lists, or
tuples.
Operators Description Example

in return true if value exists in the sequence, else false. a in list

not in return true if value does not exists in the sequence, else false. a not in list

E.g.
a = 22
list = [22,99,27,31]
In_Ans = a in list
NotIn_Ans = a not in list
print(In_Ans)
print(NotIn_Ans)
Output :-
True
False
Visit : python.mykvs.in for regular updates
Operators continue
7. Identity Operators
Identity operators in Python compare the memory locations of two objects.
Operators Description Example

is returns true if two variables point the same object, else false a is b

is not returns true if two variables point the different object, else false a is not b
e.g.
a = 34
b=34
if (a is b):
print('both a and b has same identity')
else:
print('a and b has different identity')
b=99
if (a is b):
print('both a and b has same identity')
else:
print('a and b has different identity')
Output :-
both a and b has same identity
a and b has different identity
Visit : python.mykvs.in for regular updates
Punctuators
Used to implement the grammatical and structure of a Syntax.Following
are the python punctuators.

Visit : python.mykvs.in for regular updates


Barebone of a python program
#function definition comment
def keyArgFunc(empname, emprole):
print ("Emp Name: ", empname) Function
print ("Emp Role: ", emprole) indentation
return;
A = 20 expression
print("Calling in proper sequence")
keyArgFunc(empname = "Nick",emprole = "Manager" )
print("Calling in opposite sequence") statements
keyArgFunc(emprole = "Manager",empname = "Nick")

A python program contain the following components


a. Expression
b. Statement
c. Comments
d. Function
e. Block &n indentation

Visit : python.mykvs.in for regular updates


Barebone of a python program
a. Expression : - which is evaluated and produce result. E.g. (20 + 4) / 4
b. Statement :- instruction that does something.
e.g
a = 20
print("Calling in proper sequence")
c. Comments : which is readable for programmer but ignored by python
interpreter
i. Single line comment: Which begins with # sign.
ii. Multi line comment (docstring): either write multiple line beginning with #
sign or use triple quoted multiple line. E.g.
‘’’this is my
first
python multiline comment
‘’’
d. Function
a code that has some name and it can be reused.e.g. keyArgFunc in
above program
d. Block & indentation : group of statements is block.indentation at same
level create a block.e.g. all 3 statement of keyArgFunc function
Visit : python.mykvs.in for regular updates
Variables
Variable is a name given to a memory location. A variable can consider as a
container which holds value. Python is a type infer language that means you
don't need to specify the datatype of variable.Python automatically get
variable datatype depending upon the value assigned to the variable.
Assigning Values To Variable
name = ‘python' # String Data Type
sum = None # a variable without value
a = 23 # Integer
b = 6.2 # Float
sum = a + b
print (sum)
Multiple Assignment: assign a single value to many variables
a = b = c = 1 # single value to multiple variable
a,b = 1,2 # multiple value to multiple variable
a,b = b,a # value of a and b is swaped

Visit : python.mykvs.in for regular updates


Variables
Variable Scope And Lifetime in Python Program
1. Local Variable
def fun():
x=8
print(x)

fun()
print(x) #error will be shown
2. Global Variable
x=8
def fun():
print(x) # Calling variable ‘x’ inside fun()

fun()
print(x) # Calling variable ‘x’ outside fun()

Visit : python.mykvs.in for regular updates


Dynamic typing

Data type of a variable depend/change upon the value assigned to a


variable on each next statement.
X = 25 # integer type
X = “python” # x variable data type change to string on just next line
Now programmer should be aware that not to write like this:
Y = X / 5 # error !! String cannot be devided

Visit : python.mykvs.in for regular updates


Input and Output
print() Function In Python is used to print output on the screen.
Syntax of Print Function
print(expression/variable)
e.g.
print(122)
Output :-
122

print('hello India')
Output :-
hello India

print(‘Computer',‘Science')
print(‘Computer',‘Science',sep=' & ')
print(‘Computer',‘Science',sep=' & ',end='.')
Output :-
Computer Science
Computer & Science
Computer & Science.

Visit : python.mykvs.in for regular updates


Chapter 4 :

Informatics
Practices
Class XI ( As per Data
CBSE Board)
Handling

Visit : python.mykvs.in for regular updates


Introduction
Most of the computer programming language
support data type, variables,operator and expression
like fundamentals.Python also support these.

Data Types
Data Type specifies which type of value a variable can
store. type() function is used to determine a variable's
type in Python.

Visit : python.mykvs.in for regular updates


Data type continue

Data Types In Python


1. Number
2. String
3. Boolean
4. List
5. Tuple
6. Set
7. Dictionary

Visit : python.mykvs.in for regular updates


Data type continue

1. Number In Python
It is used to store numeric values

Python has three numeric types:


1. Integers
2. Floating point numbers
3. Complex numbers.

Visit : python.mykvs.in for regular updates


Data type continue
1. Integers
Integers or int are positive or negative
numbers with no decimal point. Integers in
Python 3 are of unlimited size.
e.g.

a= 100
b= -100
c= 1*20
print(a)
print(b)
print(c)

Output :-
100
-100
200
Visit : python.mykvs.in for regular updates
Data type continue
Type Conversion of Integer
int() function converts any data type to integer.
e.g.

a = "101" # string
b=int(a) # converts string data type to integer.
c=int(122.4) # converts float data type to
integer.
print(b)
print(c)Run Code
Output :-
101
122
Visit : python.mykvs.in for regular updates
Data type continue
2. Floating point numbers
It is a positive or negative real numbers
with a decimal point.
e.g.
a = 101.2
b = -101.4
c = 111.23
d = 2.3*3
print(a)
print(b)
print(c)
print(d)Run Code

Output :-
101.2
-101.4
111.23
6.8999999999999995

Visit : python.mykvs.in for regular updates


Data type continue
Type Conversion of Floating point numbers
float() function converts any data type to floating point
number.
e.g.
a='301.4' #string
b=float(a) #converts string data type to floating point number.
c=float(121) #converts integer data type to floating point number.
print(b)
print(c)Run Code

Output :-
301.4
121.0

Visit : python.mykvs.in for regular updates


Data type continue
3. Complex numbers
Complex numbers are combination of a
real and imaginary part.Complex numbers are in
the form of X+Yj, where X is a real part and Y is
imaginary part.
e.g.
a = complex(5) # convert 5 to a real part val and zero imaginary part
print(a)
b=complex(101,23) #convert 101 with real part and 23 as imaginary part
print(b)Run Code

Output :-
(5+0j)
(101+23j)

Visit : python.mykvs.in for regular updates


Data type continue
2. String In Python
A string is a sequence of characters. In python we can create string
using single (' ') or double quotes (" ").Both are same in python.
e.g.
str='computer science'
print('str-', str) # print string
print('str[0]-', str[0]) # print first char 'h'
print('str[1:3]-', str[1:3]) # print string from postion 1 to 3 'ell'
print('str[3:]-', str[3:]) # print string staring from 3rd char 'llo world'
print('str *2-', str *2 ) # print string two times
print("str +'yes'-", str +'yes') # concatenated string

Output
str- computer science
str[0]- c
str[1:3]- om
str[3:]- puter science
str *2- computer sciencecomputer science
str +'yes'- computer scienceyes

Visit : python.mykvs.in for regular updates


Data type continue
Iterating through string

e.g.
str='comp sc'
for i in str:
print(i)

Output
c
o
m
p

s
c

Visit : python.mykvs.in for regular updates


Data type continue
3. Boolean In Python
It is used to store two possible values either true or false
e.g.
str="comp sc"
boo=str.isupper() # test if string contains upper case
print(boo)

Output
False

Visit : python.mykvs.in for regular updates


Data type continue
4.List In Python
List are collections of items and each item has its own index value.
5. Tuple In Python
List and tuple, both are same except ,a list is mutable python objects and
tuple is immutable Python objects. Immutable Python objects mean you
cannot modify the contents of a tuple once it is assigned.

e.g. of list e.g. of tuple


list =[6,9] tup=(66,99)
list[0]=55 Tup[0]=3 # error message will be displayed
print(list[0]) print(tup[0])
print(list[1]) print(tup[1])

OUTPUT
55
9

Visit : python.mykvs.in for regular updates


Data type continue
6. Set In Python
It is an unordered collection of unique and
immutable (which cannot be modified)items.
e.g.
set1={11,22,33,22}
print(set1)

Output
{33, 11, 22}

Visit : python.mykvs.in for regular updates


Data type continue
7. Dictionary In Python
It is an unordered collection of items and each
item consist of a key and a value.
e.g.
dict = {'Subject': 'comp sc', 'class': '11'}
print(dict)
print ("Subject : ", dict['Subject'])
print ("class : ", dict.get('class'))

Output
{'Subject': 'comp sc', 'class': '11'}
Subject : comp sc
class : 11

Visit : python.mykvs.in for regular updates


Operator
Operators are special symbols in Python that carry out arithmetic or
logical computation. The value that the operator operates on is called
the operand.
Arithmetic operators
Used for mathematical operation
Operator Meaning Example
x+y
+ Add two operands or unary plus
+2
x-y
- Subtract right operand from the left or unary minus
-2
* Multiply two operands x*y
Divide left operand by the right one (always results into
/ x/y
float)
Modulus - remainder of the division of left operand by the
% x % y (remainder of x/y)
right

Floor division - division that results into whole number


// x // y
adjusted to the left in the number line

** Exponent - left operand raised to the power of right x**y (x to the power y)

Visit : python.mykvs.in for regular updates


Operator continue
Arithmatic operator continue
e.g.
x=5
y=4
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)

OUTPUT
('x + y =', 9)
('x - y =', 1)
('x * y =', 20) • Write a program in python to calculate the
('x / y =', 1) simple interest based on entered amount ,rate
('x // y =', 1) and time
('x ** y =', 625)

Visit : python.mykvs.in for regular updates


Operator continue
Arithmatic operator continue

# EMI Calculator program in Python

def emi_calculator(p, r, t):


r = r / (12 * 100) # one month interest
t = t * 12 # one month period
emi = (p * r * pow(1 + r, t)) / (pow(1 + r, t) - 1)
return emi

# driver code
principal = 10000;
rate = 10;
time = 2;
emi = emi_calculator(principal, rate, time);
print("Monthly EMI is= ", emi)

Visit : python.mykvs.in for regular updates


Operator continue
Arithmatic operator continue
How to calculate GST
GST ( Goods and Services Tax ) which is included in netprice
of product for get GST % first need to calculate GST Amount by subtract
original cost from Netprice and then apply
GST % formula = (GST_Amount*100) / original_cost

# Python3 Program to compute GST from original and net prices.

def Calculate_GST(org_cost, N_price):


# return value after calculate GST%
return (((N_price - org_cost) * 100) / org_cost);

# Driver program to test above functions


org_cost = 100
N_price = 120
print("GST = ",end='')
print(round(Calculate_GST(org_cost, N_price)),end='')
print("%")
* Write a Python program to calculate the standard deviation

Visit : python.mykvs.in for regular updates


Operator continue
Comparison operators
used to compare values
Exampl
Operator Meaning
e

> Greater that - True if left operand is greater than the right x>y

< Less that - True if left operand is less than the right x<y

== Equal to - True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

Greater than or equal to - True if left operand is greater than


>= x >= y
or equal to the right

Less than or equal to - True if left operand is less than or


<= x <= y
equal to the right

Visit : python.mykvs.in for regular updates


Operator continue
Comparison operators continue
e.g.
x = 101
y = 121
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)

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

Visit : python.mykvs.in for regular updates


Operator continue
Logical operators

Operator Meaning Example

and True if both the operands are true x and y

or True if either of the operands is true x or y

not True if operand is false (complements the operand) not x


e.g.
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)

Outpur
('x and y is', False)
('x or y is', True)
('not x is', False)

Visit : python.mykvs.in for regular updates


Operator continue
Bitwise operators
Used to manipulate bit values.

Operator Meaning Example

& Bitwise AND x& y


| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>> 2
<< Bitwise left shift x<< 2

Visit : python.mykvs.in for regular updates


Operator continue
Bitwise operators continue
a=6
b=3 Output
print ('a=',a,':',bin(a),'b=',b,':',bin(b))
('a=', 6, ':', '0b110', 'b=', 3, ':', '0b11')
c=0
c = a & b; ('result of AND is ', 2, ':', '0b10')
print ("result of AND is ", c,':',bin(c)) ('result of OR is ', 7, ':', '0b111')
c = a | b; ('result of EXOR is ', 5, ':', '0b101')
print ("result of OR is ", c,':',bin(c)) ('result of COMPLEMENT is ', -7, ':', '-0b111')
c = a ^ b; ('result of LEFT SHIFT is ', 24, ':', '0b11000')
print ("result of EXOR is ", c,':',bin(c)) ('result of RIGHT SHIFT is ', 1, ':', '0b1')
c = ~a;
print ("result of COMPLEMENT is ",
c,':',bin(c))
c = a << 2;
print ("result of LEFT SHIFT is ", c,':',bin(c))
c = a >> 2;
print ("result of RIGHT SHIFT is ", c,':',bin(c))

Visit : python.mykvs.in for regular updates


Operator continue
Python Membership Operators
Test for membership in a sequence
Operator Description
in Evaluates to true if it finds a variable in the specified sequence and false otherwise.
not in Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.

e.g.
a=5
b = 10
list = [1, 2, 3, 4, 5 ]
if ( a in list ):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")
if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
print ("Line 2 - b is available in the given list")
output
Line 1 - a is available in the given list
Line 2 - b is not available in the given list

Visit : python.mykvs.in for regular updates


Operator continue
Python Identity Operators
Opera Description
tor
Evaluates to true if the variables on either side of the operator point to the
is
same object and false otherwise.
Evaluates to false if the variables on either side of the operator point to the
is not
same object and true otherwise.

e.g.
a = 10
b = 10
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is b ):
print ("Line 2 - a and b have same identity")
else:
print ("Line 2 - a and b do not have same identity")
OUTPUT
('Line 1', 'a=', 10, ':', 20839436, 'b=', 10, ':', 20839436)
Line 2 - a and b have same identity

Visit : python.mykvs.in for regular updates


Operator continue
Operators Precedence :highest precedence to lowest precedence table
Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus (method names for the last two are +@ and
-@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction


>> << Right and left bitwise shift
& Bitwise 'AND'td>
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= Assignment operators
+= *= **=
is is not Identity operators
in not in Membership operators
not or and Logical operators

Visit : python.mykvs.in for regular updates


Expression
It is a valid combination of operators,literals and variable.
1. Arithmatic expression :- e.g. c=a+b
2. Relational expression :- e.g. x>y
3. Logical expression :- a or b
4. String expression :- c=“comp”+”sc”

Visit : python.mykvs.in for regular updates


Type conversion
The process of converting the value of one data type (integer, string, float, etc.) to
another data type is called type conversion.
Python has two types of type conversion.
Implicit Type Conversion
Explicit Type Conversion

Implicit Type Conversion:


In Implicit type conversion, Python automatically converts one data type to another
data type. This process doesn't need any user involvement.
e.g.
num_int = 12
num_flo = 10.23
OUTPUT
num_new = num_int + num_flo
('datatype of num_int:', <type 'int'>)
print("datatype of num_int:",type(num_int)) ('datatype of num_flo:', <type 'float'>)
print("datatype of num_flo:",type(num_flo)) ('Value of num_new:', 22.23)
print("Value of num_new:",num_new) ('datatype of num_new:', <type 'float'>)
print("datatype of num_new:",type(num_new))

Visit : python.mykvs.in for regular updates


Type conversion
Explicit Type Conversion:
In Explicit Type Conversion, users convert the data type of an object to
required data type. We use the predefined functions like int(),float(),str() etc.
e.g.
num_int = 12
num_str = "45"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))

OUTPUT
('Data type of num_int:', <type 'int'>)
('Data type of num_str before Type Casting:', <type 'str'>)
('Data type of num_str after Type Casting:', <type 'int'>)
('Sum of num_int and num_str:', 57)
('Data type of the sum:', <type 'int'>)

Visit : python.mykvs.in for regular updates


math module
It is a standard module in Python. To use mathematical functions of this
module,we have to import the module using import math.
Function Description Example
ceil(n) It returns the smallest integer greater than or equal to n. math.ceil(4.2) returns 5

factorial(n) It returns the factorial of value n math.factorial(4) returns 24

floor(n) It returns the largest integer less than or equal to n math.floor(4.2) returns 4

fmod(x, y) It returns the remainder when n is divided by y math.fmod(10.5,2) returns 0.5

exp(n) It returns e**n math.exp(1) return 2.718281828459045

log2(n) It returns the base-2 logarithm of n math.log2(4) return 2.0

log10(n) It returns the base-10 logarithm of n math.log10(4) returns 0.6020599913279624

pow(n, y) It returns n raised to the power y math.pow(2,3) returns 8.0

sqrt(n) It returns the square root of n math.sqrt(100) returns 10.0

cos(n) It returns the cosine of n math.cos(100) returns 0.8623188722876839

sin(n) It returns the sine of n math.sin(100) returns -0.5063656411097588

tan(n) It returns the tangent of n math.tan(100) returns -0.5872139151569291

pi It is pi value (3.14159...) It is (3.14159...)

e It is mathematical constant e (2.71828...) It is (2.71828...)

Visit : python.mykvs.in for regular updates


Chapter 5 :

Informatics
practices
Conditional
Class XI ( As per
CBSE Board)
&
Looping
Constructs

Visit : python.mykvs.in for regular updates


Control Statements
Control statements are used to control the flow
of execution depending upon the specified
condition/logic.

There are three types of control statements.

1. Decision Making Statements


2. Iteration Statements (Loops)
3. Jump Statements (break, continue, pass)

Visit : python.mykvs.in for regular updates


Decision Making Statement
Decision making statement used to control the
flow of execution of program depending upon
condition.

There are three types of decision making statement.


1. if statements
2. if-else statements
3. Nested if-else statement

Visit : python.mykvs.in for regular updates


Decision Making Statement
1. if statements
An if statement is a programming conditional
statement that, if proved true, performs a
function or displays information.

Visit : python.mykvs.in for regular updates


Decision Making Statement
1. if statements
Syntax:
if(condition):
statement
[statements]
e.g.
noofbooks = 2
if (noofbooks == 2):
print('You have ')
print(‘two books’)
print(‘outside of if statement’)
Output
You have two books
Note:To indicate a block of code in Python, you must indent each
line of the block by the same amount. In above e.g. both print
statements are part of if condition because of both are at same
level indented but not the third print statement.
Visit : python.mykvs.in for regular updates
Decision Making Statement
1. if statements
Using logical operator in if statement
x=1
y=2
if(x==1 and y==2):
print(‘condition matcing the criteria')

Output :-
condition matcing the criteria
-----------------------------------------------------------
a=100
if not(a == 20):
print('a is not equal to 20')

Output :-
a is not equal to 20

Visit : python.mykvs.in for regular updates


Decision Making Statement
2. if-else Statements
If-else statement executes some code if the test expression is true
(nonzero) and some other code if the test expression is false.

Visit : python.mykvs.in for regular updates


Decision Making Statement
2. if-else Statements
Syntax:
if(condition):
statements
else:
statements
e.g.
a=10
if(a < 100):
print(‘less than 100')
else:
print(‘more than equal 100')

OUTPUT
less than 100

*Write a program in python to check that entered numer is


even or odd
Visit : python.mykvs.in for regular updates
Decision Making Statement
3. Nested if-else statement
The nested if...else statement allows you to check for multiple test
expressions and execute different codes for more than two
conditions.

Visit : python.mykvs.in for regular updates


Decision Making Statement
3. Nested if-else statement
Syntax
If (condition):
statements
elif (condition):
statements
else:
statements
E.G.
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
OUTPUT
Enter a number: 5
Positive number
* Write python program to find out largest of 3 numbers.

Visit : python.mykvs.in for regular updates


Iteration Statements (Loops)
Iteration statements(loop) are used to execute a block
of statements as long as the condition is true.
Loops statements are used when we need to run same
code again and again.

Python Iteration (Loops) statements are of three type :-

1. While Loop

2. For Loop

3. Nested For Loops

Visit : python.mykvs.in for regular updates


Iteration Statements (Loops)
1. While Loop
It is used to execute a block of statement as long as a
given condition is true. And when the condition become
false, the control will come out of the loop. The
condition is checked every time at the beginning of the
loop.
Syntax
while (condition):
statement
[statements]
e.g.
x=1 Output
while (x <= 4): 1
print(x) 2
3
x=x+1 4

Visit : python.mykvs.in for regular updates


Iteration Statements (Loops)
While Loop continue
While Loop With Else
e.g.

x=1
while (x < 3):
print('inside while loop value of x is ',x)
x=x+1
else:
print('inside else value of x is ', x)

Output
inside while loop value of x is 1
inside while loop value of x is 2
inside else value of x is 5

*Write a program in python to find out the factorial of a given


number
Visit : python.mykvs.in for regular updates
Iteration Statements (Loops)
While Loop continue
Infinite While Loop
e.g.
x=5
while (x == 5):
print(‘inside loop')

Output
Inside loop
Inside loop

Visit : python.mykvs.in for regular updates


Iteration Statements (Loops)
2. For Loop
It is used to iterate over items of any sequence, such
as a list or a string.
Syntax
for val in sequence:
statements

e.g.
for i in range(3,5):
print(i)

Output
3
4

Visit : python.mykvs.in for regular updates


Iteration Statements (Loops)
2. For Loop continue
Example programs
for i in range(5,3,-1):
print(i)

Output
5
4
range() Function Parameters
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step(Optional): Determines the increment between each numbers
in the sequence.

Visit : python.mykvs.in for regular updates


Iteration Statements (Loops)
2. For Loop continue
For Loop With Else
e.g.
for i in range(1, 4):
print(i)
else: # Executed because no break in for
print("No Break")

Output
1
2
3
4
No Break

Visit : python.mykvs.in for regular updates


Iteration Statements (Loops)
2. For Loop continue
Nested For Loop
e.g.
for i in range(1,3):
for j in range(1,11):
k=i*j
print (k, end=' ')
print()

Output
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20

Visit : python.mykvs.in for regular updates


Iteration Statements (Loops)
3. Jump Statements

Jump statements are used to transfer


the program's control from one location to another.
Means these are used to alter the flow of a loop like - to
skip a part of a loop or terminate a loop

There are three types of jump statements used in


python.
1.break
2.continue
3.pass

Visit : python.mykvs.in for regular updates


Iteration Statements (Loops)
1.break
it is used to terminate the loop.
e.g.
for val in "string":
if val == "i":
break
print(val)

print("The end")

Output
s
t
r
The end
Visit : python.mykvs.in for regular updates
Iteration Statements (Loops)
2.continue
It is used to skip all the remaining statements in
the loop and move controls back to the top of the loop.
e.g.
for val in "init":
if val == "i":
continue
print(val)
print("The end")

Output
n
t
The end

Visit : python.mykvs.in for regular updates


Iteration Statements (Loops)
3. pass Statement
This statement does nothing. It can be used when a
statement is required syntactically but the program
requires no action.
Use in loop
while True:
pass # Busy-wait for keyboard interrupt (Ctrl+C)
In function
It makes a controller to pass by without executing any code.
e.g.
def myfun():
pass #if we don’t use pass here then error message will be shown
print(‘my program')

OUTPUT
My program

Visit : python.mykvs.in for regular updates


Iteration Statements (Loops)
3. pass Statement continue
e.g.
for i in 'initial':
if(i == 'i'):
pass
else:
print(i)

OUTPUT
n
t
a
L
NOTE : continue forces the loop to start at the next
iteration while pass means "there is no code to execute
here" and will continue through the remainder or the loop
body.
Visit : python.mykvs.in for regular updates
Chapter 6 :

Informatics
Practices
Class XI ( As per List
CBSE Board) Manipulation

Visit : python.mykvs.in for regular updates


List Manipulation
It is a collections of items and each item has its own
index value.
Index of first item is 0 and the last item is n-1.Here n is
number of items in a list.

Indexing of list

Visit : python.mykvs.in for regular updates


List Manipulation
Creating a list
Lists are enclosed in square brackets [ ] and each item
is separated by a comma.

e.g.

list1 = [‘English', ‘Hindi', 1997, 2000];


list2 = [11, 22, 33, 44, 55 ];
list3 = ["a", "b", "c", "d"];

Visit : python.mykvs.in for regular updates


List Manipulation
Access Items From A List
List items can be accessed using its index position.
e.g.
list =[3,5,9]
print(list[0])
3
print(list[1]) 5
print(list[2]) 9
print('Negative indexing') output Negative indexing
print(list[-1]) 9
print(list[-2]) 5
3
print(list[-3])

Visit : python.mykvs.in for regular updates


List Manipulation
Iterating Through A List
List elements can be accessed using looping
statement.
e.g.

list =[3,5,9]
for i in range(0, len(list)):
print(list[i])

Output
3
5
9

Visit : python.mykvs.in for regular updates


List Manipulation
Slicing of A List
List elements can be accessed in subparts.

e.g.
list =['I','N','D','I','A']
print(list[0:3])
print(list[3:])
print(list[:])

Output
['I', 'N', 'D']
['I', 'A']
['I', 'N', 'D', 'I', 'A']

Visit : python.mykvs.in for regular updates


List Manipulation
Updating Lists
We can update single or multiple elements of lists by
giving the slice on the left-hand side of the assignment
operator.
e.g.
list = ['English', 'Hindi', 1997, 2000]
print ("Value available at index 2 : ", list[2])
list[2:3] = 2001,2002 #list[2]=2001 for single item update
print ("New value available at index 2 : ", list[2])
print ("New value available at index 3 : ", list[3])
Output
('Value available at index 2 : ', 1997)
('New value available at index 2 : ', 2001)
('New value available at index 3 : ', 2002)

Visit : python.mykvs.in for regular updates


List Manipulation
Add Item to A List
append() method is used to add an Item to a List.

e.g.
list=[1,2]
print('list before append', list)
list.append(3)
print('list after append', list)
Output
('list before append', [1, 2])
('list after append', [1, 2, 3])

NOTE :- extend() method can be used to add


multiple item at a time in list.eg - list.extend([3,4])

Visit : python.mykvs.in for regular updates


List Manipulation
Add Item to A List
append() method is used to add an Item to a List.

e.g.
list=[1,2]
print('list before append', list)
list.append(3)
print('list after append', list)
Output
('list before append', [1, 2])
('list after append', [1, 2, 3])

NOTE :- extend() method can be used to add


multiple item at a time in list.eg - list.extend([3,4])

Visit : python.mykvs.in for regular updates


List Manipulation
Add Two Lists
e.g.
list = [1,2]
list2 = [3,4]
list3 = list + list2
print(list3)

OUTPUT
[1,2,3,4]

Visit : python.mykvs.in for regular updates


List Manipulation
Delete Item From A List
e.g.
list=[1,2,3]
print('list before delete', list)
del list [1]
print('list after delete', list)

Output

('list before delete', [1, 2, 3])


('list after delete', [1, 3])

e.g.
del list[0:2] # delete first two items
del list # delete entire list
Visit : python.mykvs.in for regular updates
List Manipulation
Basic List Operations

Python Results Description


Expression
len([4, 2, 3]) 3 Length
[4, 2, 3] + [1, 5, 6] [4, 2, 3, 1, 5, 6] Concatenation
[‘cs!'] * 4 ['cs!', 'cs!', 'cs!', Repetition
'cs!']
3 in [4, 2, 3] True Membership
for x in [4,2,3] : 423 Iteration
print (x,end = ' ')

Visit : python.mykvs.in for regular updates


List Manipulation
Important methods and functions of List
Function Description
list.append() Add an Item at end of a list
list.extend() Add multiple Items at end of a list
list.insert() insert an Item at a defined index
list.remove() remove an Item from a list
del list[index] Delete an Item from a list
list.clear() empty all the list
list.pop() Remove an Item at a defined index
list.index() Return index of first matched item
list.sort() Sort the items of a list in ascending or descending order
list.reverse() Reverse the items of a list
len(list) Return total length of the list.
max(list) Return item with maximum value in the list.
min(list) Return item with min value in the list.
list(seq) Converts a tuple, string, set, dictionary into list.

Visit : python.mykvs.in for regular updates


List Manipulation
Some Programs on List
* find the largest number in a list
#Using sort
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:",a[n-1])

#using function definition


def max_num_in_list( list ): list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
max = list[ 0 ] print "Max value element : ", max(list1)
print "Max value element : ", max(list2)
for a in list: Output
if a > max: Max value element : zara
max = a Max value element : 700

return max
print(max_num_in_list([1, 2, -8, 0]))
Visit : python.mykvs.in for regular updates
List Manipulation
Some Programs on List
* find the mean of a list
def Average(lst):
return sum(lst) / len(lst)

# Driver Code
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst)

# Printing average of the list


print("Average of the list =", round(average, 2))

Output
Average of the list = 35.75

Note : The inbuilt function mean() can be used to calculate the mean(
average ) of the list.e.g. mean(list)

Visit : python.mykvs.in for regular updates


List Manipulation
Some Programs on List
* Linear Search
list_of_elements = [4, 2, 8, 9, 3, 7]

x = int(input("Enter number to search: "))

found = False

for i in range(len(list_of_elements)):
if(list_of_elements[i] == x):
found = True
print("%d found at %dth position"%(x,i))
break

if(found == False):
print("%d is not in list"%x)

Visit : python.mykvs.in for regular updates


List Manipulation
Some Programs on List
* Frequency of an element in list
import collections
my_list = [101,101,101,101,201,201,201,201]
print("Original List : ",my_list)
ctr = collections.Counter(my_list)
print("Frequency of the elements in the List : ",ctr)

OUTPUT
Original List : [101, 101,101, 101, 201, 201, 201, 201]
Frequency of the elements in the List : Counter({101: 4, 201:4})

NOTE :SAME CAN BE DONE USING COUNT FUNCTION.E.G. lst.count(x)

Visit : python.mykvs.in for regular updates


Chapter 7 :

Informatics
Practices
Class XI ( As per
CBSE Board) Dictionary

Visit : python.mykvs.in for regular updates


Dictionary
It is an unordered collection of items where each item
consist of a key and a value.
It is mutable (can modify its contents ) but Key must be
unique and immutable.

Visit : python.mykvs.in for regular updates


Dictionary
Creating A Dictionary
It is enclosed in curly braces {} and each item is
separated from other item by a comma(,). Within each
item, key and value are separated by a colon (:).
e.g.
dict = {‘Subject': ‘Informatic Practices', 'Class': ‘11'}

Accessing List Item


dict = {'Subject': 'Informatics Practices', 'Class': 11}
print(dict)
print ("Subject : ", dict['Subject'])
print ("Class : ", dict.get('Class'))

OUTPUT
{'Class': '11', 'Subject': 'Informatics Practices'}
('Subject : ', 'Informatics Practices')
('Class : ', 11)
Visit : python.mykvs.in for regular updates
Dictionary
Iterating Through A Dictionary
Following example will show how dictionary items can be
accessed through loop.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
for i in dict:
print(dict[i])
OUTPUT
11
Informatics Practices

Updating Dictionary Elements


We can change the individual element of dictionary.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
dict['Subject']='computer science'
print(dict)
OUTPUT
{'Class': 11, 'Subject': 'computer science'}
Visit : python.mykvs.in for regular updates
Dictionary
Deleting Dictionary Elements
del, pop() and clear() statement are used to remove elements from
the dictionary.
del e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print('before del', dict)
del dict['Class'] # delete single element
print('after item delete', dict)
del dict #delete whole dictionary
print('after dictionary delete', dict)

Output
('before del', {'Class': 11, 'Subject': 'Informatics Practices'})
('after item delete', {'Subject': 'Informatics Practices'})
('after dictionary delete', <type 'dict'>)

Visit : python.mykvs.in for regular updates


Dictionary
pop() method is used to remove a particular item in a dictionary. clear()
method is used to remove all elements from the dictionary.
e.g.
dict = {'Subject': 'Informatics Practices', 'Class': 11}
print('before del', dict)
dict.pop('Class')
print('after item delete', dict)
dict.clear()
print('after clear', dict)

Output
('before del', {'Class': 11, 'Subject': 'Informatics Practices'})
('after item delete', {'Subject': 'Informatics Practices'})
('after clear', {})

Visit : python.mykvs.in for regular updates


Dictionary
Built-in Dictionary Functions
S.No. Function & Description
len(dict)Gives the total length of the dictionary. It is equal
to the number of items in the dictionary.
1

str(dict)Return a printable string representation of a


2 dictionary

type(variable)If variable is dictionary, then it would return


a dictionary type.
3

Visit : python.mykvs.in for regular updates


Dictionary

Built-in Dictionary Methods


S.No. Method & Description
1 dict.clear()Removes all elements of dictionary dict
2 dict.copy()Returns a shallow copy of dictionary dict
3 dict.items()Returns a list of dict's (key, value) tuple pairs
4 dict.keys()Returns list of dictionary dict's keys
dict.setdefault(key, default = None)Similar to get(), but will set
5
dict[key] = default if key is not already in dict
6 dict.update(dict2)Adds dictionary dict2's key-values pairs to dict
7 dict.values()Returns list of dictionary dict's values

Visit : python.mykvs.in for regular updates


Dictionary

Questions.
1. Create dictionary to store 4 student
details with rollno,name,age field.Search
student in list.
2. Create dictionary for month and
noofdays for a year. User is asked to
enter month name and system will show
no of days of that month.

Visit : python.mykvs.in for regular updates


Chapter 8 :

Informatics
Practices
Class XI ( As per
CBSE Board) Text
Handling

Visit : python.mykvs.in for regular updates


String Manipulation
String is a sequence of characters,which is enclosed
between either single (' ') or double quotes (" "), python
treats both single and double quotes same.

Visit : python.mykvs.in for regular updates


String Manipulation
Creating String
Creation of string in python is very easy.
e.g.
a=‘Computer Science'
b=“Informatics Practices“
Accessing String Elements
e.g.

str='Computer Sciene'
('str-', 'Computer Sciene')
print('str-', str) ('str[0]-', 'C')
print('str[0]-', str[0]) ('str[1:4]-', 'omp')
print('str[1:4]-', str[1:4]) ('str[2:]-', 'mputer Sciene')
print('str[2:]-', str[2:]) ('str *2-', 'Computer ScieneComputer
print('str *2-', str *2 ) OUTPUT Sciene')
print("str +'yes'-", str +'yes') ("str +'yes'-", 'Computer Scieneyes')

Visit : python.mykvs.in for regular updates


String Manipulation
Iterating through string
Each character of the string can be accessed sequentially using for
loop.

C
e.g. o
m
p
u
str='Computer Sciene‘ OUTPUT t
for i in str: e
print(i) r

S
c
i
e
n
e

Visit : python.mykvs.in for regular updates


String Manipulation
Updating Strings
String value can be updated by reassigning another
value in it.
e.g.
var1 = 'Comp Sc'
var1 = var1[:7] + ' with Python'
print ("Updated String :- ",var1 )

OUTPUT
('Updated String :- ', 'Comp Sc with Python')

Visit : python.mykvs.in for regular updates


String Manipulation
String Special Operators
e.g.
a=“comp”
B=“sc”
Operator Description Example
+ Concatenation – to add two a + b = comp sc
* Replicate same string multiple times a*2 = compcomp
[] Character of the string a[1] will give o
[:] Range Slice –Range string a[1:4] will give omp
in Membership check p in a will give 1
not in Membership check for non availability M not in a will give 1
% Format the string

print ("My Subject is %s and class is %d" % ('Comp Sc', 11))

Visit : python.mykvs.in for regular updates


String Manipulation
Format Symbol

%s -string conversion via str() prior to formatting


%i -signed decimal integer
%d -signed decimal integer
%u -unsigned decimal integer
%o -octal integer
%x -hexadecimal integer (lowercase letters)
%X -hexadecimal integer (UPPERcase letters)
%e -exponential notation (with lowercase 'e')
%E -exponential notation (with UPPERcase 'E')
%f -floating point real number
%c -character
%G -the shorter of %f and %E

Visit : python.mykvs.in for regular updates


String Manipulation
Triple Quotes
It is used to create string with multiple lines.

e.g.
Str1 = “””This course will introduce the learner to text
mining and text manipulation basics. The course
begins with an understanding of how text is handled by
python”””

Visit : python.mykvs.in for regular updates


String Manipulation
String functions and methods

Method Result
str.capitalize() To capitalize the string
str.find(sub) To find the substring position
String consists of only alphanumeric characters (no
str.isalnum()
symbols)
str.isalpha() String consists of only alphabetic characters (no symbols)
str.islower() String’s alphabetic characters are all lower case
str.isnumeric() String consists of only numeric characters
str.isspace() String consists of only whitespace characters
str.istitle() String is in title case
str.isupper() String’s alphabetic characters are all upper case
str.lstrip(char) Returns a copy of the string with leading/trailing
str.rstrip(char) characters

Visit : python.mykvs.in for regular updates


String Manipulation
#Python Program to calculate the number of digits and
letters in a string

string=raw_input("Enter string:")
count1=0
count2=0
for i in string:
if(i.isdigit()):
count1=count1+1
count2=count2+1
print("The number of digits is:")
print(count1)
print("The number of characters is:")
print(count2)

Visit : python.mykvs.in for regular updates


String Manipulation
#Number of occurrences of substring in main string

str = "this is india";


sub = "is";
print "str.count(sub, 4, 40) : ", str.count(sub, 0, len(str))

Output

str.count(sub, 4, 40) : 2

Visit : python.mykvs.in for regular updates


Chapter 9 :

Informatics
Practices
Class XI ( As per
Python
CBSE Board)
Modules

Visit : python.mykvs.in for regular updates


Python Module
A module is a logical organization of Python code.
Related code are grouped into a module which makes
the code easier to understand and use. Any python
module is an object with different attributes which can
be bind and referenced.
Simply, it is a file containing a set of functions which
can be included in our application.

Visit : python.mykvs.in for regular updates


Python Module
Create a Module
It is very easy to create a module in python.we have to just
save the code which we want to be as a part of module in a
file with the file extension .py
e.g.
1. Create a file a.py with following code
def label(str1):
print("----------------------------------------------")
print(str1)
print("----------------------------------------------")
2. Save this file
3. Now create one another file b.py with following code
import a
s=input("enter your school name")
a.label(s)
4. Now run it.
NOTE :- In above e.g. file a.py is being used as module b.py as
main program
Visit : python.mykvs.in for regular updates
Python Module
Variables in Module
The module can contain not only functions but also variables of all
types (arrays, dictionaries, objects etc):

e.g.
1. Create file a.py with following code
student = {
"name": "Vijay Shanti",
"age": 36,
"country": "India"
}
2. Save it
3. Create b.py with following code
import a
s = a.person1["age"]
print(s)
4. Run it

Visit : python.mykvs.in for regular updates


Python Module
Re-naming a Module
We can alias a module while importing it with the help of as keyword

e.g.

import a as m1 #here a is module and m1 is alias of the module


s = m1.person1["age"]
print(s)

Save the above script and run it.

Visit : python.mykvs.in for regular updates


Python Module
Checking for built in module
1. Type import <module name> on shell. E.g. import math
2. If it shows error then it indicate that this module is not installed.
3. Install the module after download with the help of pip/pip3
command
Some built in modules
Numeric and Mathematical Modules
1. numbers — Numeric abstract base classes
2. math — Mathematical functions
3. cmath — Mathematical functions for complex number
4. decimal — Decimal fixed point and floating point arithmetic
5. fractions — Rational numbers
6. random — Generate pseudo-random numbers
7. statistics — Mathematical statistics functions
Functional Programming Modules
1. itertools — Functions creating iterators for efficient looping
2. functools — Higher-order functions and operations on callable
objects
3. operator — Standard operators as functions
Visit : python.mykvs.in for regular updates
Python Module
Locating Modules
Python interpreter searches for the module in the following sequences −

1. The current directory.


2. Then searches each directory in the shell variable PYTHONPATH.
3. Then checks the default path.

The PYTHONPATH Variable


It is an environment variable, consisting of a list of directories.

set PYTHONPATH = c:\python34\lib;


Use such command in cmd.exe (dos command prompt) in windows OS.

Visit : python.mykvs.in for regular updates


Chapter 10 :

Informatics
Practices
Class XI ( As per
Python
CBSE Board)
Pandas

Visit : python.mykvs.in for regular updates


Python Pandas
It is a most famous Python package for data science, which
offers powerful and flexible data structures that make data
analysis and manipulation easy.Pandas makes data importing
and data analyzing much easier. Pandas builds on packages
like NumPy and matplotlib to give us a single & convenient
place for data analysis and visualization work.

Visit : python.mykvs.in for regular updates


Python Pandas
Basic Features of Pandas
1. Dataframe object help a lot in keeping track of our data.
2. With a pandas dataframe, we can have different data types
(float, int, string, datetime, etc) all in one place
3. Pandas has built in functionality for like easy grouping &
easy joins of data, rolling windows
4. Good IO capabilities; Easily pull data from a MySQL
database directly into a data frame
5. With pandas, you can use patsy for R-style syntax in
doing regressions.
6. Tools for loading data into in-memory data objects from
different file formats.
7. Data alignment and integrated handling of missing data.
8. Reshaping and pivoting of data sets.
9. Label-based slicing, indexing and subsetting of large data
sets.
Visit : python.mykvs.in for regular updates
Python Pandas
Python Pandas – Installation/Environment Setup
Pandas module doesn't come bundled with Standard Python.
If we install Anaconda Python package Pandas will be
installed by default.
Steps for Anaconda installation & Use
1. visit the site https://www.anaconda.com/download/
2. Download appropriate anaconda installer
3. After download install it.
4. During installation check for set path and all user
5. After installation start spyder utility of anaconda from start menu
6. Type import pandas as pd in left pane(temp.py)
7. Then run it.
8. If no error is show then it shows pandas is installed.
9. Like default temp.py we can create another .py file from new
window option of file menu for new program.
Visit : python.mykvs.in for regular updates
Python Pandas
Python Pandas – Installation/Environment Setup
Pandas installation can be done in Standard Python
distribution,using following steps.
1. There must be service pack installed on our computer if we
are using windows.If it is not installed then we will not be
able to install pandas in existing Standard Python(which is
already installed).So install it first(google it).
2. We can check it through properties option of my computer
icon.

3. Now install latest version(any one above 3.4) of python.

Visit : python.mykvs.in for regular updates


Python Pandas
Python Pandas – Installation/Environment Setup

4. Now move to script folder of python distribution in command


prompt (through cmd command of windows).
5. Execute following commands in command prompt serially.
>pip install numpy
>pip install six
>pip install pandas
Wait after each command for installation
Now we will be able to use pandas in standard python
distribution.
6. Type import pandas as pd in python (IDLE) shell.
7. If it executed without error(it means pandas is installed on
your system)
Visit : python.mykvs.in for regular updates
Python Pandas
Data Structures in Pandas
Two important data structures of pandas are–Series, DataFrame
1. Series
Series is like a one-dimensional array like structure with
homogeneous data. For example, the following series is a
collection of integers.

Basic feature of series are


 Homogeneous data
 Size Immutable
 Values of Data Mutable

Visit : python.mykvs.in for regular updates


Python Pandas
2. DataFrame
DataFrame is like a two-dimensional array with
heterogeneous data.

SR. Admn Student Name Class Section Gender Date Of


No. No Birth
1 001284 NIDHI MANDAL I A Girl 07/08/2010
2 001285 SOUMYADIP I A Boy 24/02/2011
BHATTACHARYA
3 001286 SHREYAANG I A Boy 29/12/2010
SHANDILYA

Basic feature of DataFrame are


 Heterogeneous data
 Size Mutable
 Data Mutable

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas Series
It is like one-dimensional array capable of holding data
of any type (integer, string, float, python objects, etc.).
Series can be created using constructor.
Syntax :- pandas.Series( data, index, dtype, copy)

Series can be created using

1. Array
2. Dict
3. Scalar value or constant

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas Series

Create an Empty Series

e.g.

import pandas as pseries


s = pseries.Series()
print(s)

Output
Series([], dtype: float64)

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas Series
Create a Series from ndarray
Without index With index position
e.g. e.g.

import pandas as pd1 import pandas as p1


import numpy as np1 import numpy as np1
data = np1.array(['a','b','c','d']) data = np1.array(['a','b','c','d'])
s = pd1.Series(data) s = p1.Series(data,index=[100,101,102,103])
print(s) print(s)

Output Output
0 a 100 a
1 b 101 b
2 c 102 c
3 d 103 d
dtype: object dtype: object
Note : default index is starting
from 0 Note : index is starting from 100

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas Series
Create a Series from dict

Eg.1(without index) Eg.2 (with index)


import pandas as pd1 import pandas as pd1
import numpy as np1 import numpy as np1
data = {'a' : 0., 'b' : 1., 'c' : 2.} data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = pd1.Series(data) s = pd1.Series(data,index=['b','c','d','a'])
print(s) print(s)

Output Output
a 0.0 b 1.0
b 1.0 c 2.0
c 2.0 d NaN
dtype: float64 a 0.0
dtype: float64

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas Series
Create a Series from Scalar
e.g

import pandas as pd1


import numpy as np1
s = pd1.Series(5, index=[0, 1, 2, 3])
print(s)

Output
0 5
1 5
2 5
3 5
dtype: int64
Note :- here 5 is repeated for 4 times (as per no of index)
Visit : python.mykvs.in for regular updates
Python Pandas
Pandas Series
Accessing Data from Series with Position
e.g.
import pandas as pd1
s = pd1.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
print (s[0])# for 0 index position
print (s[:3]) #for first 3 index values
print (s[-3:]) #for last 3 index values
Output
1
a 1
b 2
c 3
dtype: int64
c 3
d 4
e 5
dtype: int64

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas Series
Retrieve Data Using Label (Index)
e.g.

import pandas as pd1


s = pd1.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
print (s[['c','d']])

Output
c 3
d 4
dtype: int64

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas Series
Head function
e.g

import pandas as pd1


s = pd1.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
print (s.head(3))

Output
a 1
b 2
c 3
dtype: int64
Return first 3 elements

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas Series
tail function
e.g

import pandas as pd1


s = pd1.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
print (s.tail(3))

Output
c 3
d 4
e 5
dtype: int64
Return last 3 elements

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas Series
Vectorized operations with Series
e.g.
import pandas as pd1
s = pd1.Series([1,2,3])
t = pd1.Series([1,2,4])
u=s+t #addition operation 0 2
print (u) 1 4
2 7
u=s*t # multiplication operation dtype: int64
print (u) output
0 1
1 4
2 12
dtype: int64

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas DataFrame
It is a two-dimensional data structure, just like any table
(with rows & columns).
Basic Features of DataFrame
 Columns may be of different types
 Size can be changed(Mutable)
 Labeled axes (rows / columns)
 Arithmetic operations on rows and columns
Structure

Rows

It can be created using constructor


pandas.DataFrame( data, index, columns, dtype, copy)
Visit : python.mykvs.in for regular updates
Python Pandas
Pandas DataFrame
Create DataFrame
It can be created with followings
 Lists
 dict
 Series
 Numpy ndarrays
 Another DataFrame

Create an Empty DataFrame


e.g.

import pandas as pd1 Empty


df1 = pd1.DataFrame() output DataFrame
Columns: [ ]
print(df1) Index: [ ]

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas DataFrame
Create a DataFrame from Lists
e.g.1 0
import pandas as pd1 0 1
data1 = [1,2,3,4,5] output 1 2
2 3
df1 = pd1.DataFrame(data1) 3 4
print (df1) 4 5

e.g.2
import pandas as pd1
data1 = [['Freya',10],['Mohak',12],['Dwivedi',13]]
Name Age
df1 = pd1.DataFrame(data1,columns=['Name','Age'])
0 Freya 10
print (df1) output 1 Mohak 12
2 Dwivedi 13

Write below for numeric value as float


df1 = pd1.DataFrame(data,columns=['Name','Age'],dtype=float)
Visit : python.mykvs.in for regular updates
Python Pandas
Pandas DataFrame
Create a DataFrame from Dict of ndarrays / Lists
e.g.1
import pandas as pd1
data1 = {'Name':['Freya', 'Mohak'],'Age':[9,10]}
df1 = pd1.DataFrame(data1)
print (df1)

Output
Name Age
0 Freya 9
1 Mohak 10

Write below as 3rd statement in above prog for indexing


df1 = pd1.DataFrame(data1, index=['rank1','rank2','rank3','rank4'])

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas DataFrame
Create a DataFrame from List of Dicts
e.g.1

import pandas as pd1


data1 = [{'x': 1, 'y': 2},{'x': 5, 'y': 4, 'z': 5}]
df1 = pd1.DataFrame(data1)
print (df1)

Output
x y z
0 1 2 NaN
1 5 4 5.0

Write below as 3rd stmnt in above program for indexing


df = pd.DataFrame(data, index=['first', 'second'])

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas DataFrame
Create a DataFrame from Dict of Series
e.g.1
import pandas as pd1
d1 = {'one' : pd1.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd1.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df1 = pd1.DataFrame(d1)
print (df1)
Output
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4
Column Selection -> print (df ['one'])
Adding a new column by passing as Series: ->
df1['three']=pd1.Series([10,20,30],index=['a','b','c'])
Adding a new column using the existing columns values
df1['four']=df1['one']+df1['three']
Visit : python.mykvs.in for regular updates
Python Pandas
Pandas DataFrame
Column Deletion
del df1['one'] # Deleting the first column using DEL function
df.pop('two') #Deleting another column using POP function

Row Selection, Addition, and Deletion


#Selection by Label
import pandas as pd1
d1 = {'one' : pd1.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd1.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df1 = pd1.DataFrame(d1)
print (df1.loc['b'])

Output
one 2.0
two 2.0
Name: b, dtype: float64

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas DataFrame
#Selection by integer location
import pandas as pd1
d1 = {'one' : pd1.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd1.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df1 = pd1.DataFrame(d1)
print (df1.iloc[2])

Output
one 3.0
two 3.0
Name: c, dtype: float64

Slice Rows : Multiple rows can be selected using ‘ : ’ operator.


print (df1[2:4])

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas DataFrame
Addition of Rows
import pandas as pd1

df1 = pd1.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])


df2 = pd1.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])

df1 = df1.append(df2)
print (df1)

Deletion of Rows
# Drop rows with label 0
df1 = df1.drop(0)

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas DataFrame
Iterate over rows in a dataframe
e.g.
import pandas as pd1
import numpy as np1
raw_data1 = {'name': ['freya', 'mohak'],
'age': [10, 1],
'favorite_color': ['pink', 'blue'],
'grade': [88, 92]}
df1 = pd1.DataFrame(raw_data1, columns = ['name', 'age',
'favorite_color', 'grade'])
for index, row in df1.iterrows():
print (row["name"], row["age"])

Output
freya 10
mohak 1

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas DataFrame
Using itertuples:
e.g.
for row in df1.itertuples(index=True, name='Pandas'):
print (getattr(row, "name"), getattr(row, "age"))

Output
freya 10
mohak 1

modify the rows iterating over


def valuation_formula(x):
return x * 0.5

df1['age_half'] = df1.apply(lambda row: valuation_formula(row['age']), axis=1)

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas DataFrame
Binary operation over dataframe with series
e.g.
import pandas as pd
x = pd.DataFrame({0: [1,2,3], 1: [4,5,6], 2: [7,8,9] })
y = pd.Series([1, 2, 3])
new_x = x.add(y, axis=0)
print(new_x)

Output
0 1 2
0 1 4 7
1 4 10 16
2 9 18 27

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas DataFrame
Binary operation over dataframe with datafram
e.g.
import pandas as pd
x = pd.DataFrame({0: [1,2,3], 1: [4,5,6], 2: [7,8,9] })
y = pd.DataFrame({0: [1,2,3], 1: [4,5,6], 2: [7,8,9] })
new_x = x.add(y, axis=0)
print(new_x)

Output
0 1 2
0 2 8 14
1 4 10 16
2 6 12 18
Note :- similarly we can use sub,mul,div functions
Visit : python.mykvs.in for regular updates
Python Pandas
Pandas DataFrame

Handle Right-Side Addition/Subtraction etc.


These functions(starting with ‘r’ like radd,rsub etc)
are only called if the left operand does not support
the corresponding operation. For instance, to
evaluate the expression x-y, where y is an instance
of a class that has an __rsub__() method,
y.__rsub__(x) is called. Note that ternary pow() will
not try calling __rpow__() (the coercion rules would
become too complicated).

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas DataFrame
Handle Right-Side Addition/Subtraction etc.
e.g.
class Commuter:
def __init__(self, val):
self.val = val
def __add__(self, other):
print ('add', self.val, other )
def __radd__(self, other):
print ('radd', self.val, other )
x = Commuter(88)
y = Commuter(99)
x+1 # __add__: instance + noninstance
1+y # __radd__: noninstance + instance
x+y # __add__: instance + instance

Output
add 88 1
radd 99 1
add 88 <__main__.Commuter object at 0x02181370>

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas DataFrame
Handle Right-Side Addition/Subtraction etc.
e.g.
class Commuter:
def __init__(self, val):
self.val = val
def __add__(self, other):
print ('add', self.val, other )
def __radd__(self, other):
print ('radd', self.val, other )
x = Commuter(88)
y = Commuter(99)
x+1 # __add__: instance + noninstance
1+y # __radd__: noninstance + instance
x+y # __add__: instance + instance

Output
add 88 1
radd 99 1
add 88 <__main__.Commuter object at 0x02181370>

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas DataFrame
What does the term “broadcasting” mean in Pandas ?
The term broadcasting comes from numpy, simply put
the output that will result when we perform operations
between n-dimensional arrays (could be panels,
dataframes, series) or scalar values.
e.g.
import pandas as pd
import numpy as np
0 2
s = pd.Series([1,2,3]) 1 4
s=s*2 2 6
print(s) dtype: int64

So what is technically happening here is that the scalar


value has been broadcasted along the same dimensions of
the Series.Same can be done in frame also.
Visit : python.mykvs.in for regular updates
Python Pandas
Pandas DataFrame
What does the term “matching” mean in Pandas ?
Extraction of matching values from series/dataframe.
e.g.
import pandas as pd
data = {'name': ['freya', 'mohak'],
'age': [10,1]}
df = pd.DataFrame(data, columns = ['name', 'age'])
df=df[df['name'].str.contains('ya')]
print(df)

OUTPUT
name age
0 freya 10

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas DataFrame
Filling the missing data
Eg.
import pandas as pd
import numpy as np
raw_data = {'name': ['freya', 'mohak', 'rajesh'],
'age': [42, np.nan, 36 ] }
df = pd.DataFrame(raw_data, columns = ['name',
'age']) name age
print(df) 0 freya 42.0
1 mohak NaN
df['age']=df['age'].fillna(0) 2 rajesh 36.0
print(df) name age
0 freya 42.0
1 mohak 0.0
In above e.g. age of mohak is filled with 0 2 rajesh 36.0

Visit : python.mykvs.in for regular updates


Python Pandas
Pandas DataFrame
Comparing two series
e.g.
import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 10])
print("Greater than:")
print(ds1 > ds2) # compare two series

Output
Greater than:
0 True
1 True
2 True
3 True
4 False
dtype: bool
Visit : python.mykvs.in for regular updates
Python Pandas
Pandas DataFrame
Merging/combining dataframe
e.g.
import pandas as pd
left = pd.DataFrame({
'id':[1,2],
'Name': ['anil', 'vishal'],
'subject_id':['sub1','sub2']})
right = pd.DataFrame(
{'id':[1,2],
'Name': ['sumer', 'salil'],
'subject_id':['sub2','sub4']})
print (pd.merge(left,right,on='id'))
Output
id Name_x subject_id_x Name_y subject_id_y
0 1 anil sub1 sumer sub2
1 2 vishal sub2 salil sub4
Visit : python.mykvs.in for regular updates
Python Pandas
Pandas DataFrame
Merging/combining dataframe(different styles)

pd.merge(left, right, on='subject_id', how='left') #left join


pd.merge(left, right, on='subject_id', how='right') #right join
pd.merge(left, right, how='outer', on='subject_id') #outer join
pd.merge(left, right, on='subject_id', how='inner') # inner join

Visit : python.mykvs.in for regular updates


Chapter 11 :

Informatics
Practices
Data Transfer
Class XI ( As per
CBSE Board)
between CSV
files/SQL DB
& DataFrame

Visit : python.mykvs.in for regular updates


Introduction
 CSV is a file format used to store tabular data, such as
a spreadsheet or database.
 SQL Database files store data in a structured format,
organized into tables and fields.
We can create dataframes out of various input data
formats such as CSV, SQL Database also. Once the
dataframe loaded in Python, we can apply various data
analysis and visualization functions to the dataframe
and turn the dataframe data into valuable information.

Visit : python.mykvs.in for regular updates


Saving A Dataframe As CSV

E.g.

import pandas as pd
raw_data = {'name': ['freya', 'Mohak', 'Dwivedi'],
'age': [9, 2, 36]}
df = pd.DataFrame(raw_data, columns = ['name','age'])
df.to_csv('d:\\myfirstcsvfile.csv')

Above program creates a dataframe with columns name


and age with data under these columns.with the helf of
dataframe function to_csv,this dataframe(df) is being
stored as in 'd:\\myfirstcsvfile.csv’.
Open this file to check that data are stored in it or not.

Visit : python.mykvs.in for regular updates


Reading A CSV file into Dataframe

E.g.

import pandas as pd
df = pd.read_csv('d:\myfirstcsvfile.csv')
print(df)

In above program read_csv() function is


being used to read the data from
myfirstcsvfile.csv file in dataframe. And
then its(df) contents are being displayed
with the help of print function.

Visit : python.mykvs.in for regular updates


Reading A CSV file into Dataframe

Load a csv with no headers


df = pd.read_csv('d:\myfirstcsvfile.csv‘, header=None)

Load a csv with specifying column names


df = pd.read_csv('d:\myfirstcsvfile.csv‘, names=[‘NAME', ‘AGE')

Load a csv while skipping the top 2 rows


df = pd.read_csv(‘d:\myfirstcsvfile.csv', na_values=sentinels,
skiprows=2)

Visit : python.mykvs.in for regular updates


Data transfer between SQL Databases and Dataframe object

Reading and write of data to and from Python Pandas


Dataframe object is possible.Data can be permanently store in
databases using data transfer from dataframe object to
database and data permanently stored over databases can be
retrieved in dataframe object also.Following most famous
databases interaction with dataframe object is possible.

 Mysql
 SQLite
 SQL Server
 Etc.

Note :- Any of these must be preinstalled over system to


interact with dataframe object,so first install any one of these
over system.

Visit : python.mykvs.in for regular updates


Data transfer between SQL Databases and Dataframe object

Modules required to interact with databases


In order to connect Python to a database we need a driver,
which is a library used to Interact with the database. For
MySQL database, we have such 3 Driver choices:
• MySQL/connector - it is a library provided by the MySQL community.
• MySQLdb - It is a library that connects to MySQL from Python, it is
written in C language and it is free and open source software
• PyMySQL
To read and write data in mysql database following two
modules must be installed on our system.
• sqlalchemy – It is an open source SQL toolkit and object-
relational mapper (ORM) for the Python programming
language.it was released under the MIT License in year
2006.
• pymysql - This is a library that connects to MySQL from
Python and it is a pure Python library. PyMySQL's goal is to
replace MySQLdb and work on CPython, PyPy and
IronPython.
Visit : python.mykvs.in for regular updates
Data transfer between SQL Databases and Dataframe object

• How to install sqlalchemy in python


Open command prompt in windows(latest version of python
must be preinstalled over your system).
-in windows search option type cmd press enter.
-command window will open
-type pip install sqlalchemy
-wait for installation ,at last ‘successful installation’ message will
appear

• How to install sqlalchemy in anaconda


-Click start->all programs->anaconda->right click over anaconda
prompt->select run as administrator->presss yes
-now anaconda prompt window will open
-now type conda install sqlalchemy
-wait for installation ,(if prompt for overwrite press ‘y’),at last
‘successful installation’ message will appear.

Visit : python.mykvs.in for regular updates


Data transfer between SQL Databases and Dataframe object

• How to install pymysql in python


-in windows search option type cmd press enter.
-command window will open
-type pip install pymysql
-wait for installation ,at last ‘successful installation’ message will
appear

• How to install pymysql in anaconda


-Click start->all programs->anaconda->right click over anaconda
prompt->select run as administrator->presss yes
-now anaconda prompt window will open
-now type conda install pymysql
-wait for installation ,(if prompt for overwrite press ‘y’),at last
‘successful installation’ message will appear.

Visit : python.mykvs.in for regular updates


Data transfer between SQL Databases and Dataframe object

• How to read data from mysql database

First of all we must have created database and table in mysql and
posses following.
• Username
• Password
• Server name(path)/localhost
• Database name
• Table name

Visit : python.mykvs.in for regular updates


Data transfer between SQL Databases and Dataframe object

• How to read data from mysql database to dataframe

Now create a python program like a.py and save with following code.
import pandas as pd
from sqlalchemy import create_engine
cnx = create_engine('mysql+pymysql://root:root@localhost:3306/bank').connect()
sql = 'select * from bmaster'
df = pd.read_sql(sql, cnx)
print(df)

username password servername databasename


port no
Change the username,password,database name and table name according to
your system and run the program.
System will show the data available in the table.

Visit : python.mykvs.in for regular updates


Data transfer between SQL Databases and Dataframe object

• How to create table/write/append data to mysql


table/database from dataframe
Now create a python program like b.py and save with following code.
import pandas as pd
from sqlalchemy import create_engine
cnx = create_engine('mysql+pymysql://root:root@localhost:3306/bank').connect()
data = [['Freya',10],['Mohak',12],['Rajesh',13]]
df = pd.DataFrame(data,columns=['Name','Age'])
df.to_sql(name = 'bmaster', con = cnx, if_exists = 'replace', index = False) #create table & write data
data = [['dwivedi',10]]
df = pd.DataFrame(data,columns=['Name','Age']) Append record
df.to_sql(name = 'bmaster', con = cnx, if_exists = 'append', index = False)

tablename

Change the username,password,database name and table name according to


your system and run the program.
System will drop the previous table and create new table and insert data of
dataframe.

Visit : python.mykvs.in for regular updates


Data transfer between SQL Databases and Dataframe object
SQLite –
It is a self-contained, high-reliability, embedded, full-featured, public-
domain, SQL database engine. SQLite is the most used database engine
in the world.
SQLite Features–
• Transactions are atomic, consistent, isolated, and durable (ACID)
• Zero-configuration - no setup or administration needed.
• Full-featured SQL implementation with advanced capabilities like
partial indexes, indexes on expressions, JSON, and common table
expressions. (Omitted features)
• A complete database is stored in a single cross-platform disk file.
• Supports terabyte-sized databases and gigabyte-sized strings,blobs.
• Small code ,Simple, easy to use API.
• Fast: In some cases, SQLite is faster than direct filesystem I/O
• Written in ANSI-C. TCL bindings included. Bindings for dozens of
other languages available separately.
• Cross-platform: Android, *BSD, iOS, Linux, Mac, Solaris, VxWorks,
and Windows (Win32, WinCE, WinRT) are supported out of the box.
Easy to port to other systems.
Visit : python.mykvs.in for regular updates
Data transfer between SQL Databases and Dataframe object
SQLite Download–
1. First, go to the https://www.sqlite.org/index.html website.
2. Second, open the download page https://www.sqlite.org/download.html
To work with SQLite on Windows, we can download the command-line shell
program as shown in the screenshot below

The downloaded file is in the ZIP format and its size is quite small

Visit : python.mykvs.in for regular updates


Data transfer between SQL Databases and Dataframe object
Install SQLite–
Installing SQLite is simple.
• First, create a new folder e.g., C:\sqlite.
• Second, extract the content of the file that we have downloaded in the
previous section to the C:\sqlite folder.

To verify the installation


First, open the command line window and navigate to the C:\sqlite folder.
c:\cd c:\sqlite
c:\sqlite>
c:\sqlite>sqlite3
SQLite version 3.23.0 2018-06-02 12:04:16
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite>

Visit : python.mykvs.in for regular updates


Data transfer between SQL Databases and Dataframe object
Create database in SQLite
Type following command
c:\sqlite>sqlite3 test.db
After successfully completion of above command, test.db database will be
created.
Create table in SQLite
c:\sqlite>create table first(a int,b string)
After successfully completion of above command, table named first will be
created in test.db database.
How to show list of tables
c:\sqlite>.tables
just type .tables ,it will show the list of tables of currently opened databases
How to insert record
c:\sqlite>insert into first(a,b) values (1,”mohak”);
How to display records
c:\sqlite>select * from first;

Visit : python.mykvs.in for regular updates


Data transfer between SQL Databases and Dataframe object
Install SQLite GUI tool
There are many GUI tools for managing SQLite databases available
ranging from a freeware to commercial licenses.
The SQLite studio is free, portable, intuitive, and cross-platform GUI. It
also provides some of the most important features to work with SQLite
databases such as importing, exporting data in various formats
including CSV, XML, and JSON.

Download it from https://sqlitestudio.pl/index.rvt

• After installation of it open add database option from database menu.


• Select the database test we have already created through dialogbox.
• Now database will be shown in the left pane of databased.
• Now we can type sqlite queries in query window to create table and
add/delete/edit records.

Visit : python.mykvs.in for regular updates


Data transfer between SQL Databases and Dataframe object

Read data from SQLite database


Copy the test.db to the folder where python program will be created to
read its data.following is a python program to read table data.
import sqlite3
conn = sqlite3.connect("test.db")
cur = conn.cursor()
cur.execute("select * from first;")
results = cur.fetchall()
print(results)

Write data to SQLite database


import sqlite3
conn = sqlite3.connect("test.db")
cur = conn.cursor()
cur.execute("insert into first(a,b) values (2,'freya')")
conn.commit()
cur.close()
conn.close()

Visit : python.mykvs.in for regular updates


Chapter 12 :

Informatics
Practices
Class XI ( As per Relational
CBSE Board) Database
New
Concepts
Syllabus
2018-19

Visit : python.mykvs.in for regular updates


DATABASE CONCEPTS
A database is a collection of DATA/INFORMATION that
is organized so that it can be easily accessed,
managed and updated.
In Database ,Data is organized into rows, columns and
tables, and it is indexed to make it easier to find
relevant information. It works like a container which
contains the various object like Tables, Queries,
Reports etc. in organized way.

Visit : python.mykvs.in for regular updates


WHY DO WE NEED DATABASE

 To manage large chunks of data: if size of data increases into


thousands of records, it will simply create a problem to
manage.Database can manage large amount of data.
 Accuracy: Through validation rule in database ,data
accuracy can be maintained.
 Ease of updating data: With the database, we can flexibly
update the data according to our convenience. Moreover,
multiple people can also edit data at same time.
 Security of data: With databases we have security groups
and privileges to restrict access.
 Data integrity: In databases, we can be assured of accuracy
and consistency of data due to the built in integrity checks
and access controls.

Visit : python.mykvs.in for regular updates


DBMS

Database Management System(DBMS)

A DBMS refers to a software that is responsible for


storing, maintaining and utilizing database in an
efficient way.
A Database along with DBMS software is called
Database System.
Example of DBMS software are Oracle, MS SQL
Server, MS Access, Paradox, DB2 and MySQL etc.
MySQL is open source and freeware DBMS.

Visit : python.mykvs.in for regular updates


DBMS
Advantages of Database System
Databases reduces Redundancy
It removes duplication of data because data are kept at one place and
all the application refers to the centrally maintained database.
Database controls Inconsistency
When two copies of the same data do not agree to each other, then it
is called Inconsistency. By controlling redundancy, the inconsistency
is also controlled.
Database facilitate Sharing of Data
Data stored in the database can be shared among several users.
Database ensures Security
Data are protected against accidental or intentional disclosure to
unauthorized person or unauthorized modification.
Database maintains Integrity
It enforces certain integrity rules to insure the validity or correctness
of data. For ex. A date can’t be like 31/31/2000.

Visit : python.mykvs.in for regular updates


DBMS
Data Model- Way of data representation
Data model is a model or presentation which shows How data is
organized ? or stored in the database. A data is modeled by one of
the following given-
Relational Data Model
In this model data is organized into Relations or Tables (i.e. Rows and
Columns). A row in a table represents a relationship of data to each other
and also called a Tuple or Record. A column is called
Attribute or Field.
Network Data Model
In this model, data is represented by collection of records and
relationship among data is shown by Links.
Hierarchical Data Model
In this model, Records are organized as Trees. Records at top level is
called Root record and this may contains multiple directly linked
children records.
Object Oriented Data Model
In this model, records are represented as a objects. The collection of
similar types of object is called class.
Visit : python.mykvs.in for regular updates
RELATIONAL DATABASE
A relational database is a collective set of multiple
data sets organized by tables, records and columns.
Relational database establish a well-defined
relationship between database tables. Tables
communicate and share information, which
facilitates data searcheability, organization and
reporting.
A Relational database use Structured Query
Language (SQL), which is a standard user
application that provides an easy programming
interface for database interaction.

Visit : python.mykvs.in for regular updates


RELATIONAL DATABASE TERMS

Visit : python.mykvs.in for regular updates


RELATIONAL DATABASE TERMS
Relation (Table)
A Relation or Table is Matrix like structure arranged in Rows
and Columns. It has the following properties-
Atomicity : Each column assigned a unique name and must
have atomic(indivisible) value i.e. a value that can not be further
subdivided.
No duplicity: No two rows of relation will be identical i.e. in any
two rows value in at least one column must be different.
All items in a column are homogeneous i.e.same data type.
Ordering of rows and column is immaterial.
 Domain :It is collection of values from which the value is
derived for a column.
 Tuple / Entity / Record - Rows of a table is called Tuple or
Record.
 Attribute/ Field- Column of a table is called Attribute or Field.
 Degree - Number of columns (attributes) in a table.
 Cardinality - Number of rows (Records) in a table.
Visit : python.mykvs.in for regular updates
KEYS IN A DATABASE
Key plays an important role in relational database; it is
used for identifying unique rows from table & establishes
relationship among tables on need.
Types of keys in DBMS
Primary Key – A primary is a column or set of columns in
a table that uniquely identifies tuples (rows) in that table.
Candidate Key –It is an attribute or a set of attributes or
keys participating for Primary Key, to uniquely identify
each record in that table.
Alternate Key – Out of all candidate keys, only one gets
selected as primary key, remaining keys are known as
alternate or secondary keys.
Foreign Key – Foreign keys are the columns of a table that
points to the primary key of another table. They act as a
cross-reference between tables.
Visit : python.mykvs.in for regular updates
KEYS IN A DATABASE

Visit : python.mykvs.in for regular updates


Chapter 13 :

Informatics
Practices
Class XI ( As per
CBSE Board)
SQL
Commands
New
Syllabus
2018-19

Visit : python.mykvs.in for regular updates


SQL
SQL is an acronym of Structured Query Language.It
is a standard language developed and used for
accessing and modifying relational databases.
The SQL language was originally developed at the
IBM research laboratory in San José, in connection
with a project developing a prototype for a relational
database management system called System R in the
early 70s.
SQL is being used by many database management
systems. Some of them are:
 MySQL
 PostgreSQL
 Oracle
 SQLite
 Microsoft SQL Server
Visit : python.mykvs.in for regular updates
MYSQL
MySQL is currently the most popular open
source database software. It is a multi-user,
multithreaded database management system.
MySQL is especially popular on the web. It is
one of the parts of the very popular LAMP
platform. Linux, Apache, MySQL and PHP or
WIMP platform Windows,Apache,MySQL and
PHP.
MySQL AB was founded by Michael Widenius
(Monty), David Axmark and Allan Larsson in
Sweden in year 1995.

Visit : python.mykvs.in for regular updates


MYSQL
MySQL Features
Open Source & Free of Cost:
It is Open Source and available at free of cost.
Portability:
Small enough in size to instal and run it on any types of
Hardware and OS like Linux,MS Windows or Mac etc.
Security :
Its Databases are secured & protected with password.
Connectivity
Various APIs are developed to connect it with many
programming languages.
Query Language
It supports SQL (Structured Query Language) for handling
database.

Visit : python.mykvs.in for regular updates


MYSQL
Types of SQL Commands
 DDL (Data Definition Language)
To create database and table structure-commands
like CREATE , ALTER , DROP etc.
 DML (Data Manipulation Language)
Record/rows related operations.commands like
SELECT...., INSERT..., DELETE..., UPDATE.... etc.
 DCL (Data Control Language)
Used to control the transactions.commands like
COMMIT, ROLLBACK, SAVEPOINT etc.
 Transactional control Language.
used to manipulate permissions or access
rights to the tables.commands like GRANT , REVOKE
etc.

Visit : python.mykvs.in for regular updates


MYSQL
MySql datatypes
numeric
decimal -decimal(<precision>, [<scale>]) [zerofill] For storing
floating-point numbers where precision is critical.
Int - int(<size>) [auto_increment] [unsigned] [zerofill]
A whole number, 4 bytes, with a maximum range of -2,147,483,648 to
2,147,483,647 (unsigned: 0 to 4,294,967, 295)
string
char-char(<size>) [binary]
Fixed length – for storing strings that won't vary much in size.
Range of 0 to 255, stores that amount in bytes
Varchar-varchar(<size>) [binary]
Variable length – for storing strings that will vary in size.
Range of 0 to 255, stores that amount in bytes, plus 1 byte
date
Date-Format: YYYY-MM-DD ,Example: 2006-09-23,Range of years
1000 to 9999

Visit : python.mykvs.in for regular updates


MYSQL
Database Commands in MySql
Getting listings of database and tables
mysql> SHOW DATABASES;
mysql> SHOW TABLES;
Creating a database-
mysql> CREATE database myschool;
Deleting a database mysql> DROP database abc;
database;to remove table mysql> drop table abctable;
After we have created the database we use the USE statement to
change the current
mysql> USE myschool;
Creating a table in the database is achieved with CREATE table
statement.
mysql> CREATE TABLE student (lastname varchar(15),firstname
varchar(15), city varchar(20), class char(2));
The command DESCRIBE is used to view the structure of a table.
mysql> DESCRIBE student;
Visit : python.mykvs.in for regular updates
MYSQL
Database Commands in MySql
To insert new rows into an existing table use the INSERT
command:
mysql>INSERT INTO student values(‘dwivedi’,’freya’,’Udaipur’,’4’);
Similarly we can insert multiple records.With the SELECT
command we can retrieve previously inserted rows:
mysql> SELECT * FROM student;
Selecting rows by using the WHERE clause in the SELECT
command
mysql> SELECT * FROM student WHERE class=“4";
Selecting specific columns(Projection) by listing their names
mysql> SELECT first_name, class FROM student;
To modify or update entries in the table use the UPDATE
command
mysql> UPDATE student SET class=“V" WHERE
firstname=“freya";
Visit : python.mykvs.in for regular updates
MYSQL
Database Commands in MySql
Deleting selected rows from a table using the DELETE
command
mysql> DELETE FROM student WHERE firstname=“amar";
A general form of SELECT is:
SELECT what to select(field name)
FROM table(s)
WHERE condition that the data must satisfy;
Comparison operators are: < ; <= ; = ; != or <> ; >= ; >
Logical operators are: AND ; OR ; NOT
Comparison operator for special value NULL: IS
mysql> SELECT * FROM Student WHERE City IS NULL ;

Visit : python.mykvs.in for regular updates


MYSQL
Database Commands in MySql
Pattern Matching – LIKE Operator
A string pattern can be used in SQL using the following wild
card
% Represents a substring in any length
_ Represents a single character
Example:
‘A%’ represents any string starting with ‘A’ character.
‘_ _A’ represents any 3 character string ending with ‘A’.
‘_B%’ represents any string having second character ‘B’
‘_ _ _’ represents any 3 letter string.
A pattern is case sensitive and can be used with LIKE operator.
mysql> SELECT * FROM Student WHERE Name LIKE ‘A%’;
mysql> SELECT * FROM Student WHERE Name LIKE%Singh%’;
mysql> SELECT Name, City FROM Student WHERE Class>=8
AND Name LIKE ‘%Kumar%’ ;
Visit : python.mykvs.in for regular updates
MYSQL
Database Commands in MySql
Ordering Query Result – ORDER BY Clause
A query result can be orders in ascending (A-Z) or
descending (Z-A) order as per any column. Default is
Ascending order.
mysql> SELECT * FROM Student ORDER BY class;
To get descending order use DESC key word.
mysql> SELECT * FROM Student ORDER BY class
DESC;

Visit : python.mykvs.in for regular updates


MYSQL
Database Commands in MySql
Creating Table with Constraints
The following constraints are commonly used in SQL:
NOT NULL -It Ensures that a column cannot have a NULL
value
UNIQUE - It Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE.
Uniquely identifies each row in a table
FOREIGN KEY - It Uniquely identifies a row/record in another
table
CHECK - It Ensures that all values in a column satisfies a
specific condition
DEFAULT - It Sets a default value for a column when no value
is specified
INDEX - It is Used to create and retrieve data from the
database very quickly
Visit : python.mykvs.in for regular updates
MYSQL
Database Commands in MySql
Creating Table with Constraints
mysql> CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT ‘Jaipur',
CONSTRAINT CHK_Person CHECK (Age>=18)
);
mysql> CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(ID)
);

Visit : python.mykvs.in for regular updates


MYSQL
Database Commands in MySql
MySQL - INDEXES
Indexes are used to retrieve data from the database very
fast. The users cannot see the indexes, they are just
used to speed up searches/queries.
The INSERT and UPDATE statements take more time on
tables having indexes, whereas the SELECT statements
become fast on those tables. The reason is that while
doing insert or update, a database needs to insert or
update the index values as well.
CREATE INDEX
Creates an index on a table. Duplicate values are
allowed:
mysql> CREATE INDEX idx_lastname
ON Persons (LastName);
Visit : python.mykvs.in for regular updates
MYSQL
Database Commands in MySql
MySQL – INDEXES
CREATE UNIQUE INDEX
Creates a unique index on a table. Duplicate values are
not allowed:
mysql> CREATE UNIQUE INDEX idx_lastname
ON Persons (LastName);
DROP INDEX Statement
The DROP INDEX statement is used to delete an index in
a table.
mysql> ALTER TABLE table_name
DROP INDEX index_name;

Visit : python.mykvs.in for regular updates


MYSQL

Database Commands in MySql


MySQL JOINS

In MySQL JOINS are used with SELECT statement. It is used


to retrieve data from multiple tables.

There are three types of MySQL joins:

1. MySQL INNER JOIN (or sometimes called simple join)


2. MySQL LEFT OUTER JOIN (or sometimes called LEFT JOIN)
3. MySQL RIGHT OUTER JOIN(or sometimes called RIGHT JOIN)

Visit : python.mykvs.in for regular updates


MYSQL
Database Commands in MySql
1. MySQL Inner JOIN (Simple Join)
It return all rows from multiple tables where the join
condition is satisfied.

mysql> SELECT columns


FROM table1
INNER JOIN table2
ON table1.column = table2.column;

Visit : python.mykvs.in for regular updates


MYSQL
Database Commands in MySql
2. MySQL Left Outer Join
It returns all rows from the left hand table specified in the
ON condition and only those rows from the other table
where the join condition is fulfilled.

mysql> SELECT columns


FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
Visit : python.mykvs.in for regular updates
MYSQL
Database Commands in MySql
2. MySQL Right Outer Join
It returns all rows from the right hand table specified in the
ON condition and only those rows from the other table
where the join condition is fulfilled.

mysql> SELECT columns


FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
Visit : python.mykvs.in for regular updates
Chapter 14 :

Informatics
Practices
Class XI ( As per Cyber
CBSE Board) Safety

New
Syllabus
2018-19

Visit : python.mykvs.in for regular updates


Introduction-Cyber Safety
Cyber safety is the safe and responsible use of Internet
& ICT(Information & Communication Technology).
Cyber safety is about to not only keeping information
safe and secure, but also being responsible with that
information, being respectful of other people online. As
per Cyber safety peoples are advised to use good
'netiquette' (internet etiquettes).

Visit : python.mykvs.in for regular updates


Safely Browsing the Web
Viruses and malware spread, easily and quickly through
websites/web browsing. Through clicking over the links found on
web pages or in email mistakenly our computer may be infected.
An infected computer can run slow, barrage us with pop-ups,
download other programs without our permission, or allow our
sensitive personal information to others.
Tips for Safe Web Browsing
 Common sense-(never respond to spam & disclose
personal information).
 Use an antivirus & Firewall-It provide realtime malware
protection.
 Create strong passwords
 Mind your downloads -Be sure to review all pre-checked
boxes prompted at download & un-check any extra
applications which we don’t want to install.
 Stay updated- Update O.S.,Applications & Anti-virus.
Visit : python.mykvs.in for regular updates
Identity Protection
Protection against theft of personal information over Cyber
Space without consent, usually for financial gain is known as
Identity Protection.
Tips to Prevent Identity Theft
 Use strong passwords and PINs & Keep passwords and
PINs safe.
 Create log-in passwords for all devices.
 Beware of phishing scams.
 Restore old computers to factory settings.
 Encrypt your hard drive
 Check security when shopping online-check links authenticity
which are received from an unsolicited email.
 Take care when posting on social media-Check security settings
on social media accounts, and avoid posting personal information publicly, or
publicly "checking in" .
 Secure your home Wi-Fi network& Avoid using insecure public Wi-Fi
networks
Visit : python.mykvs.in for regular updates
Confidentiality of Information
Allows authorized users to access sensitive and secured
data maintains the Confidentiality of Information.
Tips to Protect Information Confidential
 Build strong passwords
 Use multifactor authentication- a computer user is granted access
only after successfully presenting 2 or more pieces of evidence.
 Masking -The free version of MaskMe creates an alternate e-mail address
whenever a Web site asks for a user’s e-mail. E-mails from that site can be
accessed via a MaskMe in-box or forwarded to a user’s regular e-mail account.
 Private Browsing & Safe Browsing-Purpose of pvt browsing is to
avoid leaving a history of one's browsing in the browser history on the
computer we are using.Use updated brower for safe browsing & browse privately.
 Encryption-Use https based sites,as HTTPS ensures data security over the
network - mainly public networks like Wi-Fi. HTTP is not encrypted and is
vulnerable to attackers. PGP is a popular program used to encrypt and
decrypt email over the Internet, as well as authenticate messages with digital
signatures and encrypted stored files.
 Avoide using public wifi and public computer
Visit : python.mykvs.in for regular updates
Cyber Safety – Social Networks
Facebook, MySpace, Twitter, LinkedIn, Digg,Ning, MeetUp
etc….. -- the number of social networking sites and tools is
exploding nowadays.These are becoming soft tool to attack
& target for scam.

Tips to stay safe on social media


 Use a strong password
 Use a different password for each social media
 Password protect your devices if using social media apps
 Be selective with friend requests.
 Be careful while sharing something.
 Become familiar with the privacy policies of the social
media sites.
 Install antivirus
 log off when done
 Create a smaller social network
Visit : python.mykvs.in for regular updates
Cyber trolls & Cyber bullying
Cyber trolling is internet slang for a person who
intentionally starts arguments or upsets others by posting
inflammatory remarks. The sole purpose of trolling is
angering people. Purpose – to entertain,to argument,to
upset victim,to get attention

Cyberbulling: Saying and/or doing mean things to the


person online. It is a harm inflicted through using the
Internet,ICT devices,or mobile phones. Purpose – to get
revenge,to harass & threat, to humiliate

Cyberstalking: Doing research on every aspect of the


person’s life.
Cyberharrassment: Continuously contacting the person
online, even though they don’t want you to.

Visit : python.mykvs.in for regular updates


Appropriate Usage of Social Network
Social Network refers to web and mobile technologies or
their practices to share content, thoughts, ideas, opinions,
experiences etc. online. Various examples of social
networks are Facebook, Twitter, YouTube, LinkedIn, and
blogging sites among many others.

Visit : python.mykvs.in for regular updates


Appropriate Usage of Social Network
Problems to Avoid
 Cyber trolling
 Cyberbulling
 Cyberstalking
 Cyberharrassment
 Stranger Danger-
Children's are advised to not to interact with strangers on
social networks as there are chances that many people on
social media are not who they say they are.
 Digital Footprint-
The history of a person's usage of digital devices, movie
search, programs watched, flight searched, websites
surfed, credit card transaction,cell phone calls,social
media messages sent, links clicked and Facebook pages
liked etc.Such information is being used to target ads to
consumers as these are digital footprint of such
consumers.

Visit : python.mykvs.in for regular updates


Appropriate Usage of Social Network
Problems to Avoid
 Spread of rumors -
A lie can travel halfway around the world before the truth has
got its boots, this phrase totally fits with rumors spread over social
media. On average, it takes more than 12 hours for a false claim to be
debunked online where as only 2 hours for true claim.
A standard model of rumor spreading is given by Daley and
Kendall ,which is called DK model.In this model there are N people in
total. Which are categorized into three groups: ignorants, spreaders
and stiflers, which are denoted as S, I, and R.

when a spreader meet an ignorant, the ignorant will become a


spreader.
when two spreaders meet with each other, one of them will
become a stifler.
when a spreader meet a stifler, the spreader will lose the
interest in spreading the rumor, so become a stifler.
So
Visit : python.mykvs.in for regular updates
Appropriate Usage of Social Network

 Don’t be rude or abusive


 Don’t spread rumors
 You are what you write/tweet
 Face your problems, don’t Post/facebook your
problems.
 Don’t take it too seriously.
 Don’t use fake name
 Protect your identity
 Respect other’s sentiments
 Don’t fight online
 Monitor comments

Visit : python.mykvs.in for regular updates


Computer Security Threats
Malware: Malware could be computer viruses, worms, Trojan horses,
dishonest spyware, and malicious .
computer virus: It is a small piece of software that can spread from one
infected computer to another. It can corrupt, steal, or delete data on your
computer/hard drive.
Trojan horse: can do anything from record your passwords by logging
keystrokes (known as a keylogger) to hijacking your webcam to watch
and record your every move.
Computer worm: A computer worm is a software program that can copy
itself from one computer to another, without human interaction.
Spam: unwanted messages in your email inbox.
Phishing:Phishing are fraudulent attempts by cybercriminals to obtain
private information. For e.g.a message prompt your personal information
by pretending that bank/mail service provider is updating its website.
spyware: spyware is used to spy on their victims. An e.g. is keylogger
software that records a victim’s every keystroke on his or her keyboard.
Adware : unwanted ads shown while surfing internet.
Eavesdropping : is the act of intercepting communications between two
points.

Visit : python.mykvs.in for regular updates


Safely accessing web sites

 How to prevent/remove Adware/malware


 Uninstall the malicious programs from Windows
 Use antivirus program for malware and unwanted programs
 Reset the browser settings to their original defaults
 Scan for malicious programs antivirus/antimalware program

 How to prevent/remove virus


 Beware of Fake Download Buttons
 Use a Secure Browser
 Avoid Public Torrent Sites
 Don’t Open Email Attachments Forwarded to You
 Don’t Use Your PC’s Admin Account
 Scan All New Files and Disks

 How to prevent/remove Trojan


 Never open unsolicited emails from unknown senders
 Avoid downloading and installing programs unless you fully trust
publisher
 Use firewall software
 Use a fully updated antivirus program
Visit : python.mykvs.in for regular updates
Safely Communicating data

 Secure Connections
A secure connection refers to the connection which is encrypted by one
or more security protocols for security of data flowing between two or
more nodes. When it is not encrypted, it can be easily listened by
anyone with the knowledge on how to do it.

 Secure Sockets Layer (SSL) is a computer networking protocol used


for insecure network, between network application clients and
servers .Due to various flaws, SSL was deprecated for use on the
internet by the Internet Engineering Task Force (IETF) in 2015 by the
Transport Layer Security (TLS) protocol. Both are not interoperable,
TLS is backwards-compatible with SSL 3.0

Visit : python.mykvs.in for regular updates


Safely Communicating data
Secure Connections
 Transport Layer Security (TLS) encrypts data moving over the
network or Internet to ensure that any body(hacker/evesdropper) will
not be able to see what is transmitting. It is useful for private and
sensitive information such as passwords, credit card numbers, and
personal correspondence.

How it works
TLS uses a combination of symmetric and asymmetric cryptography
both for better security.With symmetric cryptography, data is encrypted
and decrypted with a secret key known to both sender and recipient;
typically 128 but preferably 256 bits in length (anything less than 80
bits is now considered insecure). Symmetric cryptography uses a
common secret key ,which is shared a secure manner.
Asymmetric cryptography uses 2 keys – a public key, and a private key.
The public key of the recipient to be used by the sender to encrypt the
data they wish to send to them, but that data can only be decrypted
with the private key of the recipient.

Visit : python.mykvs.in for regular updates


Safely Communicating data
Secure Connections
 Hyper Text Transfer Protocol Secure (HTTPS) is the secure version
of HTTP, the protocol over which data is sent between your browser
and the website server. HTTPS pages typically use one of two
secure protocols to encrypt communications - SSL (Secure Sockets
Layer) or TLS (Transport Layer Security).

 Eavesdropping-eavesdropping in a man in middle attack and the


message is passing from the client to server. The solutions to this
problem are:
 to encrypt the message
 to encrypt the channel
Both are appropriate in different situations. To prevent
Eavesdropping in any kind of communication channel can be achieved
by usage of "Secure Tunneling" of your channel data.

Visit : python.mykvs.in for regular updates


Safely Communicating data

 Phishing-Phishing are fraudulent attempts by cybercriminals to


obtain private information. For e.g.a message prompt your personal
information by pretending that bank/mail service provider is
updating its website.
There are various phishing techniques used by attackers:
o Embedding a link in an email to redirect to an unsecure website that
requests sensitive information
o Installing a Trojan via a malicious email attachment
o Spoofing the sender’s address in an email to appear as a reputable
source and request sensitive information
o Attempting to obtain information over the phone by impersonating a
known company vendor.
Few steps to protect against phishing-
Deploy a SPAM filter, Keep all systems current with the latest security
patches and updates, Install an antivirus solution, Develop a security
policy, Deploy a web filter to block malicious websites, Encrypt all
sensitive information.

Visit : python.mykvs.in for regular updates


Safely Communicating data
 Identity verification methods
 Knowledge-Based Authentication (KBA)-by asking them to
answer specific security questions
 Two Factor Authentication (2FA)-not only a password and
username, but also something that the user has with them
 Database Solutions-behavioral patterns to detect if an online ID is
authentic, a fraudster or a bot.
 Online Identity Verification-A mix of artificial intelligence, computer vision,
and verification experts to determine if a government-issued ID is
authentic and belongs to the user.
 Biometric verification -by which a person can be uniquely identified by
evaluating one or more distinguishing biological traits.

Visit : python.mykvs.in for regular updates

Você também pode gostar