Computer Sc. Notes of Class-Xi
Computer Sc. Notes of Class-Xi
CLASS-XI
Sl.No Contents
1 Data Representation 3-8
9 Tuples 64-74
10 Dictionaries 75-82
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.
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).
Remainde
r Least Significant Bit (LSB)
0
0
1
0
.75 x 2 = 1.50 1
.50 x 2= 1.00 1
(5112)10=(13F8)16
= 2816 + 96 + 14
= (2926) 10
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
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.
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.
X Y X+Y X Y X+Y
– 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.
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
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
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
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
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
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
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
1 1 1 1 1 1 1 1
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
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
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.
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
VariableX=150 (X here
Example assignment operator
is a variable holding valuevalue
150)
Identity
Variable Components
Variable names are case-sensitive (name,Name and NAME are 3 different variables)
Operator
s
Shorthand
Arithmeti Relationa Logica
c l l Assignmen
t
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
Data Type
Data
Types
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
int () - int () is used with input () to convert user given value into int type.
eval () : eval () is used with input () to convert user given value into a number toevaluate the string data entered.
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 : ‘ , “ , # , \ , (), {}, [ ] , @ ,:,.,’
Because here values are objects and p, q, r are their reference name. To understand it
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
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
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.
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.
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.
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 .
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
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)
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 = “))
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
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:”)
>>> 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:
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
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)
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)
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
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
>>> 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
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
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.
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')
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)
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)
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)
>>> 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
>>>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”))
>>> 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
"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
d.items() This function returns the list of >>> d.items() dict_items([(1, 'Amrit'), (2,
elements in the dictionary. 'Bhavesh'), (3, 'Chetan'),(4, 'Falguni')])
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.
OUTPUT:
Enter the elements: [45, 11, 78, 2, 56, 34, 90, 19]
The sorted list is : [2, 11, 19, 34, 45, 56, 78, 90]
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
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
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.
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.
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:
- 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.
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.