0% found this document useful (0 votes)
18 views92 pages

Computer Sc. Notes of Class-Xi

Computer Science notes for class 11th (CBSE Syllabus [Sumita Arora])

Uploaded by

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

Computer Sc. Notes of Class-Xi

Computer Science notes for class 11th (CBSE Syllabus [Sumita Arora])

Uploaded by

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

COMPUTER SCIENCE WITH PYTHON

CLASS-XI

AMIT KUMAR KUSHWAHA


HOD (COMPUTER DEPT)

AMIT KUMAR KUSHWAHA Page 1


INDEX

Sl.No Contents
1 Data Representation 3-8

2 Boolean Logic 4-16

3 Getting Started with Python 17-18

4 Python fundamental 19-29

5 Data handling 30-36

6 Flow of control 37-44

7 String Manipulation 45-54

8 Lists Manipulation 55-63

9 Tuples 64-74

10 Dictionaries 75-82

11 Understanding sorting 83-84

12 Cyber Safety / Security / Society Law And 85-92


Ethics

AMIT KUMAR KUSHWAHA Page 2


DATA REPRESENTATION
Number systems are the technique to represent numbers in the computer system architecture,every value that
you are saving or getting into/from computer memory has a defined numbersystem.
Computer architecture supports following number systems

BINARY NUMBER SYSTEM: A Binary number system has only two digits that are 0 and 1. Every number
(value) represents with 0 and 1 in this number system. The base of binary number system is 2, because it has
only two digits.

OCTAL NUMBER SYSTEM: Octal number system has only eight (8) digits from 0 to 7. Every number (value)
representswith 0,1,2,3,4,5,6 and 7 in this number system. The base of octal number system is 8, because it has
only 8 digits.

DECIMAL NUMBER SYSTEM : Decimal number system has only ten (10) digits from 0 to 9. Every
number (value) represents with 0,1,2,3,4,5,6, 7,8 and 9 in this number system. The base of decimal number
system is 10, because it has only 10 digits.

HEXADECIMAL NUMBER SYSTEM :A Hexadecimal number system has sixteen (16) alphanumeric
values from 0 to 9 and A to F. Every number (value) represents with 0,1,2,3,4,5,6, 7,8,9,A,B,C,D,E and F in
this number system. The base of hexadecimal number system is 16, because it has 16 alphanumeric values.
Here A is 10, B is 11, C is 12, D is 14, E is 15 and F is 16.

Number system Base(Radix) Used digits Example

Binary 2 0,1 (11110000)2

Octal 8 0,1,2,3,4,5,6,7 (360)8


Decimal 10 0,1,2,3,4,5,6,7,8,9 (240)10

Hexadecimal 16 0,1,2,3,4,5,6,7,8,9, (F0)16


A,B,C,D,E,F

CONVERSIONS
Decimal Number System to Other Base
To convert Number system from Decimal Number System to Any Other Base is quiteeasy; you have to
follow just two steps:
 Divide the Number (Decimal Number) by the base of target base system (in which youwant to convert
the number: Binary (2), octal (8) and Hexadecimal (16)).
 Write the remainder from step 1 as a Least Signification Bit (LSB) to Step last as a MostSignificant Bit
(MSB).

DECIMAL TO BINARY COVERSION


Taking remainder from MSB to LSB and writing from left to right

AMIT KUMAR KUSHWAHA Page 3


EXMPLE
a) Binary equivalent of (36)10 is (0100100)2

Remainde
r Least Significant Bit (LSB)
0
0
1
0

Most significant Bit (MSB)


b) Binary equivalent of (25.75)10

.75 x 2 = 1.50 1
.50 x 2= 1.00 1

For converting decimal part we have to multiple it with 2 and then


take integer part as remainder as shown in example
Complete answer is (11001.11)2

CONVERSION OF BINARY NUMBER TO DECIMAL


NUMBER SYSTEM

AMIT KUMAR KUSHWAHA Page 4


CONVERSION OF DECIMAL NUMBER TO OCTAL NUMBER SYSTEM

CONVERSION OF OCTAL NUMBER TO DECIMAL NUMBER SYSTEM

CONVERSION OF DECIMAL NUMBER TO HEXADECIMAL NUMBER SYSTEM

AMIT KUMAR KUSHWAHA Page 5


Remainder
8=8 Least significant bit (LSB)
15=F
3=3
1=1

Most significant bit (MSB)

(5112)10=(13F8)16

CONVERSION OF HEXADECIMAL NUMBER TO DECIMAL NUMBER SYSTEM


2 1 0
16 16 16
256 16 1
B 6 E
11*256
+ 6*16
+14*1

= 2816 + 96 + 14
= (2926) 10

CONVERSION OF OCTAL NUMBER TO BINARY NUMBER SYSTEM : 421 COMBINATION

AMIT KUMAR KUSHWAHA Page 6


CONVERSION OF HEXADECIMAL NUMBER TO BINARY NUMBER SYSTEM :
8421 COMBINATION
 Each hexadecimal digit is equivalent to 4 binary
digits.
 For example:-binary equivalent to 2C :-
2 C
= 0010 1100
2C = 001011002(in binary)

CONVERSION OF BINARY NUMBER TO HEXADECIMAL NUMBER SYSTEM


 The binary digits are arranged in groups of 4 starting from the right.
 For example:-Convert 0011 0100 0110 to hexadecimal
0011 0100 0110
3 4 6

CONVERSION OF OCTAL TO HEXADECIMAL NUMBER SYSTEM


 Convert each octal digit to 3-bit binary form
 Combine all the 3 bits binary form
 Divide the binary numbers into the 4-bit binary form
 Convert these 4 bits blocks into their respective hexadecimal symbols

AMIT KUMAR KUSHWAHA Page 7


HEXADECIMAL TO DECIMAL
Convert into a decimal number 42A.11
Solution- Hence the decimal equivalent number is given as:
4 × 162+ 2 ×161 + 10 × 161 + 1 × 16−1 + 1 × 16−2
= 1024 + 32 + 10 + 0.0625 + 0.00390625
= (1066.06640625)10
HEXADECIMAL TO OCTAL
 Given hexadecimal number is A 7 2 E
 Binary equivalent is 1010011100101110
 Forming groups of 3 bits from the LSB 001 010 011 100 101 110
 Octal equivalent 1 2 3 4 5 6
Hence the octal equivalent of (𝐴72𝐸)16 is (123456)8 .
ALPHANUMERIC CODING SCHEME
ASCII- AMERICAN STANDERED CODE OF INFORMATION INCHANGE (7-BIT CODING)
 ASCII CODE OF A-Z – 65-90
 ASCII CODE OF a-z – 97-122
 ASCII CODE OF 0-9 – 48-57
ISCII – INDIAN SCRIPT CODE FOR INFORMATION INTERCHANGE-used for indian languages like
Gurmukhi , devnagri etc

AMIT KUMAR KUSHWAHA Page 8


BOOLEAN LOGIC
INTRODUCTION
 Boolean Logic, also known as Boolean algebra was developed by mathematician “George
Boole”.
 Later, Boolean logic helped in solving many big problems.
 These logics also helped in developing circuits.
 Complete logic is based on Yes or No which is also represented as True(T) or False(F).
 Computer system transmits its signals on high voltage or low voltage which can be denoted by true or
false and with which we can develop it’s circuit.

BINARY VALUES (QUANTITIES)


 The decisions which results in Yes or No only are known asbinary decisions.
 Values T and F are known as truth values.
 Boolean variables can only be either T or F.
LOGICAL OPERATORS
These are of three types -
 AND
 OR X X’
 NOT
NOT OPERATION IT is represented by applying ( ‘ ) or ( ¯ ) on an 0 1
expression. For ex- X’ or X . This is a unary operator also known 1 0
as complementation operator .
– 0’ = 1 and 1’ = 0
X Y X.Y
LOGICAL OPERATORS (AND) 0 0 0
AND operator is used by applying ( . ) between two variables. like
X.Y 0 1 0
It shows a very important operation of boolean algebra which is 1 0 0
known as logical multiplication. Result will be 1 only whenboth 1 1 1
X.Y is to be read as X AND Y the inputs will be 1 otherwise
result will always be 0.

LOGICAL OPERATORS (OR)


OR operator is used by applying ( + ) between two variables. like X+Y
It shows a very important operation of boolean algebra which is known aslogical
addition. X+Y is to be read as X OR Y.
X Y X+Y
0 0 0
0 1 1
1 0 1
1 1 1

AMIT KUMAR KUSHWAHA Page 9


LOGICAL OPERATIONS : the operation or statement which always produce result either in true or false is
called logical operations
Truth Table is a table which contains all possible truth values of logical X Y R
values along with all possibleresults.
1 1 1
When all the results of a Truth Table are true (1) this condition is known
as TAUTOLOGY and if allresults are false (0) then this condition is 1 0 0
known as FALLACY . 0 1 0
0 0 0
EVALUATION OF BOOLEAN EXPRESSION USING TRUTH TABLE
To develop Boolean Expression, logical variables are usedwith logical operators. Truth table is used
for its evaluation. For ex- X + (Y.X)’ + Z’ is a boolean expression and its truth table should be as follows-

X Y Z Y.Z (Y.Z)’ Z’ X+(Y.Z)’ X+(Y.Z)’+Z’

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

Evaluation of Boolean Expression using Truth Table


Prove (X+Y)’ = X’.Y’ using Boolean logic and truth table-

X Y X+Y (X+Y)’ X’ Y’ X’.Y’

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

By comparing (X+Y)’ and X’.Y’ it is proved that both the values are same
BASIC LOGIC GATES
 When Shannon used Boolean logic in switching circuit of telephone then Engineers realized that
Boolean algebra can also be used in computer electronics. In computers, logic gates are used to
complete Boolean operations.
 A Gate is a basic Electronic Circuit used to develop an output signal by passing one or more input
signal(s).
 A Gate is a kind of two-state digital circuit because its input or output are either low voltage (i.e. 0) or
high voltage (i.e.1).
 Gates are also known as logic gates because they can coordinate with Boolean logic.

Logic gates are of three types--


 Inverter (NOT Gate)
 OR Gate
 AND Gate
AMIT KUMAR KUSHWAHA Page 10
INVERTER (NOT GATE) X X’
 NOT gate takes one input and produces one output.
 Its output is exactly opposite to its input. Low High
 It is called NOT gate because its output is not similar to its input.
 Its output is also called as complement(opposite) of input. High Low
Truth table and diagram of Not gate are as under-

X X’

0 1
X X’
1 0

OR Gate
 OR gate takes two or more inputs and produces one output.
 Its output is logical sum of passed inputs.
 It produces high voltage output on any one high voltage input. It produceslow voltage output only
when all the inputs are of low voltage.

OR Gate Truth table and diagram are as under-

X Y X+Y X Y X+Y

Low Low Low 0 0 0

Low High High 0 1 1

High Low High 1 0 1

High High High 1 1 1

– This gate work for more than two input signals in similar manner.

AND GATE
 AND gate takes two or more inputs and produces one output.
 Its output is logical multiplication of passed inputs.
 It produces low voltage output on any of the input signal as low voltage input. It produces high voltage
output only when all the inputs are of high voltage.
AND Gate Truth table and diagram are as under- X Y X.Y
X Y X .Y 0 0 0
0 1 0
Low Low Low
Low High Low 1 0 0
High Low Low 1 1 1
High High High
This gate work for more than two input signals in similar manner.

AMIT KUMAR KUSHWAHA Page 11


BOOLEAN LOGIC-BASIC POSTULATES
Boolean algebra is a kind of mathematical system because of which it is based on some fundamental laws
which are known as basic postulates. Which are as follows- -
If X ≠ 0 then X = 1 and if X ≠ 1 then X = 0
 OR Relations (logical addition)
o 0+0=0
o 0+1=1

o 1+0=1
o 1+1=1
 AND Relations (logical multiplication)
o 0.0=0
o 0.1=0
o 1.0=0
o 1.1=1
 Complementary Rules:
o 0’ = 1
o 1’ = 0
PRINCIPLE OF DUALITY
It is very important concept of Boolean logic. A Boolean relation can be derived by other Boolean relation if
we follow following rules-
 Every OR signal (+) is replaced by AND signal (.).
 Every AND signal (.) is replaced by OR signal (+).
 Every 1 is replaced by 0 and every 0 is replaced by 1.
The received expression will be dual expression of original expression.
For ex-
 Dual of 0 + 0 = 0 will be 1 . 1 = 1
 Dual of 0 + 1 = 1 will be 1 . 0 = 0
 Dual of 1 + 0 = 1 will be 0 . 1 = 0
 Dual of 1 + 1 = 1 will be 1 . 1 = 1
For example dual nature of expression (u’+w)(u.w’)=1 WILL BE (u’.w)+(u+w’)=0

MAIN CONCEPTS OF BOOLEAN ALGEBRA


Properties of 0 and 1

 0+X=X 0 X R
0 0 0
0 1 1
 1+X=1
1 X R
1 0 1
1 1 1
 0.X=0
0 X R
0 0 0
0 1 0

AMIT KUMAR KUSHWAHA Page 12


1 X R
 1.X=X 1 0 0
1 1 1
a) INDEMPOTENCE LAW - (a) X + X = X (b) X . X = X

X X R X X R
0 0 0 0 0 0
1 1 1 1 1 1
b) INVOLUTION – (X’)’ = X
X X’ (X’)’
0 1 0
1 0 1

c) COMPLEMENTARITY LAW – (a) X + X’ = 1 (b) X . X’ = 0

X X’ R X X’ R
0 1 1 0 1 0
1 0 1 1 0 0
d) COMMUTATIVE LAW –
a) X + Y = Y + X (b) X . Y = X . Y
e) X Y X+Y Y+X X Y X.Y Y.X
0 0 0 0 0 0 0 0
0 1 1 1 0 1 0 0
1 0 1 1 1 0 0 0
1 1 1 1 1 1 1 1

d) ASSOCIATIVE LAW –(a) X+(Y+Z) = (X+Y)+Z

X Y Z Y+Z X+Y X+ (Y + Z) (X + Y) + Z
0 0 0 0 0 0 0
0 0 1 1 0 1 1
0 1 0 1 1 1 1
0 1 1 1 1 1 1
1 0 0 0 1 1 1
1 0 1 1 1 1 1
1 1 0 1 1 1 1
1 1 1 1 1 1 1

AMIT KUMAR KUSHWAHA Page 13


(b) X . (Y . Z) = (X . Y) . Z

X Y Z Y.Z X.Y X . (Y . Z) (X . Y) . Z
0 0 0 0 0 0 0
0 0 1 0 0 0 0
0 1 0 0 0 0 0
0 1 1 1 0 0 0
1 0 0 0 0 0 0
1 0 1 0 0 0 0
1 1 0 0 1 0 0
1 1 1 1 1 1 1
e) DISTRIBUTIVE LAW – a) X . (Y + Z) = X.Y + X.Z

X Y Z Y+Z X.Y X.Z X.(Y+Z) X.Y+X.Z

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

1 1 1 1 1 1 1 1

b) X + Y.Z = (X + Y) . (X + Z) Algebraic method

X Y Z Y.Z X+Y X+Z X+Y.Z (X+Y).


(X+Z)
0 0 0 0 0 0 0 0
0 0 1 0 0 1 0 0
0 1 0 0 1 0 0 0
0 1 1 1 1 1 1 1
1 0 0 0 1 1 1 1
1 0 1 0 1 1 1 1
1 1 0 0 1 1 1 1

1 1 1 1 1 1 1 1

AMIT KUMAR KUSHWAHA Page 14


f) Absorption Law – a) X + X . Y = X (b) X . (X + Y) = X

X Y X.Y X+X.Y X Y X+ X.(X+Y)


Y
0 0 0 0
0 1 0 0 0 0 0 0
1 0 0 1 0 1 1 0
1 0 1 1
1 1 1 1
1 1 1 1

g) Third Distributive Law X + X’.Y = X +Y


X Y X’ X’.Y X + X’.Y X+Y
0 0 1 0 0 0
0 1 1 1 1 1
1 0 0 0 1 1
1 1 0 0 1 1
h) DEMORGAN’s Law – (a) (X+Y)’ = X’ . Y’ (b) (X.Y)’ = X’ + Y’

X Y (X+Y)’ X’.Y’ X Y (X.Y)’ X’ + Y’


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

OTHER LOGIC GATES: There are some derived gates also besides AND, OR, NOT Gates. Like-
NOR, NAND, XOR, XNOR Gates.

NOR GATE:
There are two or more input signals and one output signal in NOR gate. If all input signals are 0 (low) then
output signal will be 1 (high).
X Y Z F
X Y F
0 0 1 0 0 0 1
0 0 1 0
0 1 0
0 1 0 0
1 0 0 0 1 1 0
1 1 0
1 0 0 0
NAND Gate
1 0 1 0
There is two or more input signals and one output signal in NAND gate.if all 1 1 0 0
input signals are 1 (high) then output signal will be 0 (low). It is also known as 1 1 1 0
universal gate because fundamental gates can be retrieved with its help

AMIT KUMAR KUSHWAHA Page 15


Y F X Y Z F
0 0 1 0 0 0 1
0 0 1 1
0 1 1
1 0 1 0 1 0 1
0 1 1 1
1 1 0
1 0 0 1
XOR GATE 1 0 1 1
XOR Gate produces 1 (high) when inputs are not at equallogic level. It
is also known as universal gate because fundamental gates can be retrieved with 1 1 0 1
its help. 1 1 1 0

No of 1’s X Y Z F
Even 0 0 0 0
Odd 0 0 1 1
No of 1’s X Y F Odd 0 1 0 1
Even 0 0 0 Even 0 1 1 0
Odd 1 0 0 1
Odd 0 1 1
Even 1 0 1 0
Odd 1 0 1 Even 1 1 0 0
Even 1 1 0 Odd 1 1 1 1

XNOR Gate
XNOR Gate produces 1 (high) when the inputs are identical(both 1’s or both 0’s).
No of 1’s X Y Z F

Even 0 0 0 1

Odd 0 0 1 0
No of 1’s X Y F

Even 0 0 1 Odd 0 1 0 0
Odd 0 1 0
Even 0 1 1 1
Odd 1 0 0
Odd 1 0 0 0
Even 1 1 1
Even 1 0 1 1

Even 1 1 0 1

Odd 1 1 1 0

AMIT KUMAR KUSHWAHA Page 16


INTRODUTION TO PYTHON
INTRODUCTION:
 General-purpose Object Oriented Programming language.
 High-level language
 Developed in late 1980 by Guido van Rossum at National Research Institute for
Mathematics and Computer Science in the Netherlands.
 It is derived from programming languages such as ABC, Modula 3, small talk, Algol-68.
 It is Open Source Scripting language.
 It is Case-sensitive language (Difference between uppercase and lowercase letters).
 One of the official languages at Google.
CHARACTERISTICS OF PYTHON:
 Interpreted: Python source code is compiled to byte code as a .py file, and this bytecode can
be interpreted by the interpreter.
 Interactive
 Object Oriented Programming Language
 Easy & Simple
 Portable
 Scalable: Provides improved structure for supporting large programs.
 Integrated
 Expressive Language
PYTHON INTERPRETER:
Names of some Python interpreters are:
 PyCharm
 Python IDLE
 The Python Bundle
 pyGUI
 Sublime Text etc.
There are two modes to use the python interpreter:
 Interactive Mode
 Script Mode
Interactive Mode: Without passing python script file to the interpreter, directlyexecute code to
Python (Command line).
Example:
>>>6+3
Output: 9

Fig: Interactive Mode

Note: >>> is a command the python interpreter uses to indicate that it is ready.
AMIT KUMAR KUSHWAHA Page 17
Theinteractive mode is better when a programmer deals with small pieces of code.
To run a python file on command line:
exec(open(“C:\Python33\python programs\program1.py”).read( ))
Script Mode: In this mode source code is stored in a file with the .py extension and use the
interpreter to execute the contents of the file. To execute the script by the interpreter, you have to
tell the interpreter the name of the file.
Example:
if you have a file name Demo.py , to run the script you have to follow the followingsteps:
Step-1: Open the text editor i.e. Notepad
Step-2: Write the python code and save the file with .py file extension. (Defaultdirectory is
C:\Python33/Demo.py)
Step-3: Open IDLE ( Python GUI) python shell
Step-4: Click on file menu and select the open option
Step-5: Select the existing python file
Step-6: Now a window of python file will be opened
Step-7: Click on Run menu and the option Run Module.
Step-8: Output will be displayed on python shell window.

Fig. : IDLE (Python GUI)

AMIT KUMAR KUSHWAHA Page 18


PYTHON FUNDAMENTALS

TOKENS : Token – It is the smallest element/unit of Python program

Identifiers The name of any variable, constant, function,


module
Literal A fix numeric or non-numeric value

Operators Symbols that perform some kind of operation (example +, - , * , / )


Category
Token

Symbols which can be used as separators of values or to enclose


Delimiters somevalues (example {} , [] )

Keywords These are reserved words in Python

Token Category
First_Name variable / identifier
X variable / identifier
print Keyword
= Operator / Delimiter
372 Literal
“Python” Literal
[1,2,3,4,5] [] Delimiter

Keywords: Keywords are the reserve words of python which have a special meaning for the interpreter.
We can’t declare then as identifier. They are case sensitive
False True None def if try

lambda class yield continue else except


assert or while break elif raise
del from is not pass with
for global finally import as and
in nonlocal return
IDENTIFIERS: Identifiers are the name given to the different programming elements like variables,
objects,classes, functions, lists, dictionaries etc.
RULES FOR NAMING AN IDENTIFIER
 Identifiers cannot be a keyword.
 Identifiers are case-sensitive.
 It can have a sequence of letters and digits. ...
 It's a convention to start an identifier with a letter rather _ .
 Whitespaces are not allowed.
 We cannot use special symbols like !, @, #, $, and so on.

AMIT KUMAR KUSHWAHA Page 19


Example of valid identifiers: Rollno_no,name,_fees etc
Example of invalid identifiers: 12rollno,roll$no,while
LITERAL: Literals are the data items that have a fixed or constant value
 STRING LITERALS - A string literal is a sequence of characters surrounded by Quotes (Single,
Double or Triple Quotes). For example name = ‘Amit’
 NUMERIC LITERALS are numeric values like integer,floating point or a complex number
 int literal :
 Decimal(base 10) : 124
 Octal (base 8) : O0124
 Hexdecimal (base 16) : ox124
 Floating Point Literals are also called Real Literals
example 1234.56 (floating point literal)
.123456e04 (real literal)
 Boolean literal ; A Boolean literal in Python is used to representone of the two Boolean
Values i.e. True or False
 Special literal None : In python, None literal is used to indicate absence of value. It
doesn’t indicate zero
VARIABLE & TYPES
A variable is like a container that stores values. This value you can
access and change

Variable is used to provide a name to an object(object-every element


X = 150
in Python is termed as an onject)
Variable

VariableX=150 (X here
Example assignment operator
is a variable holding valuevalue
150)

Identity
Variable Components

It refers to the memory location address


This memory location doen not chane once created
id() is used to check the memory location of an
object/variable
Data Type - refers to the data type of value it holds

Value - refers to the vaue it holds


In the below given example:
Variable = X
Identity of variable X = 1482682624
Data Type of X = integer (as it holds integer value)Value of X = 150

AMIT KUMAR KUSHWAHA Page 20


It must start either with alphabet (capital or small) or underscore ( _ )
VARIABLE DECLARATION

It can not start with a number

It can contain only alpha-numeric characters (A-Z, a-z, 0-9)and underscore ( _ )


RULES

Python keywords can not be used as a variable name

It can not contain spaces

Variable names are case-sensitive (name,Name and NAME are 3 different variables)

Valid variable name examples Invalid variable name examples


Student1 1student
_student #Rollno
First_Name First Name
awhile while
DOB D.O.B.

Assigning Value to a Variable

 Assigning same values to multiple variables


Jan, Mar, May, July, Aug, Oct, Dec = 31
 Assigning multiple values to multiple variables
 Jan, Feb, Mar, April, May = 31, 28, 31, 30, 31
A variable is not created until some value is assigned to it
EXPRESSION : An Expression is a combination of operand and operator.
Example: 10 50
operand operator

AMIT KUMAR KUSHWAHA Page 21


Operators
Operators are special symbols which represents computation

Operator
s

Shorthand
Arithmeti Relationa Logica
c l l Assignmen
t

Solve arithmetic or These are and , or , A combination of


algebraic comparison not binary
expression operators and assignment
Arithmetic Operators on Number data

Arithmetic Operators on Number & String data

Relational Operators on Number & String data

AMIT KUMAR KUSHWAHA Page 22


Shorthand Assignment Operators on Number data

Operators Symbols
Arithmetic Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Remainder (%)
Exponent (**)
Integer Division (//)
Relational Less than (<)
Greater than (>)
Less than equal to (<=)
Greater than equal to (>=)Not
equal to (<>) , (!=)
Equal to (==)
Logical And
Or
Not

Shorthand Assignment += , -=, *= , /= ,**=

Data Type
Data
Types

Numbe Sequence Mappin Sets Boolean


r g

Integer / String / Dictionar Set Boolean


Float Tuple y
/ Complex / List

AMIT KUMAR KUSHWAHA Page 23


Data Type

Mutable Immutabl
e
List Integer

Dictionary Float

String

Tuple

Boolean

A mutable object can be changed after it is created, and an immutable object can't
Data Type Definition Examples
Number Integer whole number without fraction 67999, -5677, 564
Float Floating numbers are written with 656.89, -676.5, 895.0
decimal point
Complex Complex numbers are made up of pair 5+7j
of real and imaginary number
Sequence String It represents sequence of charactersenclosed ‘python’ “python”
within quotation marks (single, double or ‘’’python’’’
triple)
Tuple Sequence of objects that cannot be changed (1,2,3,4,5)
(‘a’,’e’,’i’,’o’,’u’)
List Sequence of objects that can be [1,2,3,4,5]
changed [‘a’,’e’,’i’,’o’,’u’]
Mapping Dictionary It is a combination of key and its value {1:’Amita’,2:’Sachin’}
Boolean Boolean Represents one of two possible values – True/False

type() can be used to check the data type of a value that a variable hold

AMIT KUMAR KUSHWAHA Page 24


COMMENTS
 comments are python statement that are ignored by Python interpreter
 comments increase the readability of the code
 comments in Python starts with hash symbol (#) and extends till the end of line
 multiline comments starts with ‘’’ ‘’’

input () User Input


 input () is used to get the input data from user while working with script mode
 input () always returns a string type data
Output of the above program will be:

int () - int () is used with input () to convert user given value into int type.

Output of the above program will be an integer value (69):

eval () : eval () is used with input () to convert user given value into a number toevaluate the string data entered.

AMIT KUMAR KUSHWAHA Page 25


float () : float () is used with input () to convert user given value into float type.

Output of the above program will be a float value (69.0):

PRINT ()
The print() function in Python is used to print a specified message on the screen. The print command in Python
prints strings or objects which are converted to a string while printing on a screen.
print ("Welcome to “)
print(“Guru99")
output : welcome to
Guru99
By default, print function in Python ends with a newline. This function comes with a parameter called ‘end.’
The default value of this parameter is ‘\n,’ i.e., the new line character. You can end a print statement with any
character or string using this parameter.
print ("Welcome to", end = ' ')
print ("Guru99", end = '!')
Output:
Welcome to Guru99!
By default in print function variables are separated with a space. But you can change this Suppose , you want to
separate the values using underscore(_). Then you should pass underscore as the value of sep keyword. The
following function will illustrate you the idea of using python print sep keyword.
Example
print (“COMPUTER SCIENCE”, “WITH PYTHON”)
Output : COMPUTER SCIENCE WITH PYTHON
print (“COMPUTER SCIENCE”, “WITH PYTHON”,sep=’#’)
output : COMPUTER SCIENCE # WITH PYTHON
PUNCTUATORS IN PYTHON:
Punctuators are the symbols that are used in programming language to organize sentence structure,indicate the
rhythm and emphasis of expressions, statements and Program Structure.
Common punctuators are : ‘ , “ , # , \ , (), {}, [ ] , @ ,:,.,’

AMIT KUMAR KUSHWAHA Page 26


SOLVED QUESTIONS

1. What is Python Syntax?


Python syntax refers to a set of rules that defines how users and the system shouldwrite and interpret
a Python program.
2. What is dynamic typing?
Python supports dynamic typing means whatever value we assign to the variable; thedata type of the
variable will be same as the data type of value.
3. What is a variable? Explain with example.
A variable is like a container that stores values. This value you can access and change.Variable is
used to provide a name to an object. Example: X=150 (X here is a variable holding value 150)
4. Define a statement. Give one example also.
An instruction or a set of instruction written in any program is called statement.Example:
print(“We are learning Python”)
5. What are comments? How are they useful in programming? How can we give a
comment in Python?
Comments are python statement that are ignored by Python interpreter.Usefulness:
Comments increase the readability of the code.
Comments in Python starts with hash symbol (#) and extends till the end of line.
Example: # This is a comment
6. What is the significance of indentation in Python?
Indentation is shifting of statement to the right of another statement.Significance:
In Python indentation is used to define a block of statements. To define beginning and end of a
function, Python rely on indentation only. If you don’t give indentation to define a block of
statement/statements, it gives Indentation Error.
7. What are Tokens in Python? How many types of tokens are allowed in Python? Explainwith
example.
Token – It is the smallest element/unit of Python program.Token types :
 Identifiers - The name of any variable, constant, function, module
 Literal - A fix numeric or non-numeric value
 Operators - Symbols that perform some kind of operation (+, -, *, /)
 Delimiters - Symbols which can be used as separators of values or to enclosesome values ({} , [] )
 Keywords -These are reserved words in Python
Example:
Token Category
First_Name variable / identifier
X variable / identifier
print Keyword
= Operator / Delimiter
372 Literal
“Python” Literal
[1,2,3,4,5] []
Delimiter

AMIT KUMAR KUSHWAHA Page 27


8. What will be the output of give code block?
A=10
B=’Python’
print(A+B)
It will produce Type Error as variable A is holding integer type of data and variable B is
holding string type of data. And addition operator is applicable on same type ofoperands.
9. Name the statement used to generate the output in Python.
Print statement is used to generate the output in Python.
10. Name different data types available in Python.
Data types in Python can be defined as mutable and immutable. A mutable data typecan be changed
after it is created, and an immutable data type can't.
 Mutable
List
Dictionary
 Immutable
Integer
Float
String
Tuple
Boolean
11. Define String data type and the ways to define a string data in Python.
String data type represents sequence of characters. To define string type data enclosed the
values within quotation marks (single, double or triple). Example:‘This is an example of
string’
“10+60”
‘’’’Python_3.8’’
12. What happens if relational operators are applied on String data?
When relational operators are applied on String data, strings are compared left toright character by
character according to ASCII values.
13. What is the method to assign values to variables? Explain in detail.
Operator ‘=’ is used for assigning value to a variable. Value can be assigned to variablein these
different ways:
 Assigning same values to multiple variables
Jan, Mar, May, July, Aug, Oct, Dec = 31
 Assigning multiple values to multiple variables Jan,
Feb, Mar, April, May = 31, 28, 31, 30, 31
A variable is not created until some value is assigned to it
14.What are the naming rules for a variable in Python? Give some examples of valid
variables.
Variable Declaration Rules:
1. It must start either with alphabet (capital or small) or underscore ( _ )
2. It cannot start with a number

AMIT KUMAR KUSHWAHA Page 28


3. It can contain only alpha-numeric characters (A-Z, a-z, 0-9) and underscore ( _ )
4. Python keywords cannot be used as a variable name
5. It cannot contain spaces
6. Variable names are case-sensitive (name, Name and NAME are 3 different
variables)
Example (valid variable names):
First_Nam
estudent15
_rollno
15. What is the difference between a keyword and a variable?
Keywords are the reserved words in Python. We cannot use a keyword as
a variable name, function name or any other identifier. They are used to define the syntax and
structure of the Python language. In Python, keywords are case sensitive.For example – print, int,
input, float
A variable is an identifier which is used to store a value. It is user-defined and are notreserved. For
example - First_Name, student15, _rollno etc.
16. How many types of strings are supported in Python?
 Single line string – String that terminates in single line
 Multiline string – String storing multiple lines of text
17. What is ‘None’ in Python?
‘None’ is special type in Python, which is used to indicate something that has not been
created yet. It represents not-null, unidentified value.
18. What is the difference between an expression and a statement?
Expression Statement
It is a combination of symbols, It is an instruction in Python following
operators & operands certain syntax
An expression represents some value Statement is given to execute a task
Expression always evaluate some result Statement may or may not evaluate the
result
Example: Example:
10**3+2-17 Print (“Python is easy”)
19. What do you understand by block/code block/suite in Python?
A group of statements that is part of another statement or function is called ablock/code block/suite.
Example:

20. What would the following code do?X


= Y = Z = 55
X, Y and Z will be assigned with same i.e. 55

AMIT KUMAR KUSHWAHA Page 29


DATA – HANDLING
Data types: data type decide what kind of value will be stored in the variable and about the kind of operation
can be performed on it

 Data can be of any type like-character, integer, real, string.


 Anything enclosed in single double or triple quotes is considered as string in Python.
 Numbers
o Any whole value is an integer value.
o Any value with fraction part is a real value or floating point value. They give accurate value
till 15 digit of precision
o True or False value specifies Boolean value.
o A number in the form of A+Bi is called complex number
 Python supports following core data types-
o Numbers (int like10,5)(float like3.5,302.24)(complex like 3+5i)
o String (like“pankaj”, ‘pankaj’,‘a’,“a”)
o List like[3,4,5,”pankaj”] its elements are Mutable.
o Tuple like(3,4,5,”pankaj”)its elements are immutable.
o Dictionary like{‘a’:1,‘e’:2,‘I’:3,‘o’:4,‘u’:5}where a,e,i,o,u are keys
and1,2,3,4,5 are their values.
Two advantages of floating point number over integers
 They can represent values between integers
 They can represent a much greater range of values
Disadvantage of float over integers
 Floating point operations are generally slower then integer operations
MUTABLE AND IMMUTABLE DATA TYPES
In Python,Data Objects are categorized in two types-
 Mutable(Changeable) : List ,Dictionary and sets
 Immutable (Non-Changeable): String, tuple ,integers ,float, Booleans
Look at following statements carefully-
p=10
q=p they will represent 10,10,10
r=10
Now,tryto change the values-
p=17
r=7 did the values actually change?
q=9
Answer is NO.

Because here values are objects and p, q, r are their reference name. To understand it

AMIT KUMAR KUSHWAHA Page 30


VARIABLES AND VALUES
An important fact to know is- In Python, values are actually objects. And their variable names are actually their
reference names.
Suppose we assign 10 to a variable A.
A=10
Here, value 10 is an object and A is its reference name
Let B=A
It means both A and B point to same memory location of references to same object
Now if we assign B=20 it means a new object will be created and B will reference to that object

Variable Internals: there are three key attributes attached with each
variable
1. The Type of an Object - it determines the data types of object and kind of operations that can be
performed on the object. For this built in function type () is used
For example

2. Value of an object : in the above example value of a is 4


3. id of an object : is generally memory location of an object for example

OPERATORS
An operator is used to perform specific mathematical or logical operation on values.

OPERAND
The values that the operator works on are called operands.
For example,
>>>10+num,
10 & num are operands and the+(plus) sign is an operator.
Python supports following operators-
 Arithmetic Operator
 Relation Operator
 IdentityOperators
 Logical Operators
 BitwiseOperators
 Membership Operators
ARITHMETIC OPERATOR
OPERATOR DESCRIPTION
 +(unary) Explicitly express a +ve number. Example:+3,+98.36
 -(unary) Explicitly express a –ve number. Example :-3,-369.36
 +(binary) Add two numbers, Example:9+6is15

AMIT KUMAR KUSHWAHA Page 31


 -(binary) Subtract one value from another number. Example : 9–3 I s6
 * Product of two numbers. Example 9*6 is 54
 / Gives quotient, when one value is divided by the other.
Example 9/6 is 1.5
 //(floor division) Gives integer part of quotient, when one value is divided by the other.
Example9//6is1 and 6.5//2 is 3.0.
 % (Remainder) Gives remainder when one value is divided by the other.
Example 9%6 is 3
 **(Exponent) To raise a number to the power of another number.Example,3**2 is 9

AssignmentOperator or Augmented assignment operator (means combining the impact of


arithmetic operator with assignment operator
Operator Description

 = Called Assignment operator. Assign a value to the variable. Example, x=20.


 += Add and Assign, Add the R-Value to the L-Value and assign result to L-value.
Example x=20, x+=30 it means x=x+30 so the new value of x is 50.
 -= Subtract and Assign, Subtract the R-Value from L-Value and assign result to
L-value. Example x=50, x-=30 it means x=x–30 so the new value of x is 20.
 *= Multiply and Assign, Multiply the R-Value with L-Value and assign product
to L-value. Example x=50, x*=3 it means x=x*3 so the new value of x is 20.
 /= Divide and Assign Quotient, Divide the L-value with R-Value and assign
Quotient to L-value. Example, x=50 , x/=6 its means x=x/6, and the new value
of x is 8.33333……
 //= Floor and assign, Divide the L-value with R-Value and assign integer quotient
(floor division) to L-value. Example, x=50,x//=6 its means x= x//6 , and the new
value of x is 8.
 %= Divide and Assign Remainder, Divide the L-value with R-Value and assign
Remainder to L-value. Example, x=50, x%=6 its means x=x%
RELATIONAL OPERATOR
Operator Description
 == (Equality) Compares two values for equality, Returns True if they are
equal, otherwise returns False.
 !=(Not equal) Compares two values for inequality, Returns True if they are not
equal, otherwise returns False.
 <(Less than) Compares two values, Returns True if first value is less than the
second, otherwise returns False.
 >(greater than) Compares two values, Returns True if first value is greater than
The second otherwise returns False.
 <=(Less than or equal to) Compares two values, Returns True if first value is less or equal
to than the second, otherwise returns False.
 >=(greater than or equal to) Compares two values, Returns True if first value is greater or
equal to than the second, otherwise returns False

AMIT KUMAR KUSHWAHA Page 32


LOGICALOPERATOR

Operator Description
 not Negate a condition and Returns True if the condition is false
otherwise returns False.
 and Combines two conditions and returns True if both the
conditions are true, otherwise returns False.

 or Combines two conditions and returns True if any or both of


the conditions are true, otherwise returns False.
IDENTITY OPERATORS : Identity operator is also used to check for equality. These expression also results
into True or False. Identity Operators are of following types-
 “is “operator : Returns True, if both operand have same identity i.e.memory reference,
otherwise return False example if a=5 and b=5 then a is b will come to True
 “is not” operator Returns True, if both operand have not same identity i.e. Memory reference,
otherwise return False example if a=5 and b=5 then a is not b will come to False

EXECUTION OF OPERATOR DEPENDS ON THE PRECEDENCE OF OPERATOR.


Order Operator Description
Highest () Parentheses
↑ ** Exponentiation
| ~ Bitwisenor
| +,– UnaryPlusandMinus
| *, /, //, % Multiplication, Division, floor division,
Remainder
| +,– Addition,Subtraction
| & Bitwise and
| ^ BitwiseXOR
| | BitwiseOR
| <,<=,>,>=,<>,!=,==,is,isnot RelationalOperators,IdentityOperators
| not BooleanNOT
↓ and BooleanAND
Lowest or BooleanOR
OPERATOR ASSOCIATIVITY
In Python, if an expression or statement consists of multiple or more than one operator then operator
Associativity will be followed from left-to-right.

In above given expression, first 7*8 will be calculated as 56, then 56 will be divided by 5 and will result into
11.2, then 11.2 again divided by 2 and will result into5.0.
*Only in case of **,associativity will be followed rom right-to-left.

AMIT KUMAR KUSHWAHA Page 33


Above given example will be calculated as 3**(3**2).

EXPRESSIONS
Python has following types of expression-
Arithmetic Expressions like a+b, 5-4 etc.
Relational Expressions like a>b, a==betc.
Logical Expressions like a>b and a>c, a or b etc.
 StringExpressions like“Pankaj”+“Kumar”etc.

TYPE CONVERSION – conversion of one predefined data type into another is called type conversion
In Python, an expression may be consists ofmixed data types. In such cases, python changes data types of
operands internally.
 This process of internal data type conversion is called implicit type conversion. In this conversion
always take place in bigger data type to avoid loss of data. It is also called type promotion
num1 = 10 # num1 is an integer
num2 = 20.0 # num2 is a float
sum1 = num1 + num2 # sum1 is sum of a float and an integer
print(sum1)
print(type(sum1))
Output:
30.0
<class 'float'>
 Explicit type conversion or type casting in which data is converted explicitly by user like-
<datatype> (identifier)
Forex- a=“4”
b=int(a)
Anotherex- Ifa=5andb=10.5
Then we can convert a to float. Like d=float(a)
In python, following are the data conversion functions-
(1)int() (2)float() (3)complex( ) (4)str() (5)bool()
DEBUGGING (Process of Identifying and Removing Errors)
BUG/ ERRORS–The mistake (error) and problem found in the program is called Bug.
Debug–Removing the bug/error from the program is called Debug.
DEBUGGING–The process of Identifying and removing errors from the program is called debugging.
Types of Errors
 Syntax errors
 Semantics errors
 Logical errors
 Runtime errors
Syntax errors: Python has its own rules that determine its syntax. The interpreter interprets the
statements only if it is syntactically (as per the rules of Python) correct. If any syntax error is present, the
interpreter shows error message(s) and stops the execution.

AMIT KUMAR KUSHWAHA Page 34


For Example:Print(a) # P of print is capital which should be small
Semantics errors : When statement is not meaningful for example X*Y=Z is syntactical correct but
semantically incorrect as the variable which is taking value must be on the left hand side and expression
must be on the right hand side
LogicalErrors : A logical error is a bug in the program that causes it to behave incorrectly. A logical error
produces an undesired output but without abrupt termination of the execution of the program.
For Example: Instead of +,you writing – operator. Total=X–Y
Runtime Error : A runtime error causes abnormal termination of program while it is executing. Runtime
error is when the statement is correct syntactically, but the interpreter cannot execute it. Runtime errors do
not appear until after the program starts running or executing.
x=int (input (“enter number”))
You entered here 25.69.It is a runtime error. Divide by a zero is also called runtime error.
Exception: Error and exception are similar but different terms. while error represents ,any bug in the code that
disrupts running of the program or causes improper output, an exception refers to any irregular situation
occurring during execution time which you have no control
for example: if you operate an ATM then
 Entering wrong password is an error
 ATM machine struck is an exception
MATHS MODULE IN PYTHON
math.ceil()
The math.ceil() method maps a floating-point number to the smallest succeeding integer:

p = 10.1
print(math.ceil(p))
OUTPUT=11

math.floor()
The math.floor() method maps a floating-point number to the greatest preceeding integer:

q =9.99
print(math.floor(q))
OUTPUT =9
math.fabs()
The math.fabs() method removes the negative sign of a given number, if any, and returns its absolute value as
a float:

print(math.fabs(-25))
25.0
math.pow()
The math.pow() method returns a floating-point value representing the value of x to the power of y .

AMIT KUMAR KUSHWAHA Page 35


math.exp()
The math.exp(x) method is equal to ��, where � is the Euler's number. We can say
the math.exp(x) method is equivalent to the statement below:
math.pow(math.e, x)
print(math.exp(3))
print(math.pow(math.e,3))
20.085536923187668
20.085536923187664
math.sqrt()
The math.sqrt() method returns the square root of a number. Let's try it:

print(math.sqrt(16))
4.0
math.log()
The math.log() method accepts two arguments, x and base, where the default value of base is �. So the
method returns the natural logarithm of x (log�⁡�) if we only pass one argument. On the other hand, if we
provide two arguments, it calculates the logarithm of x to the given base (log�⁡�). Let's calculate different
logarithms:
print(math.log(10))
print(math.log(10,3))
2.302585092994046
2.095903274289385
RANDOM MODULE IN PYTHON
a) random.random() – it will returns a random floating point number N in the range (0.0 to 1.0) i.e
0.0<=N<1.0(lower limit inclusive)
for example : to generate random number between 15 to 35 you may write as
import random
print(random.random() *(35-15)+15)
output : 28.30718
b) random.randrange () – this function can be used in three different ways
i) random.randrange (stop value)- to generate random number in the range 0 to stop value e.g.
print(random.randrange (45)) will generate 13
ii) random.randrange (start, stop) - to generate random number in the range 11 to 45 e.g.
random.randrange (11, 45) will generate 25
iii) random.randrange(start ,stop, step)- to generate random number in the range 11 to 45 with a
jump of 4
e.g. print(random.randrange(11,45,4)) will generate 15
e.g. print(random.randrange(11,45,4)) will generate 19
c) random.randint(a,b) – it will returns a random integer number N in the range (a to b) i.e a<=N=<b
for example : to generate random number between 15 to 35 you may write as
import random
print(random.random(15,35)
output : 27

AMIT KUMAR KUSHWAHA Page 36


FLOW OF CONTROL
SELECTION STATEMENT – means execution of statement(s) depending upon a condition test.
There are three types of conditions in python:
 if statement
 if-else statement
 elif statement
if statement: It is a simple if statement. When condition is true, then code which isassociated with if statement
will execute.
For example
a=5
b=6
if a>b:
print(“a is greater than b”)
now in this example what if condition is false then it will not print anything
if – else Statement :If statement called if..else statement
allows us to write two alternative paths and the control
condition determines which path gets executed. The syntax
for if..else statement is as follows
The syntax of if statement is:
if condition:
statement(s)
else:
statement(s)
Q. Write a program to accept person age from the user and
check weather person is eligiblefor vote or not.

age = int(input(“Enter your age: “)) # Taking input from the user
if age >= 18: # Checking weather age is grater then 18 or not
print(“Eligible to vote”) #Printing the comment if age is grater then 18
else:
print(“Not eligible to vote”) #Printing the comment if age is grater then 18
Q. Program to print the positive difference of two numbers.
num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))
if num1 > num2:
diff = num1 – num2
else:
diff = num2 – num1
print(“The difference of”,num1,”and”,num2,”is”,diff)
Output:
Enter first number: 5 Enter second number: 6
The difference of 5 and 6 is 1
elif statement : It is short form of else-if statement. If the previous conditions were not true,then do this
condition". It is also known as nested if statement. You can build a chain of if statement using this
syntax : if condtition :
statement(s)

AMIT KUMAR KUSHWAHA Page 37


elif condition:
statement(s)
else:
statement(s)
Q. Check whether a number is positive, negative, or zero.
number = int(input(“Enter a number: “)
if number > 0:
print(“Number is positive”)
elif number < 0:
print(“Number is negative”)
else:
print(“Number is zero”)
Q. program to create four function calculator
result = 0
val1 = float(input(“Enter value 1: “))
val2 = float(input(“Enter value 2: “))
op = input(“Enter any one of the operator (+,-,*,/): “)
if op == “+”:
result = val1 + val2
elif op == “-“:
if val1 > val2:
result = val1 – val2
else:
result = val2 – val1
elif op == “*”:
result = val1 * val2
elif op == “/”:
if val2 == 0:
print(“Error! Division by zero is not allowed. Program terminated”)
else:
result = val1/val2
else:
print(“Wrong input, program terminated”)
print(“The result is “,result)
Output:
Enter value 1: 84
Enter value 2: 4
Enter any one of the operator (+,-,*,/): /
The result is 21.0
Q-Write a program to find the maximum number out of three given numbers.
a= int(input("Enter first number"))
b= int(input("Enter second number"))
c= int(input("Enter third number"))
max=a
if b>max:
max=b
elif z>max:
max=c

AMIT KUMAR KUSHWAHA Page 38


print("Maximum number out of three is",max)
Output
Enter first number 12
Enter second number32
Enter third number1
(‘Maximum number out of three is', 32)
REPETITION: Iteration is another word for this kind of repetition. A
programme can repeat a certain collection ofstatements by using looping
constructs.
Looping – The ability to repeatedly run a group of statements in a
programme based on a condition is provided by looping constructs. While a
certain logical condition is true, the statementsin a loop are repeated again.
There are two types of loops-
 For loop
 While loop
They are also called Entry Control Loop – The loop which check the
condition first and then execute the body of loop is known as entry control
loop
THE RANGE ( ) FUNCTION: it generates a list of numbers, which is
generally used to iterate over with for loop. range ( ) function uses three types of parameters, which are:
 start: Starting number of the sequence.
 stop: Generate numbers up to, but not including last number.
 step: Difference between each number in the sequence.
Python use range ( ) function in three ways:
 range(stop)
 range(start, stop)
 range(start, stop, step)
Note:
All parameters must be integers.
All parameters can be positive or negative.
range(stop): By default, It starts from 0 and increments by 1 and ends up to stop,but not including stop
value.
Example:
for x in range(4):
print(x)
Output: 0
1
2
3
range(start, stop): It starts from the start value and up to stop, but not includingstop value.
Example:
for x in range(2, 6):
print(x)
Output:
2
3
4
5

AMIT KUMAR KUSHWAHA Page 39


range(start, stop, step): Third parameter specifies to increment or decrement the value byadding or subtracting
the value.
Example:
for x in range(3, 8, 2):
print(x)
Output:
3
5
7
Explanation of output: 3 is starting value, 8 is stop value and 2 is step value. First print 3 and increase it
by 2, that is 5, again increase is by 2, that is 7. The output can’t exceed stop-1 valuethat is 8 here. So, the
output is 3, 5, 8.
For Loop: The for statement allows you to specify how many times a statement or compound statement
should be repeated. A for statement’s body is executed one or more times until an optional condition is met.
Syntax of the For Loop
for <control-variable> in <sequence/ items in range>:
<statements inside body of the loop>
Q. Program to print the characters in the string ‘PYTHON’ using for loop.
Str= “python”
For i in str:
Print(i)
Output :
p
y
t
h
o
n
Q- Program to generate table of any given number
N= int(input(“Enter number to generate table”))
for i in range(1,11):
print(N , ‘X’,i,’=’N*i)
WHILE LOOP: With the while loop we can execute a set of statements as long as a condition istrue. It
requires defining an indexing variable
Example: To print table of number 2
i=2
while i<=20:
print(i)
i+=2
Q. Program to print first 5 natural numbers using while loop.
count = 1
while count <= 4:
print(count)
count += 1
Output: 1
2
3
4

AMIT KUMAR KUSHWAHA Page 40


Q. Program to find the factors of a whole number using while loop.
num = int(input(“Enter a number to find its factor: “))
print (1, end=’ ‘) #1 is a factor of every number factor = 2
while factor <= num/2 :
if num % factor == 0:

print(factor, end=’ ‘)
factor += 1
print (num, end=’ ‘) #every number is a factor of itself
Output:Enter a number to find its factors : 6
1236
Infinite Loop: loop which never ends or condition of loop never become false. for loop cannot be infinite as it
will take by default jump of step 1 but in case of while loop if we forget to give increment to loop variable or it
is not in indentation of while or use of break before increment will led to infinite loop
For example
Case -1 : Here loop is infinite as no increment of i is there
i=1
while i<10:
print(i)
Case-2 : Here increment is given but it is outside indentation of while
i=1
while i<10:
print(i)
i+=1
Loop else statement: The else statement of a python loop executes when the loop terminates normally.
The else statement of the loop will not execute when the break statement terminates the loop.The else clause of
a loop appears at the same indentation as that of the loop keyword while or for.
For example
Q. Program to print first 5 natural numbers using while loop.
count = 1
while count <= 5:
print(count)
count += 1
else :
print(“loop over”)
Output: 1
2
3
4
5
Loop over
NESTED LOOP -A loop may contain another loop inside it. A loop inside another loop is called a nested
loop. Pythondoes not impose any restriction on how many loops can be nested inside a loop or on the levels
of nesting. Any type of loop (for/while) may be nested within another loop (for/while).
#Program to print the pattern for a number input by the user
num = int(input(“Enter a number to generate its pattern = “))

AMIT KUMAR KUSHWAHA Page 41


for i in range(1,num + 1):

for j in range(1,i + 1):


print(j, end = ” “)
print()
Output:
Enter a number to generate its pattern = 4
1
12
123
1234
Q. Program to find prime numbers between 2 to 21 using nested for loops.
for i in range(2, 18):
for j in range (2,i):
if i%j==0:
j=num/i
print(“found a factor(“,j”, i)
break
else :
print(i,”is a prime number”)

Output:
2 is a prime number
3 is a prime number
5 is a prime number
7 is a prime number
11 is a prime number
13 is a prime number
JUMP STATEMENTS
There are two jump statements in python:
 break
 continue
break statement: With the break statement we can stop the loop even if it is true. It enables a program to skip
over a part of code. It terminates the very loop it lies in
in while loop in for loop
i = 1 languages = ["java", "python", "c++"]
while i < 6: for x in languages:
print(i) if x == "python":
if i == 3: break
break print(x)
i += 1
Output: Output:
1 java
2
3
Note: If the break statement appears in a nested loop, then it will terminate the very loop it is in i.e. if
the break statement is inside the inner loop then it will terminate the inner loop only and the outer loop

AMIT KUMAR KUSHWAHA Page 42


will continue as it is.
continue statement: With the continue statement we can stop the current iteration, andcontinue with
the next iteration

in while loop in for loop


i = 0 languages = ["java", "python", "c++"]
while i < 6: for x in languages:
i += 1 if x == "python":
if i == 3: continue
continue print(x)
print(i)
Output: Output:
1 java c++
2
4
5
6

PASS STATEMENT
This statement does nothing. It can be used when a statement is required syntactically but the programrequires
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 : 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
SOME EXTRA PROGRAM ON LOOPING
Q. Find the sum of all the positive numbers entered by the user. As soon as the user entersa negative number,
stop taking in any further input from the user and display the sum.
num = sum = 0
print(“Enter numbers to find their sum, negative number ends theloop:”)

AMIT KUMAR KUSHWAHA Page 43


while True:
num=int(input(“enter number”)
if num<0:
break
sum+=num
print(“sum=”,sum)
Output : Enter numbers to find their sum, negative number ends the loop:3
4
5
-1
Sum = 12
Q. Program to check if the input number is prime or not.
num=int(input(“enter number to check”))
flag = 0 #presume num is a prime numberif num > 1 :
a=int(num/2)
for i in range(2, int(num / 2)):
if (num % i == 0):
flag = 1 #num is a not prime numberbreak #no need to check any further
if flag == 1:
print(num , “is not a prime number”)
else:
print(num , “is a prime number”)
else :
print(“Entered number is <= 1, execute again!”)
Q. Write a program to calculate the factorial of a given number.
num = int(input(“Enter a number: “))
fact = 1
# check if the number is negative, positive or zero
if num < 0:
print(“Sorry, factorial does not exist for negative numbers”)
elif num == 0:
print(“The factorial of 0 is 1”)
else:
for i in range(1, num + 1):
fact = fact * i
print(“factorial of “, num, ” is “, fact)
output: Enter a number : 5
Factorial of 5 is 120
Q- write a program to generate Fibonacci series till n terms
num = int(input(“Enter a number: “))
F=0
S=1
print(F,end=’’)
print(S,end=’’)
for i in range(num):
third=F+S
print(third,end=’’)
F,S=S,Third
Output : Enter a number :5
0112358

AMIT KUMAR KUSHWAHA Page 44


STRING MANIPULATION
INTRODUCTION: Definition: Sequence of characters enclosed in single, double or triple quotation marks.
Basics of String:
 Strings are immutable in python. It means it is unchangeable. At the same memoryaddress, the
new value cannot be stored.
 Each character has its index or can be accessed using its index.
 String in python has two-way index for each location. (0, 1, 2, In the forward direction and -1, -2, -
3, in the backward direction.)
FOR EXAMPLE :
STR=”kendriya”
0 1 2 3 4 5 6 7
k e n d r i y a
-8 -7 -6 -5 -4 -3 -2 -1
 The size of string is total number of characters present in the string. (If there are n characters in
the string, then last index in forward direction would be n-1 and last index in backward
direction would be –n.)
 String are stored each character in contiguous location.
Note – Python accepts single (‘), double (“), triple (”’) or triple(“””) quotes to denote string literals.Single
quoted strings and double quoted strings are equal. Triple quotes are used for contain special characters
like TAB, or NEWLINES
Accessing Characters in a String
A method known as indexing can be used to retrieve each individual character in a string. The
character to be retrieved in the string is specified by the index, which is enclosed in square
brackets([ ]). We receive an IndexError if we provide an index value outside of this range. A
number must make up the index (positive, zero or negative).

STRING IS IMMUTABLE SO ASSIGNMENT CANNOT BE DONE IN STRING

>>> str1 = “Hello World!” #if we try to replace character ‘e’ with ‘a’
>>> str1[1] = ‘a’ #TypeError: ‘str’ object does not support item assignment
TRAVERSING A STRING:

AMIT KUMAR KUSHWAHA Page 45


Access the elements of string, one character at a time.
str = “kendriya”
for ch in str :
print(ch, end= ‘ ‘)
Output: kendriya
Q- Program to read a string and display it in reverse order
Str= input("Enter string")
print("the original string is",Str)
L=len(Str)
for i in range(-1,(-L-1),-1):
print(Str[i])
Output : Enter string 'Python'
('the original string is', 'Python')
n
o
h
t
y
P
STRING OPERATORS:
 Basic Operators (+, *)
 Membership Operators ( in, not in)
 Comparison Operators (==, !=, <, <=, >, >=)
Basic Operators: There are two basic operators of strings:
a) String concatenation Operator: The + operator creates a new string by joining the two operand strings.
For concatenation both input must be a string
Example:
>>>”Hello”+”Python”
‘Hello Python’
>>>’2’+’7’
’27’
>>>”Python”+”3.0”
‘Python3.0’
Note: You cannot concate numbers and strings as operands with + operator.Example:
>>>7+’4’ # unsupported operand type(s) for +: 'int' and 'str'It is invalid and generates an error.
b) String repetition Operator: It is also known as String replication operator. It requires two types of
operands- a string and an integer number.
Example:
>>>”you” * 3‘
youyouyou’
>>>3*”you”
‘youyouyou’

AMIT KUMAR KUSHWAHA Page 46


Note:You cannot have strings as n=both the operands with * operator.Example:
>>>”you” * “you” # can't multiply sequence by non-int of type 'str' It is invalid and generates an error.
MEMBERSHIP OPERATORS:
a) in – Returns True if a character or a substring exists in the given string; otherwise False
b) not in - Returns True if a character or a substring does not exist in the given string; otherwise False
Example:
>>> "ken" in "Kendriya Vidyalaya"
False
>>> "Ken" in "Kendriya Vidyalaya"
True
>>>"ya V" in "Kendriya Vidyalaya"
True
>>>"8765" not in "9876543"
False
Comparison Operators: These operators compare two strings character by characteraccording to their ASCII
value
Characters ASCII (Ordinal) Value
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122
Example:
>>> 'abc'>'abcD'
False
>>> 'ABC'<'abc'
True
>>> 'abcd'>'aBcD'
True
>>> 'aBcD'<='abCd'
True
FINDING THE ORDINAL OR UNICODE VALUE OF A CHARACTER:

Function Description
ord(<character>) Returns ordinal value of a character
chr(<value>) Returns the corresponding character
Example:
>>> ord('b')
98
>>> chr(65)
'A'
Program: Write a program to display ASCII code of a character and vice versa.
var=True

AMIT KUMAR KUSHWAHA Page 47


while var:
ch=int(input("Press-1 to find the ordinal value \n Press-2 to find a character of a value\n"))
if ch==1:
a=input("Enter a character : ")
print(ord(a))
elif ch==2:
val=int(input("Enter an integer value: "))
print(chr(val))
else:
print("You entered wrong choice")
print("Do you want to continue? Y/N")
option=input(“Enter your choice”)
if option=='y' or option=='Y':
var=True
else:
var=False
SLICE OPERATOR WITH STRINGS: The slice operator slices a string using a range of indices.
Syntax:
string-name[start:end]
where start and end are integer indices. It returns a string from the index start to end-1.
0 1 2 3 4 5 6 7 8 9 10 11 12 13
d a t a s t r u c t u r e
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Example:
>>> str="data structure"
>>> str[0:14]
'data structure'
>>> str[0:6]
'data s'
>>> str[2:7]
'ta st'
>>> str[-13:-6]
'ata str'
>>> str[-5:-11]
'' #returns empty string
>>> str[:14] # Missing index before colon is considered as 0.
'data structure'
>>> str[0:] # Missing index after colon is considered as 14. (length of string)
'data structure'
>>> str[7:]
'ructure'
>>> str[4:]+str[:4]

AMIT KUMAR KUSHWAHA Page 48


' structuredata'
>>> str[:4]+str[4:] #for any index str[:n]+str[n:] returns original string
'data structure'
>>> str[8:]+str[:8]
'ucturedata str'
>>> str[8:], str[:8]
('ucture', 'data str')
SLICE OPERATOR WITH STEP INDEX: Slice operator with strings may have third index. Which is known
as step. It is optional.
Syntax:
string-name[start:end:step]
Example:
>>> str="data structure"
>>> str[2:9:2]
't tu'
>>> str[-11:-3:3]
'atc'
>>> str[: : -1] # reverses a string
'erutcurts atad'
Interesting Fact: Index out of bounds causes error with strings but slicing a string outside theindex does not
cause an error.
Example:
>>>str[14]
IndexError: string index out of range
>>> str[14:20] # both indices are outside the bounds
'' # returns empty string
>>> str[10:16]
'ture'
Reason: When you use an index, you are accessing a particular character of a string, thus theindex must be valid
and out of bounds index causes an error as there is no character to return from the given index.
But slicing always returns a substring or empty string, which is valid sequence.
BUILT-IN FUNCTIONS OF STRING:
EXAMPLE: str=”data structure”
s1= “hello365”
s2= “python”
s3 = ‘4567’
s4 = ‘ ‘
s5= ‘comp34%@’

AMIT KUMAR KUSHWAHA Page 49


S. No. Function Description Example
1 len( ) Returns the length of a string >>>print(len(str))
14
2 capitalize( ) Returns a string with its first >>> str.capitalize()
character 'Data structure'
capitalized.
3 find(sub,start,end) Returns the lowest index in the string where >>> str.find("ruct",5,13)
the substring sub is found within the slice range. 7
Returns -1 if sub is not found. >>> str.find("ruct",8,13)
-1
4 isspace( ) Returns True if there are >>> " ".isspace()
only whitespace characters in the True
string. False otherwise. >>> "".isspace()
False
5 lower( ) Converts a string in lowercase characters. >>> "HeLlo".lower()
'hello'
6 isalnum( ) Returns True if the characters in the string are >>>s1.isalnum( )
alphabets or numbers. False otherwise True
>>>s2.isalnum( )
True
>>>s3.isalnum( )
True
>>>s4.isalnum( )
False
>>>s5.isalnum( )
False
7 isalpha( ) Returns True if all characters in the string >>>s1.isalpha( )
arealphabetic. False otherwise. False
>>>s2.isalpha( )
True
>>>s3.isalpha( )
False
>>>s4.isalpha( )
False
>>>s5.isalpha( )
False
8 isdigit( ) Returns True if all the characters in the >>>s1.isdigit( )
string aredigits. False otherwise. False
>>>s2.isdigit( )
False
>>>s3.isdigit( )
True
>>>s4.isdigit( )
False
>>>s5.isdigit( )
False

AMIT KUMAR KUSHWAHA Page 50


9 islower( ) Returns True if all the characters in the >>> s1.islower()
string arelowercase. False otherwise. True
>>> s2.islower()
True
>>> s3.islower()
False
>>> s4.islower()
False
>>> s5.islower()
True
10 isupper( ) Returns True if all the characters in the >>> s1.isupper()
string are uppercase. False otherwise. False
>>> s2.isupper()
False
>>> s3.isupper()
False
>>> s4.isupper()
False
>>> s5.isupper()
False
11 upper( ) Converts a string in uppercase characters. >>> "hello".upper()
'HELLO'
12 lstrip( ) Returns a string after >>> str="data structure"
removing the leading characters. >>> str.lstrip('dat')
(Left side). ' structure'
if used without any argument, it removes >>> str.lstrip('data')
the leading whitespaces. ' structure'
>>> str.lstrip('at')
'data structure'
>>> str.lstrip('adt')
' structure'
>>> str.lstrip('tad')
' structure'
13 rstrip( ) Returns a string after >>> str.rstrip('eur')
removing the trailing 'data struct'
characters. (Right side). >>> str.rstrip('rut')
if used without any argument, it removes 'data structure'
the trailing whitespaces. >>> str.rstrip('tucers')
'data '
14. title() Returns the string with first letter of every >>> str=” I am a
word in the string in uppercase and rest in student?
lowercase >>>str.title()
>>>I Am A Student

count(str, start, end) : Returns number of times substring str occurs in the given string. If we do not give
start index andend index then searching starts from index 0 and ends at length of the string.
>>> str1 = ‘Hello World! HelloHello’
>>> str1.count(‘Hello’,12,25)

AMIT KUMAR KUSHWAHA Page 51


2
>>> str1.count(‘Hello’)
3
index(str, start, end) : Returns the lowest index in the string where the substring sub is found within the slice
range. Returns an exception ValueError if sub is not found.
>>> str1 = ‘Hello World! HelloHello’
>>> str1.index(‘Hello’)
0
>>> str1.index(‘Hee’)
ValueError: substring not found
>>> str1.count(‘Hello’,12,25)
2
endswith() : Returns True if the given string ends with the supplied substring otherwise returns False
>>> str1 = ‘Hello World!’
>>> str1.endswith(‘World!’)
True
>>> str1.endswith(‘!’)
True
>>> str1.endswith(‘lde’)
False
startswith() : Returns True if the given string starts with the supplied substring otherwise returns False
>>> str1 = ‘Hello World!’
>>> str1.startswith(‘He’)
True
>>> str1.startswith(‘Hee’)
False
istitle() : Returns True if the string is non-empty and title case, i.e., the first letter of every word in the string
in uppercase and rest in lowercase
>>> str1 = ‘Hello World!’
>>> str1.istitle()
True
>>> str1 = ‘hello World!’
>>> str1.istitle()
False
join() : Returns a string in which the characters in the string have been joined by a separator
>>> str1 = (‘HelloWorld!’)
>>> str2 = ‘-‘ #separator
>>> str2.join(str1)
‘H-e-l-l-o-W-o-r-l-d-!’
>>>’##’.join([‘Radhe’,’Shyam’])
>>>‘Radhe’##’Shyam’
Note : In this sequence must of same type not mixed

AMIT KUMAR KUSHWAHA Page 52


partition() :Partitions the given string at the first occurrence of the substring (separator) and returns the tuple
string partitioned into three parts.
 Substring before the separator
 Separator
 Substring after the separator
If the separator is not found in the string, it returns the whole string itself and two empty strings. It always
returns the tuple of length 3
>>> str1 = ‘India is a Great Country’
>>> str1.partition(‘is’)
(‘India ‘, ‘is’, ‘ a GreatCountry’)
>>> str1.partition(‘are’)
(‘India is a Great Country’,’ ‘,”)
split() :Returns a list of words delimited by the specified substring. If no delimiter is given then words are
separated by space. The length of the list is equal to the number of words
>>> str1 = ‘India is a Great Country’
>>> str1.split()
[‘India’,’is’,’a’,’Great’,’Country’]
>>> str1.split(‘a’)
[‘Indi’, ‘ is ‘, ‘ Gre’, ‘t Country’]
Difference between partition() and split()
S.no split() partition()
1 Will split the string at any Will only split the string at first
occurrence of the given argument occurrence of the given argument
2 It will return a list type containing It will return a tuple type containing
the split substrings the split substrings
3 The length of the list is equal to the It always returns the tuple of length 3
number of words if split on With the given separator as the
whitespaces middle value of the tuple

Some string problems and their solution


Q. Write a program with a user defined function to count the number of times a character occurs in
the given string.
count = 0
st= input(“Enter string”)
ch=input(“enter character to count”)
for a in st:
if a == ch:
count += 1
print(“Number of times character”, ch, ”occurs in the string is:”,count)
Output: Enter a string: Today is a Holiday
Enter the character to be searched: a
Number of times character a occurs in the string is: 3

AMIT KUMAR KUSHWAHA Page 53


Q: Write a program to check whether the entered string is palindrome or not
st = input(“Enter a String: “)
i=0
mid = len(st)/2
j=-1
while(i <mid):
if st[i] = st[j]:
i += 1
j -= 1
else :
print(“The given string”,st,”is not a palindrome”)
break
else :
print(“The given string”,st,”is a palindrome”)
Output 1: Enter a String: kanak
The given string kanak is a palindrome
Output 2: Enter a String: computer
The given string computer is not a palindrome

Q-Write a program that takes a string with multiple words and then capitalizes the first letter of
each word and forms a new string out of it.
Solution:
s1=input("Enter a string : ")
length=len(s1)
a=0
end=length
s2="" #empty string
while a<length:
if a==0:
s2=s2+s1[0].upper()
a+=1
elif (s1[a]==' 'and s1[a+1]!=''):
s2=s2+s1[a]
s2=s2+s1[a+1].upper()
a+=2
else:
s2=s2+s1[a]
a+=1
print("Original string : ", s1)
print("Capitalized wrds string: ", s2)

AMIT KUMAR KUSHWAHA Page 54


LIST MANIPULATION
INTRODUCTION
 List is a collection of elements which is ordered and changeable (mutable).
 Allows duplicate values.
 A list contains items separated by commas and enclosed within square brackets ([ ]).
 All items belonging to a list can be of different data type.
 The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list
Difference between list and string:
List String
Mutable Immutable
Element can be assigned at specified Element/character cannot be
index assigned at specified index.
Example: Example:
>>>L=[7,4,8,9] >>>str= “python”
>>>L[2]=6 #valid >>>str[2]= ‘p’ #error

CREATING A LIST: To create a list enclose the elements of the list within square brackets and separate the
elements by commas.
Syntax: list-name= [item-1, item-2, , item-n]
Example: mylist = ["apple", "banana", "cherry"] # a list with three items
L=[] # an empty list
Using assignment operator
 L1 = [1,2]
 L2 = L1 (creates deep copy)
Creating a list using list( ) Constructor: using existing sequence like string or tuple
a) It is also possible to use the list( ) constructor to make a list.
mylist = list(("apple", "banana", "cherry")) #note the double round-brackets
>>>print(mylist)
["apple", "banana", "cherry"]
L=list( ) # creating empty list
Nested Lists:
>>> L=[23,'w',78.2, [2,4,7],[8,16]]
>>> L
[23, 'w', 78.2, [2, 4, 7], [8, 16]]
b) Creating a list by taking input from the user:
>>> List=list(input("enter the elements: "))
enter the elements: hello python
>>> List
['h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n']
>>> L1=list(input("enter the elements: "))
enter the elements: 678546
>>> L1
['6', '7', '8', '5', '4', '6'] # it treats elements as the characters though we entered digits

AMIT KUMAR KUSHWAHA Page 55


To overcome the above problem, we can use eval( ) method, which identifies the data type and evaluate them
automatically.
>>> L1=eval(input("enter the elements: "))
enter the elements: 654786
>>> L1
654786 # it is an integer, not a list
>>> L2=eval(input("enter the elements: "))
enter the elements: [6,7,8,5,4,3] # for list, you must enter the [ ] bracket
>>> L2
[6, 7, 8, 5, 4, 3]
Note: With eval( ) method, If you enter elements without square bracket[ ], it will beconsidered as a
tuple.
>>> L1=eval(input("enter the elements: "))
enter the elements: 7,65,89,6,3,4
>>> L1
(7, 65, 89, 6, 3, 4) #tuple

Accessing lists:
 The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes.
 List-name[start:end] will give you elements between indices start to end-1.
 The first item in the list has the index zero (0).
Example:
>>> number=[12,56,87,45,23,97,56,27]

0 1 2 Forward3Index 4 5 6 7
12 56 87 45 23 97 56 27
>>> number[2]
-8 -7 -6 -5 -4 -3 -2 -1
Backward Index
= 87
>>> number[-1] = 27
>>> number[-8] = 12
>>> number[8]
IndexError: list index out of range
>>> number[5] = 55 #Assigning a value at the specified index
>>> number
[12, 56, 87, 45, 23, 55, 56, 27]
TRAVERSING A LIST: Traversing means accessing and processing each element.
Method-1:
day=list(input("Enter elements :"))
for d in day:
print(d)
Output: sunday
s
u
n

AMIT KUMAR KUSHWAHA Page 56


d
a
y
Method-2
day=list(input("Enter elements :"))
for i in range(len(day)):
print(day[i])
Output:
Sunday
S
u
n
d
a
y
LIST OPERATORS:
 Joining operator +
 Repetition operator *
 Slice operator [:]
 Comparison Operator <, <=, >, >=, ==, !=
JOINING OPERATOR: It joins two or more lists.
Example:
>>> L1=['a',56,7.8]
>>> L2=['b','&',6]
>>> L3=[67,'f','p']
>>> L1+L2+L3
['a', 56, 7.8, 'b', '&', 6, 67, 'f', 'p']
>>> L5=[10,12,14]
>>>L5+2
ERROR AS BOTH SHOULD BE LIST TYPE
>>>L5+=[2]
>>>L5
[10,12,14,2]
>>>L5+’ABC’
ERROR AS BOTH SHOULD BE LIST TYPE
>>>L5+=’ABC’
>>>L5
[10,12,14,’A’,’B’,’C’]

REPETITION OPERATOR: It replicates a list specified number of times.


Example:
>>> L1*3
['a', 56, 7.8, 'a', 56, 7.8, 'a', 56, 7.8]

AMIT KUMAR KUSHWAHA Page 57


>>> 3*L1
['a', 56, 7.8, 'a', 56, 7.8, 'a', 56, 7.8]
SLICE OPERATOR: LIST SLICING : List-name[start:end] will give you elements between indices start
to end-1.
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:-2] [87, 45, 23, 97]
>>> number[4:20] [23, 97, 56, 27]
>>> number[-1:-6] []
>>> number[-6:-1] [87, 45, 23, 97, 56]
>>> number[0:len(number)] [12, 56, 87, 45, 23, 97, 56, 27]
List-name[start:end:step] will give you elements between indices start to end-1 with skipping elements as
per the value of step.
>>> number[1:6:2] [56, 45, 97]
>>> number[: : -1] [27, 56, 97, 23, 45, 87, 56, 12] #reverses the list
List modification using slice operator:
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:4]=["hello","python"]
>>> number
[12, 56, 'hello', 'python', 23, 97, 56, 27]
>>> number[2:4]=["computer"]
>>> number
[12, 56, 'computer', 23, 97, 56, 27]
Note: The values being assigned must be a sequence (list, tuple or string)
Example:
>>> number=[12,56,87,45,23,97,56,27]
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:3]=78 # 78 is a number, not a sequence TypeError: can only assign an iterable
COMPARISON OPERATORS:
 Compares two lists
 Python internally compares individual elements of lists in lexicographical order.
 It compares the each corresponding element must compare equal and two sequences must be of the same
type.
 For non-equal comparison as soon as it gets a result in terms of True/False, from corresponding
elements’ comparison. If Corresponding elements are equal, it goes to the next element and so on, until it
finds elements that differ.
Example:
>>>L1, L2 = [7, 6, 9], [7, 6, 9]
>>>L3 = [7, [6, 9] ]
For Equal Comparison:
Comparison Result Reason
>>>L1==L2 True Corresponding elements have same value and same type

AMIT KUMAR KUSHWAHA Page 58


>>>L1==L3 False Corresponding values are not same

For Non-equal comparison:


Comparison Result Reason

>>> L1>L2 False All elements are equal

>>> L2>L3 TypeError: '>' not in L2, element at the index 1 is int type
supported between and in L3 element at the index 1 is list
instances of 'int' and 'list' type
>>>[3,4,7,8]<[5,1] True 3<5 is True

>>>[3,4,7,8]<[3,4,9,2] True First two elements are same so move


to next element and 7<9 is True
>>>[3,4,7,8]<[3,4,9,11] True 7<9 is True

>>>[3,4,7,8]<[3,4,7,5] False 8<5 is False


LIST METHODS:
Consider a list: company=["IBM","HCL","Wipro"]
S.No. Function Description Example
Name
1 append( ) To add element to the listat >>> company.append("Google")
the end. syntax: >>> company
list-name.append (element)
['IBM', 'HCL', 'Wipro', 'Google']
Error: >>>company.append("infosys","microsoft") # takes exactly one elementTypeError:
append() takes exactly one argument (2 given)
2 extend( ) Add a list, to the end of the >>>company=["IBM","HCL","Wipro"]
current list. >>> desktop=["dell","HP"]
Syntax: >>> company.extend(desktop)
list-name.extend(list) >>> company
['IBM', 'HCL', 'Wipro', 'dell', 'HP']
Error: >>company.extend("dell","HP") #takes only a list as argumentTypeError: extend() takes
exactly one argument (2 given)
3. len( ) Find the length of the list. >>>company=["IBM","HCL","Wipro"]
Syntax: >>> len(company) 3
len(list-name) >>> L=[3,6,[5,4]]
>>> len(L) 3

AMIT KUMAR KUSHWAHA Page 59


4 index( ) Returns the index of the first >>> company = ["IBM", "HCL", "Wipro",
element with the specified "HCL","Wipro"]
value. >>> company.index("Wipro")2
Syntax:
list-name.index(element)
Error: >>> company.index("WIPRO") # Python is case-sensitive languageValueError: 'WIPRO' is
not in list
>>> company.index(2) # Write the element, not index ValueError: 2 is not in list

5 insert( ) Adds an element at the >>>company=["IBM","HCL","Wipro"]


specified position. >>> company.insert(2,"Apple")
>>> company
Syntax: ['IBM', 'HCL', 'Apple', 'Wipro']
list.insert(index, element) >>> company.insert(-16,"TCS")
>>> company
['TCS', 'IBM', 'HCL', 'Apple', 'Wipro']
6 count( ) Return the number of >>> company = ["IBM", "HCL",
times the value appears. "Wipro", "HCL","Wipro"]
Syntax: >>> company.count("HCL") 2
list-name.count(element) >>> company.count("TCS") 0
7 remove( ) To remove an element >>> company = ["IBM", "HCL",
from the list. "Wipro", "HCL","Wipro"]
Syntax: >>> company.remove("Wipro")
list-name.remove(element) >>> company = ['IBM', 'HCL', 'HCL', 'Wipro']
Error: >>> company.remove("Yahoo") # ValueError:
list.remove(x): #x not in list
8 clear( ) Removes all the elements >>> company=["IBM","HCL", "Wipro"]
from list. >>> company.clear( )
Syntax:list-name.clear( ) >>> company[ ]
9 pop( ) Removes the element at the >>>company=["IBM","HCL", "Wipro"]
specified position and returns >>> company.pop(1)
the deletedelement. 'HCL'
Syntax: list-name.pop(index) >>> company
The index argument is ['IBM', 'Wipro']
optional. If no index is >>> company.pop( )
specified, pop( ) removes and 'Wipro'
returns the last item in the list.
Error: >>>L=[ ] >>>L.pop( ) IndexError: pop from empty list

AMIT KUMAR KUSHWAHA Page 60


10 copy( ) Returns a copy of the list. >>>company=["IBM","HCL", "Wipro"]
Syntax: >>> L=company.copy( )
list-name.copy( ) >>> L output : ['IBM', 'HCL', 'Wipro']
11 reverse( ) Reverses the order of the list. >>>company=["IBM","HCL", "Wipro"]
Syntax: list-name.reverse( ) >>> company.reverse()
Takes no argument, >>> company ['Wipro', 'HCL', 'IBM']

12. sort( ) Sorts the list. By defaultin >>>company=["IBM","HCL", "Wipro"]


ascending order. >>>company.sort( )
Syntax: >>> company output: ['HCL', 'IBM', 'Wipro']
list-name.sort( ) To sort a list in descending order:
>>>company=["IBM","HCL", "Wipro"]
>>> company.sort(reverse=True)
>>> company ['Wipro', 'IBM', 'HCL']

DELETING THE ELEMENTS FROM THE LIST USING DEL STATEMENT:


SYNTAX:
del list-name[index] # to remove element at specified index
del list-name[start:end] # to remove elements in list slice
Example:
>>> L=[10,20,30,40,50]
>>> del L[2] # delete the element at the index 2
>>> L
[10, 20, 40, 50]
>>> L= [10,20,30,40,50]
>>> del L[1:3] # deletes elements of list from index 1 to 2.
>>> L
[10, 40, 50]
>>> del L # deletes all elements and the list object too.
>>> L
NameError: name 'L' is not defined
Difference between del, remove( ), pop( ), clear( ):

S. del remove( ) pop( ) clear( )


No.

1 Statement Function Function Function


Deletes a single element Removes the first Removes an Removes all the
2 or a list slice or complete matching item from individual item and elements from
list. the list. returns it. list.
Removes all elements Removes all
3 and deletes list object elements but list
too. object still exists.

AMIT KUMAR KUSHWAHA Page 61


Difference between append( ), extend( ) and insert( ) :
S. append( ) extend( ) insert( )
No.
Adds an element at the
1 Adds single element in the Add a list in the end ofthe
endof the list. another list specified position.
(Anywhere in the list)
Takes one element as
2 argument Takes one list as Takes two arguments,
argument position and element.
The length of the list will
3 The length of the list The length of the listwill
willincrease by 1. increase by the length of increase by 1.
inserted list.
ACCESSING ELEMENTS OF NESTED LISTS:
Example:
>>> L=["Python", "is", "a", ["modern", "programming"], "language", "that", "we", "use"]
>>> L[0][0]
'P'
>>> L[3][0][2]
'd'
>>> L[3:4][0]
['modern', 'programming']
>>> L[3:4][0][1]
'programming'
>>> L[3:4][0][1][3]
'g'
>>> L[0:9][0]
'Python'
>>> L[0:9][0][3]
'h'
>>> L[3:4][1]
IndexError: list index out of range
Programs related to lists in python:
Program-1 Write a program to find the minimum and maximum number in a list.
L=eval(input("Enter the elements: "))
n=len(L)
min=L[0]
max=L[0]
for i in range(n):
if min>L[i]:

AMIT KUMAR KUSHWAHA Page 62


min=L[i]
if max<L[i]:
max=L[i]
print("The minimum number in the list is : ", min)
print("The maximum number in the list is : ", max)
Program-2 Find the second largest number in a list.
L=eval(input("Enter the elements: "))
n=len(L)
max=second=L[0]
for i in range(n):
if max<L[i]>second:
max=L[i]
second=max
print("The second largest number in the list is : ", second)

Program-3: Program to search an element in a list. (Linear Search).


L=eval(input("Enter the elements: "))
n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):

if L[i]==item:
print("Element found at the position :", i+1)
break
else:
print("Element not Found")
Output:
Enter the elements: 56,78,98,23,11,77,44,23,65
Enter the element that you want to search : 23
Element found at the position : 4

AMIT KUMAR KUSHWAHA Page 63


TUPLES

INTRODUCTION:
 A tuple is an ordered sequence of elements of different data types, such as integer, float, string, list
or even a tuple.
 Tuple is a collection of elements which is ordered and unchangeable (Immutable).Immutable means
you cannot change elements of a tuple in place.
 Allows duplicate members.
 Consists the values of any type, separated by comma.
 Tuples are enclosed within parentheses ( ).
 Cannot remove the element from a tuple
 Like list and string, elements of a tuple can be accessed using index values, starting from 0.

Example :
>>> tuple1 = (1,2,3,4,5) #tuple1 is the tuple of integers
>>> tuple2 =('Economics',87,'Accountancy',89.6) # tuple2 is the tuple of mixed data types
>>> tuple3 = (10,20,30,[40,50]) # tuple3 is the tuple with list as an element
>>> tuple4 = (1,2,3,4,5,(10,20)) # tuple 4 is the tuple with tuple as an element
Creating Tuple:
Syntax:
tuple-name = ( ) # empty tuple
tuple-name = (value-1, value-2, , value-n)
Example:
>>> T=(23, 7.8, 64.6, 'h', 'say')
>>> T
(23, 7.8, 64.6, 'h', 'say')
Creating a tuple with single element:
>>> T=(3) #With a single element without comma, it is a value only, not a tuple
>>> T
3
>>> T= (3, ) # to construct a tuple, add a comma after the single element
>>> T
(3,)
>>> T1=3, # It also creates a tuple with single element
>>> T1
(3,)
Tuple created without parenthesis ( ) :A sequence of without parenthesis i.e. values separated with
comma is treated as tuple by default.

AMIT KUMAR KUSHWAHA Page 64


# A sequence without parentheses is treated as tuple by default
>>> seq = 1,2,3 #comma separated elements
>>> type(seq) #treated as tuple
<class 'tuple'>
>>> print(seq) #seq is a tuple
(1, 2, 3)
# A sequence having different types of values
>>> seq = 1, "www.anjeevsinghacademy.com", 2, "www.mycstutorial.in"
>>> type(seq)
<class 'tuple'>
>>> print(seq)
(1, 'www.anjeevsinghacademy.com', 2, 'www.mycstutorial.in')
CREATING A TUPLE USING tuple ( ) CONSTRUCTOR: It is also possible to use the tuple( ) constructor to create
a tuple.
>>>T=tuple( ) # empty tuple
>>> T=tuple((45,3.9, 'k',22)) #note the double round-brackets
>>> T
(45, 3.9, 'k', 22)
>>> T2=tuple('hello') # for single round-bracket, the argument must be of sequence type
>>> T2
('h', 'e', 'l', 'l', 'o')
>>> T3=('hello','python')
>>> T3
('hello', 'python')
NESTED TUPLES:
>>> T=(5,10,(4,8))
>>> T
(5, 10, (4, 8))
CREATING A TUPLE BY TAKING INPUT FROM THE USER:
>>> T=tuple(input("enter the elements: "))
enter the elements: hello python
>>> T
('h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n')
>>> T1=tuple(input("enter the elements: "))
enter the elements: 45678
>>> T1
('4', '5', '6', '7', '8') # it treats elements as the characters though we entered digits
To overcome the above problem, we can use eval( ) method, which identifies the data type and evaluate them
automatically.

AMIT KUMAR KUSHWAHA Page 65


>>> T1=eval(input("enter the elements: "))
enter the elements: 56789
>>> T1
56789 # it is not a list, it is an integer value
>>> type(T1)
<class 'int'>
>>> T2=eval(input("enter the elements: "))
enter the elements: (1,2,3,4,5) # Parenthesis is optional
>>> T2
(1, 2, 3, 4, 5)
>>> T3=eval(input("enter the elements: "))
enter the elements: 6, 7, 3, 23, [45,11] # list as an element of tuple
>>> T3
(6, 7, 3, 23, [45, 11])
ACCESSING TUPLES:
o Tuples are very much similar to lists. Like lists, tuple elements are also indexed.Forward
indexing as 0,1,2,3,4……… and backward indexing as -1,-2,-3,-4,………
o The values stored in a tuple can be accessed using the slice operator ([ ] and [:]) with indexes.
o tuple-name[start:end] will give you elements between indices start to end-1.
o The first item in the tuple has the index zero (0).
ACCESSING ELEMENTS IN A TUPLE
Elements of a tuple can be accessed in the same way as a list or string using indexing and slicing.
Example : >>> tuple1 = (2,4,6,8,10,12)
>>> tuple1[0] # Accessing the first element of tuple1
2
>>> tuple1[3] # Accessing the fourth element of tuple1
8
>>>tuple1[1+4] # an expression resulting in an integer index
12
# Backward Accessing
>>> tuple1[-1] # Accessing the first element from right
12
>>> tuple1[-3] # Accessing the third element from right
8
# Index out of range : If invalid index is given then python raise an error message - IndexError : Index out of
range.
>>> tuple1[15] #returns error as index is out of range
IndexError: tuple index out of range

AMIT KUMAR KUSHWAHA Page 66


DIFFERENCE BETWEEN TUPLE AND LIST
S. No. List Tuple

1 Ordered and changeable (Mutable) Ordered but unchangeable (Immutable)

2 Lists are enclosed in brackets. [] Tuples are enclosed in parentheses. ( )

3 Element can be removed. Element can’t be removed.


Tuple is Immutable :Tuple is an immutable data type. It means that the elements of a tuple cannot be
changed after it has been created. An attempt to do this would lead to an error.
>>> tuple1 = (1,2,3,4,5)
>>> tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment
Elements of Tuple is Mutable (If element is a list) :An element of a tuple may be of mutable type, e.g., a
list.
>>> tuple2 = (1,2,3,[8,9]) # 4th element of the tuple2 is a list
>>> tuple2[3][1] = 10 # modify the list element of the tuple tuple2
# modification is reflected in tuple2
>>> tuple2
(1, 2, 3, [8, 10])
TRAVERSING A TUPLE:
Syntax: for <variable> in tuple-name:
statement
Example:
Method-1
>>> alpha=('q','w','e','r','t','y')
>>> for i in alpha:
print(i)
Output:
q
w
e
r
t
y
Method-2
>>> for i in range(0, len(alpha)):
print(alpha[i])
Output:
q
w
e

AMIT KUMAR KUSHWAHA Page 67


r
t
y

Tuple Operations:
 Joining operator +
 Repetition operator *
 Slice operator [:]
 Comparison Operator <, <=, >, >=, ==, !=
Joining Operator: It joins two or more tuples.Example:
>>> T1 = (25,50,75)
>>> T2 = (5,10,15)
>>> T1+T2
(25, 50, 75, 5, 10, 15)
>>> T1 + (34)
TypeError: can only concatenate tuple (not "int") to tuple
>>> T1 + (34, )
(25, 50, 75, 34)
Create a new tuple which contains the result of this concatenation operation.
>>> tuple3 = ('Red','Green','Blue')
>>> tuple4 = ('Cyan', 'Magenta', 'Yellow' ,'Black')
>>> tuple5 = tuple3 + tuple4 # tuple5 stores elements of tuple3 and tuple4
>>> tuple5
('Red','Green','Blue','Cyan','Magenta','Yellow','Black')
Repetition Operator: It replicates a tuple, specified number of times.
Example: T1 =(25, 50, 75)
>>> T1*2
(25, 50, 75, 25, 50, 75)
>>> T2=(10,20,30,40)
>>> T2[2:4]*3
(30, 40, 30, 40, 30, 40)
Membership operator [ in and not in ]
 in : The in operator checks if the element is present in the tuple and returns True, else it returns
False.
>>> tuple1 = ('Red','Green','Blue')
>>> 'Green' in tuple1
True
 not in : The not in operator returns True if the element is not present in the tuple, else it returns
False.
>>> tuple1 = ('Red','Green','Blue')

AMIT KUMAR KUSHWAHA Page 68


>>> 'Green' not in tuple1
False
SLICE OPERATOR:
tuple-name[start:end] will give you elements between indices start to end-1.
>>>alpha=('q','w','e','r','t','y')
>>> alpha[1:-3]
('w', 'e')
>>> alpha[3:65]
('r', 't', 'y')
>>> alpha[-1:-5]
()
>>> alpha[-5:-1]
('w', 'e', 'r', 't')
List-name[start:end:step] will give you elements between indices start to end-1 withskipping elements as
per the value of step.
>>> alpha[1:5:2]
('w', 'r')
>>> alpha[ : : -1]
('y', 't', 'r', 'e', 'w', 'q') #reverses the tuple
 >>> tuple1 = (10,20,30,40,50,60,70,80) # tuple1 is a tuple
 >>> tuple1[2:7] # elements from index 2 to index 6
(30, 40, 50, 60, 70)
 >>> tuple1[0:len(tuple1)] # all elements of tuple are printed
(10, 20, 30, 40, 50, 60, 70, 80)
 >>> tuple1[:5] # slice starts from zero index
(10, 20, 30, 40, 50)
 >>> tuple1[2:] # slice is till end of the tuple

(30, 40, 50, 60, 70, 80)


 >>> tuple1[0:len(tuple1):2] # step size 2
(10, 30, 50, 70)
Backward Slicing / Negative Indexing
 >>> tuple1[::-1] # slice in reverse of the tuple
(80, 70, 60, 50, 40, 30, 20, 10)
 >>> tuple1[-1: -(len(tuple)+1):-1]
(80, 70, 60, 50, 40, 30, 20, 10)
 >>> tuple1[-1: -(len(tuple)+1):-2] # slice in reverse alternate element of the tuple
(80,60,40,20)
 >>> tuple1[-6:-4] # negative indexing

AMIT KUMAR KUSHWAHA Page 69


(30, 40)

COMPARISON OPERATORS:
Compare two tuples
 Python internally compares individual elements of tuples in lexicographical order.
 It compares the each corresponding element must compare equal and two sequences must be of the
same type.
 For non-equal comparison as soon as it gets a result in terms of True/False, from corresponding
elements’ comparison. If Corresponding elements are equal, it goes to the next element and so on,
until it finds elements that differ.
Example:
>>> T1 = (9, 16, 7)
>>> T2 = (9, 16, 7)
>>> T3 = ('9','16','7')
>>> T1 = = T2
True
>>> T1==T3
False
>>> T4 = (9.0, 16.0, 7.0)
>>> T1==T4
True
>>> T1<T2
False
>>> T1<=T2
True
TUPLE METHODS:
Consider a tuple:
subject=("Hindi","English","Maths","Physics")

S. Function
Description Example
No. Name
1 len( ) Find the length of a tuple. >>>subject=("Hindi","English","Maths","Physics”)
Syntax: len (tuple-name) >>> len(subject)4
2 max( ) Returns the largest value >>> max(subject)'Physics'
from a tuple.
Syntax: max(tuple-name)

AMIT KUMAR KUSHWAHA Page 70


Error: If the tuple contains values of different data types, then it will give an errorbecause mixed
data type comparison is not possible.
>>> subject = (15, "English", "Maths", "Physics", 48.2)
>>> max(subject)
TypeError: '>' not supported between instances of 'str' and 'int'
3. min( ) Returns the smallest >>>subject=("Hindi","English","Maths","Physics")
value from a tuple. >>> min(subject)
Syntax: min(tuple-name) 'English'
Error: If the tuple contains values of different data types, then it will give an errorbecause mixed
data type comparison is not possible.
>>> subject = (15, "English", "Maths", "Physics", 48.2)
>>> min(subject)
TypeError: '>' not supported between instances of 'str' and 'int'
4 index( ) Returns the index of the first >>>subject=("Hindi","English","Maths","Physics")
element with the specified >>> subject.index("Maths")
value. 2
Syntax:
tuple-name.index(element)
5 count( ) Return the number of >>> subject.count("English")
times the value appears. 1
Syntax:
tuple- name.count(element)
6 sorted() Takes elements in the tuple and >>> tuple1 = (“Rama”,”Heena”,”Raj”, “Mohsin”,
returns a new sorted list. It ”Aditya”)
should be noted that, sorted()
>>> sorted(tuple1)
does not make any change to
the original tuple. [‘Aditya’, ‘Heena’, ‘Mohsin’, ‘Raj’, ‘Rama’]

7 Sum() Returns sum of the elements of


>>> tuple1 = (19,12,56,18,9,87,34)
the tuple
>>> sum(tuple1)
235

Tuple Assignment : Assignment of tuple is allows a tuple of variables on the left side of the assignment
operator to be assignedrespective values from a tuple on the right side. The number of variables on the left
should be same as the number of elements in the tuple.
# The rst element 10 is assigned to num1 and the second element 20 is assigned to num2.
>>> (num1,num2) = (10,20)
>>> print(num1)
10
>>> print(num2)

AMIT KUMAR KUSHWAHA Page 71


20
>>> record = ( “Pooja”,40,”CS”)
>>> (name,rollno,subject) = record
>>> name
‘Pooja’
>>> rollno
40
>>> subject
‘CS’
>>> (a,b,c,d) = (5,6,8)
ValueError: not enough values to unpack (expected 4, got 3)
Tuple Packing and Unpacking:
Tuple Packing: Creating a tuple from set of values.
Example:
>>> T=(45,78,22)
>>> T
(45, 78, 22)

Tuple Unpacking : Creating individual values from the elements of tuple.


Example:
>>> a, b, c=T
>>> a
45
>>> b
78
>>> c
22
Note: Tuple unpacking requires that the number of variable on the left side must be equalto the length of
the tuple.
DELETE A TUPLE: The del statement is used to delete elements and objects but as you know that tuples
areimmutable, which also means that individual element of a tuple cannot be deleted.
Example:
>>> T=(2,4,6,8,10,12,14)
>>> del T[3]
TypeError: 'tuple' object doesn't support item deletion
But you can delete a complete tuple with del statement as:
Example:
>>> T=(2,4,6,8,10,12,14)
>>> del T
>>> T

AMIT KUMAR KUSHWAHA Page 72


NameError: name 'T' is not defined

Nested Tuples : A nested tuple is one that contains another tuple inside of it. Students’ names, roll
numbers, andgrades (in percentage) are saved in a tuple. We can create a nested tuple to contain the
information of many of these students.
Example –
st=((101,”Aman”,98),(102,”Geet”,95),(103,”Sahil”,87),(104,”Pawan”,79))
print(“S_No”,” Roll_No”,” Name”,” Marks”)
for i in range(0,len(st)):
print((i+1),’\t’,st[i][0],’\t’,st[i][1],’\t’,st[i][2])
Output:
S_No Roll_No Name Marks1
1. 101 Aman 98
2 102 Geet 95
3 103 Sahil 87
4 104 Pawan 79
 Function that work for nested tuple : len(),count(),index()
 Function which work for nested tuples having only tuples as elements max() ,min()
 Function that donot work for nested tuple : sum()
ACCESSING ELEMENT OF NESTED TUPLE
>>>T1=(11,’ram’,(68,77,78))
>>>student[2]
(68,77,78)
>>>student[2][0]
68
>>>student[2][2]
78
INDIRECTLY MODIFYING A TUPLE
a) Using Tuple unpacking : tuple are immutable, to change a tuple ,we would need to first unpack it,
change the values and then again repack it
T1=(11,22,33,44)
a,b,c,d=T1
c=77
T1=(a,b,c,d)
>>>T1
(11,22,77,44)
b) Using constructor of list and tuple
>>>T1=(11,22,77,44)

AMIT KUMAR KUSHWAHA Page 73


>>>L1=list(T1)
>>>L1
[11,22,77,44]
>>>L1[1]= 66
>>>L1
[11,66,77,44]
>>>T1=tuple(L1)
>>>T1
(11,66,77,44)
Program : Write a program to input n numbers from the user. Store these numbers in a tuple. Print the
maximum and minimum number from this tuple.
numbers = tuple() #create an empty tuple 'numbers'
n = int(input("How many numbers you want to enter?: "))
for i in range(0,n):
num = int(input()) # it will assign numbers entered by user to tuple 'numbers'
numbers = numbers +(num,)
print('\nThe numbers in the tuple are:')
print(numbers)
print("\nThe maximum number is:")
print(max(numbers))
print("The minimum number is:")
print(min(numbers))
Output:
How many numbers do you want to enter?: 5
9
8
10
12
15
The numbers in the tuple are:
(9, 8, 10, 12, 15)
The maximum number is:
15
The minimum
8

AMIT KUMAR KUSHWAHA Page 74


DICTIONARY
INTRODUCTION:

 Dictionary is a collection of elements which is unordered, changeable and indexed.


 Dictionary has keys and values.
 Doesn’t have index for values. Keys work as indexes.
 Dictionary doesn’t have duplicate member means no duplicate key.
 Dictionaries are enclosed by curly braces { }
 The key-value pairs are separated by commas ( , )
 A dictionary key can be almost any Python type, but are usually numbers , strings or tuple
 Values can be assigned and accessed using square brackets [ ].
CREATING A DICTIONARY:
Syntax:
dictionary-name = {key1:value, key2:value, key3:value, keyn:value}
Example:
marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>>print( marks)
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
>>> D = { } #Empty dictionary
>>> D
{ }
Note :
 There is no guarantee that elements in dictionary can be accessed as per specific order.
 Keys of a dictionary must be of immutable types, such as string, number, tuple.
Example:
>>> D1={[2,3]:"hello"}
TypeError: unhashable type: 'list'
DIFFERENT WAYS OF CREATING A DICTIONARY
 using dict( ) Constructor: Use the dict( ) constructor with single parentheses:
>>> marks=dict(Physics=75,Chemistry=78,Maths=81,CS=78)
>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
In the above case the keys are not enclosed in quotes and equal sign is used for assignment rather than
colon.
 dict ( ) constructor using parentheses and curly braces:
>>> marks=dict({"Physics":75,"Chemistry":78,"Maths":81, "CS":78})
>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
 dict( ) constructor using keys and values separately: use of ZIP function
>>> marks=dict(zip(("Physics","Chemistry","Maths","CS"),(75,78,81,78)))
>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}

AMIT KUMAR KUSHWAHA Page 75


In this case the keys and values are enclosed separately in parentheses and are given as argument to the zip( )
function. zip( ) function clubs first key with first value and so on.
 dict( ) constructor using key-value pairs separately:
o Example-A
>>> marks=dict([['Physics',75],['Chemistry',78],['Maths',81],['CS',78]])
# list as argument passed to dict( ) constructor contains list type elements.
>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
o Example-B
>>> marks=dict((['Physics',75],['Chemistry',78],['Maths',81],['CS',78]))
# tuple as argument passed to dict( ) constructor contains list type elements
>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
o Example-C
>>> marks=dict((('Physics',75),('Chemistry',78),('Maths',81),('CS',78)))
# tuple as argument to dict( ) constructor and contains tuple type elements
>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
CREATING DICTIONARY FROM KEYS – the fromkeys() method
This method is used to create new dictionary from a sequence containing all the keys and a common value,
which will be assigned to all the keys
Syntax : dict.fromkeys(<key sequence>,value)
Example : following code will create a dictionary having keys 1,5,8, and values as 90
nd=dict.fromkeys([1,5,8],90)
Output >>>nd {1:90,5:90,8:90}
If you specify only key sequence and donot give any value ,it will take none as the values for the keys
D=dict.fromkeys([2,6,10])
>>>D {2:None,6:None,10:None}
If you specify a sequence of values in place of the argument it will consider the whole sequence as the value for
the keys
D1=dict.fromkeys((3,4,5),(1,2,3))
>>>D1
{3:( 1,2,3),4: ( 1,2,3), 51,2,3)}
Note : keys argument must be an iterable sqence even if it is a single value
D1.fromkeys(3)
>>>D1
Type Error : ‘int’ object is not iterable
Correction : >>> D1.fromkeys(3,)
>>>D1
{3:None}
ACCESSING ELEMENTS OF A DICTIONARY:
Syntax: dictionary-name[key]

AMIT KUMAR KUSHWAHA Page 76


Example:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> marks["Maths"]
81
>>> marks["English"] #Access a key that doesn’t exist causes an error
KeyError: 'English'

>>> marks.keys( ) #To access all keys in one go


dict_keys(['physics', 'Chemistry', 'Maths', 'CS'])
>>> marks.values( ) # To access all values in one go
dict_values([75, 78, 81, 78])
Lookup : A dictionary operation that takes a key and finds the corresponding value, iscalled lookup.
TRAVERSING A DICTIONARY:
Syntax:
for <variable-name> in <dictionary-name>:
statement
Example:
>>> for i in marks:
print(i, ": ", marks[i])
OUTPUT:
physics : 75
Chemistry : 78
Maths : 81
CS : 78
CHANGE AND ADD THE VALUE IN A DICTIONARY: for addition in dictionary key must not exist but
for updation or change key must exist in dictionary
Syntax:
dictionary-name[key]=value
Example:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }

>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
>>> marks['CS']=84 #Changing a value
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
>>> marks['English']=89 # Adding a value
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
UPDATE AND SETDEFAULT () METHOD:
The setdefault () method: it insert a new key: value pair only if the key doesn’t already exist. If the key already
exist it returns current value of the key

AMIT KUMAR KUSHWAHA Page 77


Syntax : dict.setdefault(<key>:<value>)
Marks= {1: 98, 2: 99}
>>>Marks.setdefault(3,98)
98
>>>Marks
{1: 98, 2: 99,3:98}
>>> Marks.setdefault(2,98)
99
>>>Marks
Marks= {1: 98, 2: 99,3:98}
Update methods () : this method merges key: value pair from the new dictionary into the original dictionary.
Adding or replacing as needed
Example :
>>>Emp={‘name’:’John’,’salary’:10000,’age’:23}

>>>Emp1={‘name’:’Divya’,’salary’:54000,’Dept’:’Sales}
>>>Emp.update(Emp1)
>>>Emp
{’salary’:54000, ‘name’:’Divya’,‘dept’:’sales’,’age’:23}
Q- Write a program to create a Dictionary M which stores the marks of the students of the class with
rollno as keys and marks as values. Get the number of students as input
Ans : M={ }
n=int(input(“How many students ”))
for i in range(n):
r= eval(input(“enter rollno : ”)
m=eval(input(“enter marks : ”)
M[r]=m
print(“dictionary created”)
print(M)
Output
How many students 2
enter rollno:1
enter marks:98
enter rollno:2
enter marks:97
Dictionary created
{1: 98, 2: 97}
Q- modify marks of a student in dictionary M created above. Enter the rollno of the student whose marks
to modify
R = int(input(“Enter rollno number”))
if R in M:
M[R]=int(input(“Enter new marks”))

AMIT KUMAR KUSHWAHA Page 78


else:
print(“no such rollno found”)
print(M)
output
How many students 2
enter rollno:1
enter marks:98
enter rollno:2
enter marks:97
Dictionary created

{1: 98, 2: 97}


Enter rollno number 2
Enter new marks 99
{1: 98, 2: 99}
DELETE ELEMENTS FROM A DICTIONARY:
There are two methods to delete elements from a dictionary:
1. using del statement
2. using pop( ) method
3. using popitem() method
Using del statement: for this key must exist in dictionary otherwise it will give key error
Syntax:
del dictionary-name[key]
Example:

>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
>>> del marks['English']
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
>>> del marks[Ip]
KeyError : IP
If you simply write
>>>del marks # it will delete whole dictionary
Using pop( ) method: It deletes the key-value pair and returns the value of deleted element.
Syntax:
dictionary-name.pop( )
Example:
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
>>> marks.pop('Maths')
81

AMIT KUMAR KUSHWAHA Page 79


>>> marks.pop('IP', ”Not there”) #you can specify an error message if key is not present in
dictionary if you do not specify any error message it will
generate key error
Advantage of pop() method over del() : in you can specify an error message which will be return as output if
key is not present in dictionary if you do not specify any error message it will generate key error. But in del
there is no ways to specify your error message
Using popitem () method – it will remove key: value pair from the dictionary
 it returns the items which was the last item entered in the dictionary .
 it return deleted key value pair in the form of tuple
 if the dictionary is empty it will raise key Error
Syntax:
dictionary-name.popitem( )
Example:
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
>>> marks.popitem()
(‘CS’,84)
Difference between pop and popitem () method: pop will delete an item with a chosen key while popitem
will delete last item of the dictionary. In pop we can specify error message while it is not so in popitem () it will
generate an key error message
Clear () method : this method removes all the element of the dictionary and dictionary becomes empty but it
doesn’t delete the dictionary empty dictionary object remains
Syntax:
dictionary-name.clear( )
Example:
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
>>>marks.clear()
>>>marks
{}
Difference between clear () and del() method: clear method this method removes all the element of the
dictionary and dictionary becomes empty but it doesn’t delete the dictionary empty dictionary object remains.
Del method will delete whole dictionary along with its structure
CHECK THE EXISTANCE OF A KEY IN A DICTIONARY:
To check the existence of a key in dictionary, two operators are used:
 in : it returns True if the given key is present in the dictionary, otherwise False.
 not in : it returns True if the given key is not present in the dictionary, otherwise False.
Example:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> 'Chemistry' in marks
True
>>> 'CS' not in marks

AMIT KUMAR KUSHWAHA Page 80


False
>>> 78 in marks # in and not in only checks the existence of keys not values False
However, if you need to search for a value in dictionary, then you can use in operatorwith the following
syntax:
value in dictionary-name. values( )
Example:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>> 78 in marks.values( )
True
PRETTY PRINTING A DICTIONARY:
What is Pretty Printing?
To print a dictionary in more readable and presentable form. For pretty printing a dictionary you need to
import json module and then you can use dumps( ) function from json module.
Example:
>>> print(json.dumps(marks, indent=2))
OUTPUT:
{ "physics": 75,
"Chemistry": 78,

"Maths": 81,
"CS": 78 }
dumps( ) function prints key:value pair in separate lines with the number of spaceswhich is the value of
indent argument.
COUNTING FREQUENCY OF ELEMENTS IN A LIST USING DICTIONARY
Steps:
 import the json module for pretty printing
 Take a string from user
 Create a list using split( ) function
 Create an empty dictionary to hold words and frequency
 Now make the word as a key one by one from the list
 If the key not present in the dictionary then add the key in dictionary and count
 Print the dictionary with frequency of elements using dumps( ) function
PROGRAM
import json
sentence=input("Enter a string: ")
L = sentence.split()
d={ }
for word in L:
key=word
if key not in d:
count=L.count(key)
d[key]=count

AMIT KUMAR KUSHWAHA Page 81


print("The frequqency of elements in the list is as follows: ")
print(json.dumps(d,indent=2))

Function/Method Purpose Example


len() This function returns the >>>d={1: 'Amrit', 2:
number of elements i.e.the key- 'Bhavesh', 3: 'Chetan', 4:'Falguni', }
value pairs present in the >>> len(d)
dictionary. 6

d.items() This function returns the list of >>> d.items() dict_items([(1, 'Amrit'), (2,
elements in the dictionary. 'Bhavesh'), (3, 'Chetan'),(4, 'Falguni')])

d.keys() This function returns theall the >>> d.keys()


keys that are present in the dict_keys([1, 2, 3, 4])
dictionary.
This returns all the values in the >>> d.values() dict_values(['Amrit','Bhavesh',
d.values() dictionary. Chetan', 'Falguni'])

d.get(key) This function returns the value >>> d.get(2)'Bhavesh'


corresponding to a key in the >>> d.get(8, -1)
dictionary. If the key is not -1
present, the function returns,
'None'.
d.update(object) This function merges the object >>> d2={5: 'Kartikay', 6:'Prerna'}
enclosed in brackets with d. >>> d.update(d2)
>>> d
{1: 'Amrit', 2: 'Bhavesh', 3:'Chetan', 4:
'Falguni', 5:'Kartikay', 6: 'Prerna'}

d.clear() This function clears the entire


>>>d2={1:"Deer",2:"Bear", 3:"Cat",
dictionary. It deletes all the key-
4:"Elephant"}
valuepairs. >>>d2
{1:"Deer", 2:"Bear",3:"Cat", 4:"Elephant"}
>>>d2.clear()
>>>d2
{}
d.pop(key) This function removes a key >>> d2={1:"Apple", 2:"Ball",
along with its value in a 3:"Pineapple",4:"Mangoes"}
dictionary. >>> d2.pop(2)'Ball'
>>> d2
{1: 'Apple', 3: 'Pineapple',4: 'Mangoes'}

AMIT KUMAR KUSHWAHA Page 82


UNDERSTANDING SORTING
SORTING: To arrange the elements in ascending or descending order.
In this chapter we shall discuss two sorting techniques:
 Bubble Sort
 Insertion Sort
BUBBLE SORT: Bubble sort is a simple sorting algorithm. It is based on comparisons, in which each element
is compared to its adjacent element and the elements are swapped if theyare not in proper order

PROGRAM: BUBBLE SORT


L=eval(input("Enter the elements:"))
n=len(L)
for p in range(0,n-1):
for i in range(0,n-1):
if L[i]>L[i+1]:
L[i], L[i+1] = L[i+1],L[i]
print("The sorted list is : ", L)

OUTPUT:
Enter the elements:[60, 24, 8, 90, 45, 87, 12, 77]
The sorted list is : [8, 12, 24, 45, 60, 77, 87, 90]
INSERTION SORT: Sorts the elements by shifting them one by one and inserting
theelement at right position.

AMIT KUMAR KUSHWAHA Page 83


PROGRAM: INSERTION SORT

L=eval(input("Enter the elements: "))


n=len(L)
for j in range(1,n):
temp=L[j]
prev=j-1
while prev>=0 and L[prev]>temp: # comparison the elements
L[prev+1]=L[prev] # shift the element forward
prev=prev-1
L[prev+1]=temp #inserting the element at proper position
print("The sorted list is :",L)

OUTPUT:
Enter the elements: [45, 11, 78, 2, 56, 34, 90, 19]
The sorted list is : [2, 11, 19, 34, 45, 56, 78, 90]

AMIT KUMAR KUSHWAHA Page 84


SOCIETY, LAW AND ETHICS

DIGITAL FOOTPRINT :A digital footprint -- sometimes called a digital shadow -- is the body of data that an
individual creates through their actions online. Almost every online activity leaves some form of digital trace.
A digital footprint is relatively permanent, and once the data is public -- or even semipublic, as may be the case
with social media -- the owner has little control over how it is used by others. For that reason, a major focus of
digital footprint management is caution about online activities to control the data that can be gathered in the first
place.
Types of digital footprint
 Active digital footprints consist of data a user leaves intentionally. The user is also aware of the digital
trace they leave behind because they have deliberately submitted information.
 Passive digital footprints are composed of data a user leaves behind unintentionally on the internet.
Website visits and actions, searches and online purchases are among the online activities that add
passive data traces to a digital footprint.
DIGITAL SOCIETY reflects the growing trend of using digital technologies in all
spheres of human activities. But while online, all of us need to be aware of how to
conduct ourselves, how best to relate with others and what ethics, morals and values to
maintain.
DIGITAL CITIZEN Anyone who uses digital technology along with Internet is a
digital citizen or a netizen. Being a good netizen means practicing safe, ethical and
legal use of digital technology. A responsible netizen must abide by net etiquettes,
communication netiquettes and social media etiquettes.
NET ETIQUETTES: We follow certain etiquettes during our social interactions. Similarly, we
need to exhibit proper manners and etiquettes while being online One should be ethical,
respectful and responsible while surfing the Internet.
a) Be Ethical
 No copyright violation: we should not use copyrighted materials without the
permission of the creator or owner
 Share the expertise: it is good to share information and knowledge on Internet so that
others can access it The information shared should be true and unambiguous
b) Be Respectful
 Respect privacy: as good digital citizens we have the right to privacy and the
freedom of personal expression and same others also have should not share those
images, documents, files, etc., with any other digital citizen without each others’
consent.
 Respect diversity: in a group or public forum, we should respect the diversity of the
people in terms of knowledge, experience, culture and other aspects.
c) Be Responsible
 Avoid cyber bullying: bullying online can have very serious implications on the other
person (victim).
 Don’t feed the troll: an Internet troll is a person who deliberately sows discord on the
Internet by starting quarrels or upsetting people, by posting inflammatory or off topic

AMIT KUMAR KUSHWAHA Page 85


messages in an online community, just for amusement. Since trolls thrive on attention, the
best way to discourage trolls is not to pay any attention to their comments
Communication Etiquettes: Digital communication includes email, texting, instant messaging,
talking on the cell phone, audio or video conferencing, posting on forums, social networking
sites, etc. All these are great ways to connect with people in order to exchange ideas, share data
and knowledge. Digital citizen to abide by the communication etiquettes
 Be Precise
 Be Polite
 Be Credible
Social Media Etiquettes : Facebook, Google+, Twitter, Instagram, Pinterest, or the YouTube
channel. Social media are websites or applications that enable their users to participate in social
networking by creating and sharing content with others in the community. These platforms
encourage users to share their thoughts and experiences through posts or pictures
In social media too, there are certain etiquettes we need to follow-
a) Be Secure
 Choose password wisely
 Know who you befriend
 Beware of fake information
b) Be Reliable :Think before uploading as once anything is uploaded it will remain in the
server even if you delete it hence need to be cautious while uploading or sending sensitive or
confidential files which have a bearing on our privacy
DATA PROTECTION: In this digital age, data or information protection is mainly about the
privacy of data stored digitally. Elements of data that can cause substantial harm, embarrassment,
inconvenience and unfairness to an individual, if breached or compromised, is called sensitive data.
Privacy of sensitive data can be implemented by encryption, authentication, and other secure
methods to ensure that such data is accessible only to the authorized user and is for a legitimate
purpose.
Intellectual Property Right (IPR): Intellectual Property refers to the inventions, literary and
artistic expressions, designs and symbols, names and logos. The ownership of such concepts lies
with the creator, or the holder of the intellectual property. This enables the creator or copyright
owner to earn recognition or financial benefit by using their creation or invention. Intellectual
Property is legally protected through copyrights, patents, trademarks,etc.

COPYRIGHT grants legal rights to creators for their original works like writing, photograph, audio
recordings, Copyright law gives the copyright holder a set of rights that they alone can avail legally.
The rights include right to copy (reproduce) a work, right to create derivative works based upon it,
right to distribute copies of the work to the public, and right to publicly display or perform the
work. It prevents others from copying, using or selling the work.

A PATENT is usually granted for inventions. Unlike copyright, the inventor needs to apply (file)
for patenting the invention. When a patent is granted, the owner gets an exclusive right to prevent
others from using, selling, or distributing the protected invention. Patent gives full control to the
patentee to decide whether or how the invention can be used by others. A patent protects an
invention for 20 years, after which it can be freely used

AMIT KUMAR KUSHWAHA Page 86


TRADEMARK includes any visual symbol, word, name, design, slogan, label, etc., that
distinguishes the brand or commercial enterprise, from other brands or commercial enterprises

Violation of IPR
Plagiarism : It is stealing someone else’s intellectual work( idea, literary/academic work, etc.) and
representing it as your own work without citing the source of information or giving credit to creator.
How to avoid plagiarism?
 You must give credit whenever you use:
 Another person’s idea, opinion, or theory.
 Quotation of another person’s actual spoken or written words.
Copyright Infringement: Copyright infringement is when we use other person’s work without
obtaining their permission to use or we have not paid for it, if it is being sold. Hence, check the
copyright status of writer’s work before using it to avoid plagiarism.
Trademark Infringement: Trademark Infringement means unauthorized use of other’s trademark
on products and services. An owner of a trademark may commence legal proceedings against
someone who infringes its registered trademark.

Public Access and Open Source Software


Copyright sometimes put restriction on the usage of the copyrighted works by anyone else.
Licenses provide rules and guidelines for others to use the existing work. When authors share their
copyrighted works with others under public license, it allows others to use and even modify the
content. Open source licenses help others to contribute to existing work or project without seeking
special individual permission to do so.
The GNU General public license (GPL) and the Creative Commons (CC) are two popular
categories of public licenses CC enables the free distribution of an otherwise copyrighted work. It
is used when an author wants to give people the right to share, use and build upon a work that they
have created. GPL is primarily designed for providing public licence to a software. GNU GPL is
another free software license, which provides end users the freedom to run, study, share and
modify the software, besides getting regular updates.
Free and open source software (FOSS) has a large community of users and developers who are
contributing continuously towards adding new features or improving the existing features. For
example, Linux kernel-based operating systems like Ubuntu and Fedora come under FOSS.

Apache Licence ; Offers following rights:


1. Perpetual rights
2. Worldwide rights
3. No fee or royalty
4. Non-exclusive rights
5. Rights are irrevocable
Cybercrime
- Any criminal offence that is facilitated by or involves the use of, electronic communications or
information systems, including any electronic device, computer, or the internet is referred to as

AMIT KUMAR KUSHWAHA Page 87


Cyber Crime.
- e.g.
* Credit card frauds
* Phishing
* Illegal downloading
* Child pornography
* Cyber bullying. etc.

Phishing
- It is the practice of attempting to acquire sensitive information from individuals over the internet,
by means of deception.
- Information targeted by phishing include:
 User-name, passwords
 Bank account information
 Credit/debit card details
- In phishing, an imposter uses an authentic looking email or website to trick recipients into giving out
sensitive personal information.
HACKING : Hacking is the act of unauthorized access to a computer, computer network or any
digital system. Hacker is the one who tries to gain unauthorized access to computers or networks
in order to steal sensitive data with the intent to damage or bring down systems. Hackers try
to break through system securities for identity theft, monetary gain, to bring a competitor or rival
site down, to leak sensitive information, etc.
RANSOM WARE: This is another kind of cyber crime where the attacker gains access to the
computer and blocks the user from accessing, usually by encrypting the data. The attacker
blackmails the victim to pay for getting access to the data, or sometimes threaten to publish
personal and sensitive information or photographs unless a ransom is paid. Ransom ware can get
downloaded when the users visit any malicious or unsecure websites or download software from
doubtful repositories
EAVESDROPPING: n eavesdropping attack occurs when a hacker intercepts, deletes, or modifies data that is
transmitted between two devices. Eavesdropping, also known as sniffing or snooping, relies on unsecured
network communications to access data in transit between devices.
CYBER TROLL: An internet troll, or online bully, deliberately tries to offend, cause trouble or directly attack
people by posting derogatory comments on Facebook posts, blogs, under YouTube videos, on forums and other
social media, such as Twitter and Instagram
CYBER BULLYING: Cyber bullying includes sending, posting, or sharing negative, harmful, false, or mean
content about someone else. It can include sharing personal or private information about someone else causing
embarrassment or humiliation. Some cyber bullying crosses the line into unlawful or criminal behavior

IDENTITY THEFT: stealing someone’s online identity (social media account, email etc.), and posting
fraudulent post or carrying out malicious activity (spread of rumors etc.)
How stealing carried out?
 Through Phishing
 Stealing your information, provided during online purchase.

AMIT KUMAR KUSHWAHA Page 88


PREVENTING CYBER CRIME
 Take regular backup of important data
 Use an antivirus software and keep it updated always
 Avoid installing pirated software. Always download software from known and secure
(HTTPS) sites
 Always update the system software which include the Internet browser and other application
software
 Do not visit or download anything from untrusted websites
 Use strong password for web login, and change it periodically.
 While using someone else’s computer, don’t allow browser to save password or auto fill
data, and try to browse in your private browser window
 For an unknown site, do not agree to use cookies when asked for, through a Yes/No
option.
 Always secure wireless network at home with strong password and regularly change it.
E-WASTE MANAGEMENT
E-WASTE: E-waste i.e. electronic waste refers to discarded electrical or electronic devices such as discarded
computers, mobile phones, television sets and refrigerators etc.
CHARACTERISTICS OF E-WASTE
 Fastest growing segment of waste
 Most valuable due to its basic composition
 Very hazardous if not handled carefully
Composition of E-Waste
Electrical and electronic equipment contain metallic and non-metallic elements, alloy or
compounds such as copper, Aluminum, Gold, silver, Platinum, Nickel, Tin, Lead, Iron,
Sulphur, Phosphorus, Arsenic etc.
E-Waste disposal methods
a. Dismantling :Removal of parts containing dangerous substances (CFCs, Mercury); removal of
easily accessible parts containing valuable substances.(copper and other precious metals).
b. Segregation of Ferrous & non-ferrous metals and plastic : Separation is normally done in a
shredder process.
c. Reuse : Some parts in e-waste can be easily reused with minor repairs.
d. RECYCLING : e-waste can be recycled also to obtain other useful materials.
Benefits of e-waste recycling
 Allows for recovery of valuable precious metals.
o Electronic equipment contains precious metals like platinum, gold, zinc etc. which can be
recycled.
 Protects Public health and water quality
o E-waste contains toxic substances, such as mercury, lead etc. Improper disposal releases these
harmful toxins in environment.
o Therefore proper disposal of e-waste ensures public health and environment safety.
 Creates Jobs

AMIT KUMAR KUSHWAHA Page 89


o Recycling e-waste domestically creates jobs for professional recyclers.
 Saves landfill space
o E-waste is a growing waste stream. Recycling these items will help conserve landfill space.

COMPUTER FORENSICS/DIGITAL FORENSICS

It refers to methods used for interpretation of computer media for digital evidence. It provides our legal
system (courts) with a way to recover data from electronic or digital services.
Goal of process: To preserve any evidence in its most original form while performing a structured
investigation by collecting, identifying and validating the digital information for the purpose of reconstructing
past events.
CYBER LAW AND IT ACT: Cyber law is a generic term which refers to all the legal and regulatory aspects
of Internet and the World Wide Web.
The growth of e-commerce and accessibility of internet to common people has propelled the need for vibrant and
effective regulatory mechanisms which would further strengthen the legal infrastructure.
India’s IT Act and IT (Amendment) Act, 2008
In India the cyber laws are enforced through Information Technology Act, 2000 (IT Act 2000). Its prime
purpose was to provide legal recognition to electronic commerce.
This act was amended in December 2008 through the IT (Amendment) Act, 2008. It came into force from
Oct. 27, 2009. It provided additional focus on Information Security and added several new sections on offences
including Cyber Terrorism and Data Protection.
Other major amendments of IT Act(2008) included:
 Authentication of electronic records by digital signatures gets legal recognition.
 E-documents gets legal recognition.
TECHNOLOGY AND SOCIETY : Information and Communication Technology (ICT) capabilities has led to
social and economic development of society.
Reasons:
 Enable greater efficiency in economic and social processes.
 Enhance the effectiveness of cooperation between different stakeholders ; and
 Increase the volume and range of information available to people, businesses and governments.
SOCIAL IMPACTS/BENEFITS OF TECHNOLOGY:

 Enhanced freedom of expression and associations.


 New pattern of work and human settlements.
 Change in relationship between government and citizens.
ECONOMIC IMPACTS/BENEFITS OF TECHNOLOGY:
 Globalization of production in goods and services.
 Change in international trade and distribution networks.
 Facility of Secure Transactions to most part of world with a greater security.
 Ease and Availability of making payments (24 x 7)
 With ICT, now the market is entire globe. Small business can reach any part of the world.

AMIT KUMAR KUSHWAHA Page 90


GENDER ISSUES WHILE TEACHING/USING COMPUTERS

- Major issue : ‘under representation’ of girls. i.e. there are far less girls than boys who opted
for computer science subject in the high school.
Reasons:

1. Preconceived Notions – ‘boys are better at technical things’ , ‘girls must take up a
career keeping in mind that they have to raise family’ , ‘teaching is best career option for
girls’, etc. have their impact in decision making of girls while taking up subjects.
2. Lack of Interest – playing games (mostly boys-centric) increases boys interest in
computers. Moreover, boys get to play more on smartphones/computers (in Indian
scenario) and develop more interest in computers than girls.
3. Lack of motivation - Girls are pressurized to choose a career option which will give
them ‘work life balance’.
4. Lack of Role Models – Girls these days see less of role models in the field of
‘Computer Science’ whom they can imitate. This also influence girls psychologically and
they infer that ‘Computer Science’ is for boys and do not take up the subject.
Possible solutions to remove this under representation:

1. There should be more initiatives supported by government and run by many tech-
giants to encourage more girls to take up ‘Computer Science’ subject.
2. The film and TV censor board should ensure fair representation of female role models in TV,
Cinema etc. so that more girls get encouraged to take up ‘Computer Science’.
DISABILITY ISSUES WHILE TEACHING AND USING COMPUTERS
- In order to provide conducive study environment for students with disabilities in the field of technology,
the emphasis has been given to ‘Inclusive Education’ and ‘Promotion of Accessibility’.
- But still there are some challenges which needs to be addressed:
1. Unavailability of Teaching Materials/Aids
o Students with different disabilities need different types of teaching aids/materials.
 e.g. visually challenged students would want there are screen readers that could read
the digital content to them; also programming lessons should not involve visual inputs.
 Similarly, hearing impaired students would want more of visual input than
oratory, rather oratory instructions should be available in sign language, if possible.
 For most students with locomotors disabilities, virtual keyboard is required for writing
programs. For such virtual keyboard, sophisticated virtual keyboard hardware is
required.
 Unavailability of such supportive programming aids and software are a big
issue that must be handled by schools and their managements.
2. Lack of Special Teachers
• For different types of special needs, if special needs teachers are available,
disabled students get their needs addressed in right manner.

AMIT KUMAR KUSHWAHA Page 91


• There should be teachers who know what types of hardware, software, tools

etc. can be used for the differently able students as per their specific needs,
e.g. special types of specialized hardware such as Braille keyboards,
monitors, printers, synthetic speech generators etc.
3. Lack of Supporting Curriculum
• Curriculum should be designed while keeping focus on inclusive education.
• There always should be possible alternatives keeping in mind special needs of the
students.
• Software and programs should be so used so that the disabled students can easily work
on that.

Possible Solutions
 Schools must work toward making available the required teaching aids/materials to fulfil special
needs of students with disabilities.
 There should be proper budget allocated for buying the required material and equipment to
promote inclusive education.
 School must employ special needs teachers and should also train other teachers as well about how to
interact with students with special needs.
 School must support the inclusive curriculum and refrain from any other practice that
directly or indirectly puts the disabled students at the disadvantaged side.

MALWARE, short for malicious software, refers to any intrusive software developed by cybercriminals (often
called hackers) to steal data and damage or destroy computers and computer systems. Examples of common
malware include viruses, worms, Trojan viruses, spyware, adware, and ransom ware
A COMPUTER VIRUS is a type of malicious software, or malware, that spreads between computers and
causes damage to data and software. Computer viruses aim to disrupt systems, cause major operational issues,
and result in data loss and leakage.
 Your computer is running slower than normal
 You are getting pop-ups that you didn’t initiate
 Your computer is freezing or crashing
 Your files are disappearing or becoming corrupted
 You’re receiving strange emails that you didn’t notice.
A TROJAN HORSE (Trojan) is a type of malware that disguises itself as legitimate code or software. Once
inside the network, attackers are able to carry out any action that a legitimate user could perform, such as
exporting files, modifying data, deleting files or otherwise altering the contents of the device.

ADWARE (OR ADVERTISING SOFTWARE) is the term used for various pop-up advertisements that show
up on your computer or mobile device. Adware has the potential to become malicious and harm your device by
slowing it down, hijacking your browser and installing viruses and/or spyware. Adware is a type of malware
that blasts your device with excessive ads.

AMIT KUMAR KUSHWAHA Page 92

You might also like