Comp 11 CS Combined Notes 2025
Comp 11 CS Combined Notes 2025
COMPUTER SCIENCE
Unit-1
Units of Memory
1. The smallest unit of memory is called a binary digit, or a bit.
2. The bit can assume only two values, 0 and 1.
3. A sequence of 4-bits is called a Nibble.
4. A Word is a fixed length sequence of bits which the processor can handle at a time.
3 Word Group of bits on which the CPU can work as a single unit. Can be
8 bits, 16 bits, 32 bits or 64 bits depending on CPU Architecture.
5 KiloByte(KB) 1 KB = 1024 B
6 MegaByte(MB) 1 MB = 1024 KB
7 GigaByte(GB) 1 GB = 1024 MB
8 TeraByte(TB) 1 TB = 1024 GB
9 PetaByte(PB) 1 PB = 1024 TB
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Language Translators
Languages are majorly divided into two categories: Low Level Languages and High-Level Languages.
● Low Level Languages are nearer to Machine Code than to human-like languages. They are difficult
to understand by humans but easily understandable by machines.
● On the other hand, humans can easily understand high level languages but computers require
language translators to convert high level languages into low level languages which they understand.
● Low level language comprises Binary Language (combination of 0’s and 1’s) and Assembly
Language (uses keywords like ADD, SUB, STR), whereas High Level Language comprises C, C++,
Java, Python etc.
● Software that translates one language to another language is called language translators.
● Language Translators can be divided into Compiler, Interpreter and Assembler.
Operating System
An operating system is system software that acts as an interface between the user and the computer hardware
and manages all the resources of a computer.
COMPUTER SCIENCE
Boolean Logic
Boolean Logic is a concept that involves binary variables and operations. It focuses on the values true and
false (1 and 0). It was developed by the English Mathematician and logician George Boole. Boolean Algebra
comprises of following:
1. Boolean Expression
2. Boolean Variable
Boolean Variable
A boolean variable is a variable that holds boolean values True/ False or 1/0.
Boolean Expression
A boolean expression is an expression that consists of a combination of boolean variables, boolean values
and boolean operators. A boolean expression evaluates to either True or False.
Boolean Operators
Boolean operators perform operations on operands (Boolean Variables/Values). The boolean operators are:
AND, OR and NOT.
AND operator - It evaluates to True(1) if all inputs are True(1), otherwise False(0). It is represented by the
dot operator (.) Example : A.B may be read A AND B
OR operator - It evaluates to True(1) if any of the inputs is True(1), otherwise False(0). It is represented by
the + operator. Example: A + B may be read as A OR B.
NOT operator - It evaluates to True(1) when the condition is False, and returns False(0) when the condition
is True(1).
Truth Table
A truth table is a representation of all possible combinations of the input variables and the corresponding
output values.
The number of rows in a truth table are 2n, where n is no. of input variables.
Example- Here, A and B are the input boolean variables, OR (+) is the operator, F is the output.
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
A B F = A OR B
0 0 0
0 1 1
1 0 1
1 1 1
De Morgan’s Laws
DeMorgan’s First Law states that when two input variables are AND’ed and complemented, they are
equivalent to the OR of the complements of the individual variables.
(AB)'=A'+B'
0 0 1 1 0 1 1
0 1 1 0 0 1 1
1 0 0 1 0 1 1
1 1 0 0 1 0 0
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
DeMorgan’s Second Law states that when two input variables are OR’ed and complemented, they are
equivalent to the AND of the complements of the individual variables.
(A+B)'=A'.B'
0 0 1 1 0 1 1
0 1 1 0 1 0 0
1 0 0 1 1 0 0
1 1 0 0 1 0 0
Logic Gates
A logic gate is a device that performs a Boolean Function. One or more inputs in the form of 1/0 are provided
to get the specific output governed by a logic. Examples of Logic Gates are: AND, OR, NOT, NOR, NAND
and XOR.
NAND and NOR are called Universal Gates, as they can implement any Boolean expression.
AND Gate
Truth Table
A B A.B
0 0 0
0 1 0
1 0 0
1 1 1
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
OR Gate
Truth Table
A B A+B
0 0 0
0 1 1
1 0 1
1 1 1
NOT Gate
Truth Table
A A'
0 1
1 0
NAND Gate
Logic Gate Diagram
Truth Table
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
NOR Gate
A B A+B (A+B)'
0 0 0 1
0 1 0 1
1 0 0 1
1 1 1 0
Truth Table
XOR Gate
Truth Table
A B A⊕B
0 0 0
0 1 1
1 0 1
1 1 0
COMPUTER SCIENCE
Logic Circuits
A logic circuit is an electronic circuit which performs logical operations on the input boolean variables, and
transforms them into the output using a combination of Logic Gates.
Y=(A.B)’BC’
Y Y=?
Number System
There are many possible ways to represent numbers. A number system provides a consistent and unique
method to represent the numbers.
A positional number system is one way of writing numbers. It has unique symbols for 0 through (b – 1),
where b is the base (also known as radix) of the system. These symbols are called digits.
COMPUTER SCIENCE
The binary system is most easily implemented through computer hardware. The binary digits 0 and 1
correspond to the presence or the absence of a digital signal. The manipulation of binary digits is performed
using a combination of boolean logic gates and circuits. Negative numbers can also be represented in the
Binary Number System.
The numbers are represented by creating a sequence of bits, such as 00000, 010100, 011100 etc. Binary
numerals are often subscripted with 2 in order to indicate the base. For example, (110101)2. Numbers that
have no fractional part are called binary integers.
In the figure above, representation of the binary number (101.01)2 is shown. The most significant bit (MSB)
is the bit in a binary number sequence with the largest value. This is usually the bit farthest to the left. The
MSB represents the highest-order place of the binary integer. On the other hand, the Least Significant Bit
(LSB) is the right-most bit of the number.
The maximum possible sequence of binary numbers that can be created using a sequence of n-bits is 2n .
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
1 21 = 2
2 22 = 4
3 23 = 8
4 24 = 16
0 000 0
1 001 1
2 010 2
3 011 3
4 100 4
5 101 5
6 110 6
7 111 7
For example, an octal number (532.67)8 can be represented in the decimal number system as
(532.67)8 = 5 x 82 + 3 x 81 + 2 x 80 + 6 x 8-1 + 7 x 8-2
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Octal numbers find applications where the number of bits in one word is a multiple of 3. They are also used
as shorthand for representing file permissions on UNIX/Linux operating systems and representation of
UTF8 numbers, etc. The advantage of using Octal numbers is that it uses fewer digits than the decimal
number system. It has fewer computations and is less prone to the computational errors.
0 0000 0
1 0001 1
2 0010 2
3 0011 3
4 0100 4
5 0101 5
6 0110 6
7 0111 7
8 1000 8
9 1001 9
10 1010 A
11 1011 B
12 1100 C
13 1101 D
14 1110 E
15 1111 F
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
COMPUTER SCIENCE
=(1001011)2
= (10001110.1010)2
COMPUTER SCIENCE
1. Repeatedly multiply the fractional part by 8 and note the integer and fractional part of the product.
2. Repeatedly multiply the fraction part by 8 and note the integer part from top to the bottom. (Stop if
you get 0)
3. Repeat this procedure till sufficient precision is reached (usually 2 to 3 places after the radix point).
= (150)8
= (1063.7070)8
COMPUTER SCIENCE
3. Repeat this procedure till sufficient precision is reached (usually 2 to 3 places after the radix point).
= (258)16
= (31)16
COMPUTER SCIENCE
COMPUTER SCIENCE
0000 0 1000 8
0001 1 1001 9
For the integer part, make groups of four bits together starting from the left side of the radix point, and for
the fractional part, make groups of four bits towards the right side of the radix point.
Replace each group with the corresponding hexadecimal number, we get the hexadecimal equivalent of the
given binary number.
NOTE: Add any number of 0’s in the left most bit for integer part, and 0’s in right most bit for fractional
part required to complete the grouping of 4 bits.
Ques 1 - Convert binary number 1000110101110 to hexadecimal number.
Converting Binary Number into Decimal Number:
= (1000110101110)2
= 1 x 212 + 0 x 211 + 0 x 210 + 0 x 29 + 1 x 28 + 1 x 27 + 0 x 26 + 1 x 25 + 0 x 24 + 1 x 23 + 1 x 22 + 1 x 21 +
0 x 20
= 4096 + 0 + 0 + 0 + 256 + 128 + 0 + 32 + 0 + 8 + 4 + 2 + 0
= (4526)10
= (11AE)16
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
2 5 E D
= (25ED)16
1 6 4 9 C
Hence the equivalent Hexadecimal Number is (164.9C)16
D 2 . 9 2 A B
COMPUTER SCIENCE
000 0
001 1
010 2
011 3
100 4
101 5
110 6
111 7
For the integer part, make groups of three bits together starting from the left side of the radix point, and for
the fractional part, make groups of three bits towards the right side of the radix point.
NOTE: Add any number of 0’s in the left most bit for integer part, and 0’s in the right most bit for fractional
part required to complete the grouping of 3 bits.
1 3 3 2
= (1332)8
COMPUTER SCIENCE
= (100111001110.001101)2
4 B (11) 2 A (10)
= (45452)8
F E 6
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
= (7746)8
2 1 0 6
= (446)16
Ques 2 - Convert Octal Number 765 into Hexadecimal Number.
7 6 5
=1 1111 0101
= (1F5)16
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Encoding Schemes
Encoding is defined as the process to convert data from one form to another. Computers only understand
binary language. There is a need to convert popularly used languages by humans into machine
understandable format. Textual characters (letters, numbers and symbols) are assigned unique numerical
codes. Some of the popular encoding schemes are ASCII, ISCII and Unicode.
ASCII
● ASCII stands for American Standard Code for Information Interchange.
● It was developed in the United States of America by American Standards Association (ASA).
● It is used to represent textual information in computers.
● ASCII uses 7-bits for encoding.
● A maximum of 128 characters may be encoded. Out of these 128 characters, only 95 are printable
including the digits 0-9, lowercase and uppercase characters a-z A-Z and punctuation marks. The
rest of the characters are Control Characters.
ISCII
● ISCII stands for Indian Script Code for Information Interchange (ISCII).
● ISCII is an extended version of the ASCII code and uses 8 bits for encoding.
● It was developed by the Bureau of Indian Standards, India.
● It represents various languages from India.
● Some of the supported scripts are Devanagari (Hindi, Marathi, Sanskrit, Konkani), Gujarati,
Kannada, Punjabi, Malayalam, Telugu, Tamil, Oriya, Bengali-Assamese etc.
Unicode
● Unicode Standard is developed and managed by the Unicode Consortium, which is a non-profit
organization composed of members from Software Development companies such as Apple, Adobe,
Google, IBM, Microsoft etc.
● It aims to provide a universal platform for encoding characters of various languages from the world.
● It assigns a unique Code Point to every character, independent of the CPU architecture/platform, or
the underlying software.
● Unicode covers most writing scripts across the world. As of now, over 161 scripts are included in
the latest version of Unicode.
● Unicode defines two mapping methods: the Unicode Transformation Format (UTF) encodings, and
the Universal Coded Character Set (UCS) encodings.
● Various versions of UTF are UTF-8, UTF-16, UTF-32.
● All UTF encodings map code points to a unique sequence of bytes.
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
○ UTF-8 uses 8-bits or 16-bits or 24-bits or 32-bits for each code point.
○ UTF-16 uses 16-bits or 32-bits for each code point.
○ UTF-32 uses 32-bits for each code point.
Q.Assertion (A): NAND and NOR are called the Universal Gates.
Reason (R): OR operator results True(1) if both the inputs are True(1), otherwise False(0).
Q.Assertion (A): Each symbol in a hexadecimal number system can be represented by a unique 4-bit binary
number.
Reason (R): The hexadecimal number system has 16 unique symbols.
Answer: Both A and R are true and R is the correct explanation for A.
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Features of Python
● High-level Programming language.
● Interpreted language (as Python programs are executed by an interpreter)
● Easy to use
● Simple Syntax
● Python programs are generally written with fewer Lines of Code as compared to other
programming languages.
● Case-sensitive. For example, 'NUMBER' and 'number' are treated differently in Python.
● Portable programming language - has ability run programs on many computer architectures and
operating systems.
Working in Python
● Install Python on the computer (https://www.python.org/downloads/).
● Use Python IDLE (Integrated Development and Learning Environment) for developing python
Programs.
Interactive Mode
In Interactive Mode, a python statement is executed in a command-line shell. It provides instant feedback
for each statement while keeping prior statements in memory.
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Script Mode
In script mode, the instructions are saved in a file with a '.py' extension and executed from the beginning of
the file. This mode is suitable for creating and running large programs. In script mode, all commands are
stored in the form of a program or a script.
Character Set:
A character set is a collection of valid characters that can be recognized by a language. Python Language
recognises the following characters as valid:
Letters : A-Z, a-z
Digits : 0-9
Special Symbol : + / @ ! - = <> == etc.
Whitespaces : '\n', '\t' ,’ ‘(single space),’ ‘(more than one space)etc.
Tokens (DOLIK)
Tokens are the smallest individual units of a program.
Keywords
Keywords are reserved words with special meaning (known to the interpreter). These can not be used as
identifiers in a program.
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while',
'with', 'yield']
Identifier
A variable, function, class, module, or other objects are identified by a name known as identifier.
Rules for naming an identifier:
1. First character of a variable can be an alphabet(A-Z or a-z) or an underscore(_).
2. Next characters of a variable can be an alphabet(A-Z or a-z), an underscore(_) or a digit.
3. Keywords cannot be used as variables.
4. First character cannot be a digit.
5. Special characters including white spaces are not allowed.
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Literals:
Literals are data-items that have a fixed value of a certain data type, such as a number, string, boolean, or
None. They are also known as Constants.
Example :
String literals (Text) : 'Hello World'
Numeric literals (Numbers) : 3.14
Boolean literals (Truth Value) : True/False
None Literal : The None keyword is used to define a null value
or absence of a value. None is different from 0.
Operators
Arithmetic Operators : Arithmetic operators perform mathematical operations like addition, subtraction,
multiplication, division, floor division, exponent and modulus. (+,-,*,/,//,**,%)
Relational Operators:
Relational operators perform comparison between values. An expression having relational operators
evaluates to either True or False. Example >, <, >=, <=, ==, !=
Python Comments
Comments are descriptions about the code. They help other programmers understand the functionality of
the code. Comments are ignored by the Python interpreter, and are only relevant to the programmer.
Single line comment-#, Multi line comment ‘’’Comment’’’ (enclosed in triple single/double quotes)
Variable
Variables refer to an object (data items like int, float, list, dictionary etc) stored in the memory. Value stored
in a variable can be changed during the program execution.
Rules for naming a variable are the same as the rules for naming an Identifier.
Example: pri = 5
Here pri is a variable with value 5.
COMPUTER SCIENCE
x = 5+2
In the statement above, the l-value is 'x' as it is on the left-hand side of the = operator.
The r-value is 7 as it is on the right-hand side of the = operator, and is generated by performing the addition
operation on 5 and 2.
The memory location of x may be checked by executing the command id(x).
Data type represents the type of data a Variable or a Literal is referring to. Each data type has specific
characteristics and operations associated with it. In Python, there are various data types, including number,
string, boolean, list, tuple, and dictionary.
Mutable Objects:
Mutable data objects are objects that can be changed at the same memory location after they are created. It is
possible to add, remove, or modify elements within these data types. Example of mutable data types: List,
Set and Dictionary.
Immutable Objects :
Objects whose values cannot be changed at the same memory location after they are created are called
immutable objects. To change the value, a new object is created. Example of immutable data types: Number
(Integer, Float), String, and Tuple.
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Integer
● Numbers with No Fractional Part
● Can be Positive or Negative
● In Python 3, the int type has no max limit. Values can be as large as the available memory allows.
● Example 100, 0o55 (octal number), 0x68(hexadecimal number)
Float
● Numbers with Fractional Part
● Example 3.14, .314E01
Complex
● Numbers with both real and imaginary components
● A complex number is represented by "x + yj". Example 10 + 9j
Boolean
A boolean data type can assume one of the two possible values : True or False.
Sequence: Sequence is an ordered collection of items or elements which includes several built-in types
as String, List, and Tuple. Values in the sequence are called elements/items. Each element in a sequence
has a unique index.
String:
● A string is an ordered sequence of characters enclosed in single/double/triple quotes.
● Single Line String : Terminates in a single line. Example – 'This is an example of single line'
● Multi Line String : Does not terminate in a single line. A multiline string may be created using three
quotes
Example -
'''This is a
Multiline
string'''
List:
● List is an ordered sequence data type which can store values of any data type.
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
● List is mutable.
● List is enclosed in square brackets [ ]
● Example : [ ] is an empty List,
[5, 6.5, True, 'Hello'] is a List having 5, 6.5, True and 'Hello' as four
elements.
Tuple:
● Tuple is an ordered sequence which can store values of any data type.
● They are immutable, i.e the items of a Tuple cannot be updated after creation.
● Tuple is enclosed in parenthesis ( )
● Example : t=( ) is an empty Tuple
t=(9,) is a Tuple with 9 as an item, a single item has to be followed by comma
t=(8, 5, 9.5, False) is a Tuple with 8, 5, 9.5, False as four items
Dictionary:
● Dictionary in Python stores items in the form of key-value pairs
● Syntax is dict_variable = {key1:value1, key2:value2, …, key-n:value-n}
● Items in a dictionary are enclosed in curly brackets { } and are separated by commas
● In a key-value pair, the key is separated from the value using a colon (:)
● To access any value in the dictionary, specify the key as the index using square brackets [ ].
● Example : { } is an empty dictionary,
D = {'name':'Python','version':'3.7.2', 'OS': 'Windows'}
print(D['version']) # shows 3.7.2 as output
Special Data-type: None
The None data type/keyword is used to indicate absence of a value (No value or Missing Value).
Types of Operators
1. Arithmetic
Operators
2. Relational
Operators
3. Logical Operators
4. Assignment 2.0
Operators
5. Identity Operators
6. Membership
Operators
Arithmetic
operators: Arithmetic
operators perform
mathematical operations such as addition, subtraction, multiplication, division, and modulus.
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
In case u have 2**3**2 (its associativity is from right to left ) so first 3**2 will be executed which is 9
and then 2**9.
Modulo Operator
The modulo operator (%) evaluates the remainder of the operation when the operand on the left is divided
by the operand on the right of the modulo operator. a - (a // b) * b
Also the sign of the result in the modulo operation depends on the denominator (divisor).
Example
15 % 7 = 1 10.5 % 3 = 1.5
print(10 % 3) # Output: 1 (10 // 3 = 3, remainder = 1)
Relational Operators: Relational operators compare the operands. They evaluate to either True or
False.
Logical operators:
Logical operators combine logical values of true or false into a logical expression. They evaluate to either
True or False. There are three basic types of logical operators: 'NOT', 'AND', and 'OR'. Highest
precedence is of NOT and then And and then OR
Assignment operators:
Variables are assigned values using assignment operators.
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Identity Operators
Identity operators in Python are used to compare the memory locations of two objects. They help determine
whether two variables reference the same object in memory, rather than just having equal values.
Example1:
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True, because their values are the same
print(a is b) # False, because they are different objects in memory
Example2:
x = [10, 20, 30]
y = x # y is assigned the same reference as x
print(x is y) # True, both refer to the same memory location
Example3:
a = 100 c = 1000
b = 100 d = 1000
print(a is b) # True print(c is d) # False (in most cases)
Python caches small integers (typically from -5 to 256), so a and b reference the same memory location.
Larger integers (c and d) may not be cached, so they could be stored separately.
Example4:
x = [1, 2, 3]
y = [1, 2, 3]
z=x
print(x == y) # True (values are the same)
print(x is y) # False (different objects)
print(x is z) # True (same object)
Identity Operators Vs Equality Operator
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Membership Operators
The membership operators in Python are 'IN' and 'NOT IN'. They check whether the operand on the left
side of the operator is a member of a sequence (such as a list, tuple or a string) and dictionary on the right
side of the operator.
Example :
x = ['Red', 2, 'Green']
if 'Red' in x:
print("Found")
else:
print("Not Found")
Output will display Found because the item 'Red' is a member of the List x.
Operator Precedence
Associativity of Python Operators
Associativity refers to the order in which operators of the same precedence are
evaluated. The associativity of an operator may be left-to-right or right-to-left.
Evaluation of Expression
1. Evaluate the expression 50 + 20 * 30
Evaluation:
= 50 + (20 * 30) #precedence of * is more than that of +
= 50 + 600
= 650
COMPUTER SCIENCE
= 45
Type conversion
It is the process of converting the value from one data type into another. Python supports two ways of Type
conversion:
● Implicit conversion
● Explicit conversion
Implicit conversion
This type of conversion is performed by Python Interpreter automatically without the user's intervention.
Example:
num1 = 20 # num1 is integer
num2 = 30.5 # num2 is float
sum1 = num1 + num2 # sum1 will use float to avoid
# loss of fractional part during addition
print(sum1)#50.5
print(type(sum1))#float
Explicit Conversion:
This type of conversion is performed by the user manually. It is also known as type-casting. Explicit type-
casting is performed using functions such as int( ), float( ), str( ) etc.
Syntax : new_data_type (expression)
Example
num1 = input("Enter a number : ") # takes a string input by default
var1 = int(num1) #converts string to integer
var1 = var1 * 3
print(var)
Output
Enter a number : 2
6
Data Output:
print( ) function is used for displaying output on the screen.
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Example-1
num1 = int(input("Enter a Number : ")) # type casting the input from
String to Int
print("The Number is : ", num1)
Example-2
num = int(input("Enter a Number : "))
num_cube = num*num*num
print("The cube is : ",num_cube)
Errors
An error is a problem that occurs in a program. Error sometimes halt the program execution, or produce
unexpected results, and cause the program to behave abnormally.
● Syntax error
● Logical error
● Runtime error
Syntax Error
Syntax are the rules for framing statements in a programming language. Any violations in the rules while
writing a program are known as Syntax Errors. They prevent the code from executing and are detected by
the Python interpreter before the execution of the program begins.
Some of the Common Syntax Errors are
● Parenthesis Mismatch
● Misspelled keyword
● Incorrect Indentation
Logical Error
Logical errors occur when the code runs without any errors, but the output is not as expected. Logical errors
are caused by a problem in the logic of the code.
Example : Average = mark_1 + mark_2 / 2 # incorrect calculation of average marks
Corrected Code : Average = (mark_1 + mark_2 ) / 2
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Runtime Error
A runtime error causes abnormal termination of the program during the execution. Runtime error occurs
when the statement is correct syntactically, but the interpreter cannot execute it.
num1 = 5.0
num2 = int(input("num2 = ")) #if the user inputs zero, a runtime error
will occur
print(num1/num2)
Conditional Statements
Conditional statements execute specific blocks of code based on certain conditions. In Python, conditional
statements are implemented using the keywords if, if-else, and if-elif-else.
Terminology
Indentation
Indentation refers to the spaces at the beginning of a line.
Example
if a<5:
print(a)
print('Inner Block')
print('Outside block')
Block of code
A block of code is a set of statements that are grouped together and executed as a single unit. A block of
code is identified by the indentation of the lines of code.
if statement
The if statement is used to execute a block f code only if a certain condition is true.
Syntax:
if <condition>:
Set of Statements
COMPUTER SCIENCE
Program
Write a python Program to find the absolute value of the number entered by the user.
num = int(input("Enter any number : "))
if num>=0:
abs_num = num
else:
abs_num= -num
print(abs_num)
Output
Enter any number : -5
5
Program
Write a python Program to sort three numbers entered by a user.
a = float(input("Enter the first number : "))
b = float(input("Enter the second number : "))
c = float(input("Enter the third number : "))
if a > b:
a,b = b,a
if a > c:
a,c = c,a
if b > c:
b,c = c,b
print (a, "<", b, "<", c)
Output
Enter the first number : 30
Enter the second number : 25
Enter the third number : 20
20.0 < 25.0 < 30.0
if-else statement
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
The if-else statement is used to execute one block of code if a certain condition is true, and another block
of code if the condition is false.
Syntax of if-else
if <condition>:
set of statements
else:
set of statements
Example
Program
Write a python Program to check if a number entered by a user is divisible by 3.
num=int(input("Enter a number : "))
if num % 3 == 0:
print(num,"is divisible by 3")
else:
print(num,"is not divisible by 3")
Output
Enter a number : 601
601 is not divisible by 3
if-elif-else statement
if-elif-else statement is used to check multiple conditions.
Program
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Iterative Statement
Iterative statements execute a set of instructions multiple times. 'for' and 'while' loops are the iterative
statements in Python.
while Loop
The while loop repeatedly executes a block of code as long as the specified condition is true.
The while loop is an exit controlled loop, i.e. the user is responsible for exiting the loop by changing the
value of the condition to False. While loop may run infinitely if the condition remains true.
Syntax:
while (condition):
block of statements
Example
Write a Python Program (using a while loop) to Find the Sum of First 10 Natural Numbers.
num=1
sum=0
while (num <= 10):
sum = sum + num
num = num+1
print ("Sum of Natural Numbers : ", sum)
range( ) Function
range( ) is a built-in function that returns a sequence of numbers.
Syntax
range(start, stop, step)
start: The starting value of the sequence (inclusive). If not specified, it defaults to 0.
stop: The ending value of the sequence (exclusive).
step: The difference between two consecutive elements. Its default value is 1.
If step is +ve start <stop,
If step is –ve then start>stop , otherwise the range wont produce anything
The range( ) function can be used in for loops to iterate over a sequence of numbers.
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
for Loop
The for loop is used to iterate over a sequence (such as a list, tuple, string, etc.) and execute a block of code
for each item in the sequence.
Syntax
for <control_variable> in <sequence>:
Block of code
Example-1 Example-2
list1 = [1,2,3,4,5,6,7,8,9,10] str1 = 'India'
for var1 in list1: for each_character in str1:
print(var1) print(each_character)
Program-1
Write a Python Program (using for loop) to Find the Sum of First 10 Natural Numbers.
sum=0
for num in range(1,11):
sum = sum + num
print ("Sum of Natural Numbers : ", sum)
Output:
Sum of Natural Numbers : 55
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Program-2
Write a Python Program (using for loop) to Find the Sum of First N Natural Numbers where N is entered by the
user.
sum=0
n = int(input("Enter the value of n : "))
for num in range(1, n+1):
sum = sum + num
print ("Sum of Natural Numbers : ", sum)
Output:
Enter the value of n : 20
Sum of Natural Numbers : 210
Program-3
Write a Python Program (using for loop) to find the factorial of a number.
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
else:
for i in range(1, num + 1):
factorial *= i
print("The factorial of", num, "is", factorial)
Output
Enter a number: 5
The factorial of 5 is 120
COMPUTER SCIENCE
Example :
fruits = ['apple', 'banana', 'cherry']
for x in fruits:
if x == 'banana':
break
print(x)
Example :
Write a program in Python to check if a number entered by a user is a prime number or not.
num = int(input("Enter a number: "))
flag=False
if num > 1:
for i in range(2, num):
if (num % i) == 0:
flag=True
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
Example :
Write a program in Python to print all natural numbers between 1 and 50 (both inclusive) which are not
multiple of 3.
for x in range(1, 51):
if x % 3 ==0 :
continue
print(x)
Write a program in Python to print all natural numbers from 1 to 10 except 7.
for i in range(1,11):
if i==7:
continue
print(i)
The pass statement in Python is a null operation that acts as a placeholder. It allows you to write syntactically
correct code without executing anything. It is commonly used in functions, loops, or conditional statements where
code will be added later.
for i in range(5):
pass # Placeholder for future logic
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Nested loops
Output
Enter the number of rows: 5
*
**
***
****
*****
Example
for i in range(1, 4):
print("Table for ",i)
for j in range(1, 6):
print(i,'*',j,'=',i * j)
The outer loop (i) runs from 1 to 3, representing different multiplication tables.
For each i, the inner loop (j) runs from 1 to 5, multiplying i by j and printing the result.
Module
Module: It is any .py file containing python definitions and statements. Modules are a simple way to structure a
program. Module is anything that has python statements in it or functions or classes etc. To use a module, we
need to import the module. Once we import a module, we can directly use all the functions of that module. A
module is loaded only once, regardless of the number of times it is imported.
import Statement:
You can use any Python source file as a module by executing an import statement in some other Python source
file. When the interpreter encounters an import statement, it imports the module in the program. A module is
loaded only once, regardless of the number of times it is imported. This prevents the module execution from
happening over and over again if multiple imports occur.
import statement can be written anywhere in the code not necessarily at the top. It should be written just
above the line where the function is invoked.
3 ways of importing a module:
1. import math 2. from math import sqrt 3. from math import *
math.sqrt(49) sqrt(49) sqrt(49)
can only use sqrt function cos(45)
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
import math
This imports the entire math module but requires you to use the module name as a prefix to access its functions and constants.
from math import *
This imports all functions and constants from the math module directly into your namespace, allowing you to use them without the
module prefix.
from math import sqrt, ceil
imports only the specified functions (sqrt and ceil) from the math module directly into your namespace.
Python has a very extensive standard library. It is a collection of many built in functions that can be called in the program as and when
from math import *
required, thus saving programmers time of creating those commonly used functions every time.
• math
• random
This imports all functions and constants from the math mo
• statistics
Ifnamespace, allowing
you use both import math and from mathyou to* inuse
import them
the same without
Python script, the
they will both be module
considered, but they behave differently.
import math
from math import *
from math import sqrt, ceil
print(math.sqrt(16)) # Works (math module is imported)
print(sqrt(16)) # Works (because of from math import *)
imports
Module aliasing:only the specified functions (sqrt and ceil) from th
You can create an alias (nickname) of a module using ‘as’ keyword.
into your namespace.
import <module_name> as <alias_name>
For example:
import random as r
r.random()
Output: 32.6
2. Median
Function: statistics.median(x)
Description: Returns the median (middle value) of a numeric sequence.
Output: 32
3. Mode
Function: statistics.mode(x)
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
import statistics
print(statistics.mode([11, 24, 11, 45, 11]))
Output: 11
Output: 'red'
print(math.ceil(-9.7)) # Output: -9
print(math.ceil(9.7)) # Output: 10
2. Floor Function (math.floor(x))
Description: Returns the largest integer less than or equal to x.
print(math.floor(-4.5)) # Output: -5
print(math.floor(4.5)) # Output: 4
3. Absolute Value (math.fabs(x))
Description: Returns the absolute (positive) value of x.
COMPUTER SCIENCE
print(random.random())
print(random.randrange(5)) # Output: 4
4. Generate a Random Number in a Given Range (random.randrange(x,
y))
COMPUTER SCIENCE
String
String: String is a sequence of UNICODE characters. A string can be created by enclosing one or more
characters in single, double or triple quotes (' ' or '' '' or ''' ''').
Example
>>> str1 = 'Python'
>>> str2 = "Python"
>>> str3 = '''Multi Line
String'''
>>> str4 = """Multi Line
String"""
Whitespace Characters: Those characters in a string that represent horizontal or vertical space.
Example: space (' '), tab ('\t'), and newline ('\n')
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Indexing in Strings
● Indexing is used to access individual characters in a string using a numeric value.
● The index of the first character (from left) in the string is 0 and the last character is n-1
● The index can also be an expression including variables and operators but the expression must
evaluate to an integer
● Forward indexing, also known as positive indexing, starts from left to right, with the first character
having index 0, second character having index 1, and so on.
● Backward indexing, also known as negative indexing, starts from right to left, with the last character
having index -1, second-last character having index -2, and so on
Example
>>> str1 = 'Python' >>> str1 = 'Python'
>>> str1[0] >>> str1[2+3]
'P' 'n'
Slicing
Slicing is the process of extracting a substring from a given string. It is done using the operator ':'.
Syntax : string[start:end:step].
start : 'start' is the starting index of the substring (inclusive).
end : 'end' is the ending index of the substring (exclusive)
step : 'step' is the difference between the index of two consecutive elements. Default value is 1
Case-1 Case-2 Case-3 Case-4
print(str1[:3]) print(str1[1:4]) print(str1[0:5:2]) print(str1[-5:-1])
COMPUTER SCIENCE
String is Immutable
A string is an immutable data type. It means that the value (content) of a string object cannot be changed
after it has been created. An attempt to do this would lead to an error.
Example
>>> str1 = 'Python'
>>> str1[1]='Y'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
Traversal of a String
Accessing the individual characters of string i.e. from first
1. Using only for Loop
str1 = 'Computer'
for ch in str1:
print(ch, end=' ')
COMPUTER SCIENCE
String Operations
We can perform various operations on string such as concatenation, repetition, membership and slicing.
Concatenation
Operator : +
>>> str1 = "Python"
>>> str2 = "Programming"
>>> str1 + str2
'PythonProgramming'
Repetition
Use : To repeat the given string multiple times.
Repetition operator : *
>>> str1 = "Hello "
>>> str1*2*3 # str1*5.0 will give error as it can’t be float
'Hello Hello Hello Hello Hello Hello'
Membership
Membership is the process of checking whether a particular character or substring is present in a sequence
or not. It is done using the 'in' and 'not in' operators.
Example
>>> str1 = "Programming in Python"
>>> "Prog" in >>> "ming in" >>> "Pyth " >>> "Pyth " not in str1
str1 in str1 in str1 True
True True False
String Methods/Functions
Python has several built-in functions that allow us to work with strings
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
len() capitalize()
Returns the length of the given string Returns the string by converting the first character
>>> str1 = 'Hello World!' of a string to capital (uppercase) letter and rest in
>>> len(str1) lowercase.
12 str1 = "python Programming for
11th"
str1.capitalize()
'Python programming for 11th'
title() lower()
Returns the string by converting the first letter of Returns the string with all uppercase letters
every word in the string in uppercase and rest in converted to lowercase
lowercase >>> str1 = "PYTHON PROGRAMMING for
>>> str1 = "python ProGramming 11th"
for 11th" >>> str1.lower()
>>> str1.title() 'python programming for 11th'
'Python Programming For 11Th'
upper() count()
Returns the string with all lowercase letters Returns number of times a substring occurs in the
converted to uppercase given string. If it does not occur then returns 0
>>> str1 = "python programming >>> str1 = "python programming for
for 11th" 11th"
>>> str1.upper() >>> str1.count("p")
'PYTHON PROGRAMMING FOR 11TH' 2
>>> str1.count("pyth")
1
find(substr,beg,end) index(substr,beg,end)
Returns the index of the first occurrence of Same as find() but raises an exception if the
substring in the given string. The beg is(0) and substring is not present in the given string. The beg
end is len(s) by default and end not included. If is(0) and end is len(s) by default and end not
the substring is not found, it returns -1 included.
>>> str1 = "python programming >>> str1 = "python programming for
for 11th" 11th"
>>> >>> str1.index('r')
str1.find('r')#8 8
>>> str1.find('u')#-1 >>> str1.index('u')
>>> s="pujau" ValueError: substring not found
>>> s.find('u',2)#4 >>> s="pujau"
>>> s.index('u',2)#4
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
isalnum() isalpha()
The isalnum() method returns True if all Returns True if all characters in the string are
characters in the string are alphanumeric (either alphabets, Otherwise, It returns False
alphabets or numbers). If not, it returns False. >>> 'Python'.isalpha()
>>> str1 = 'HelloWorld2' True
>>> str1.isalnum() >>> 'Python 123'.isalpha()
True False
>>> str1 = 'Hello World2'
>>> str1.isalnum()
False
isdigit() isspace()
returns True if all characters in the string are Returns True if has characters and all of them are
digits, Otherwise, It returns False white spaces (blank, tab, newline)
>>> '1234'.isdigit() >>> str1 = ' \n \t'
True >>> str1.isspace()
>>> '123 567'.isdigit() True
False >>> str1 = 'Hello \n'
>>> str1.isspace()
False
islower() isupper()
returns True if the string has letters all of them returns True if the string has letters all of them are
are in lower case and otherwise False. in upper case and otherwise False.
>>> str1 = 'hello world!' >>> str1 = 'HELLO WORLD!'
>>> str1.islower() >>> str1.isupper()
True True
>>> str1 = 'hello 1234' >>> str1 = 'HELLO 1234'
>>> str1.islower() >>> str1.isupper()
True True
>>> str1 = 'hello ??' >>> str1 = 'HELLO ??'
>>> str1.islower() >>> str1.isupper()
True True
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
strip() lstrip()
It returns a string after removing leading and trailing Returns the string after removing Leading
characters from a string. By default, it removes characters only from the left (beginning). By default
whitespace, but you can specify other characters as removes white space characters.
well. >>> str1 = ' Hello World! '
>>> str1 = ' Hello World! ' >>> str1.lstrip()
>>> str1.strip() 'Hello World! '
'Hello World!'
>>>text = "###Hello, World!!!###"
>>>result = text.strip("#!")
'Hello, World'
rstrip() replace(oldstr,newstr,no_of_times)
Returns the string after removing trailing It returns a string after replacing a particular
characters only from the right (ending). By default substring in a string with another substring. By
removes white space characters.
deault no_of_times is max
>>> str1 = ' Hello World! '
>>> str1 = 'Hello World!'
>>> str1.rstrip()
>>> str1.replace('o','*')
' Hello World!'
'Hell* W*rld!'
>>>str1.replace('o','*',1)
'Hell* World!'
istitle() split()
It returns True if the string is in titled case i.e first Returns a list of words delimited by the specified
letter of every word is capital and rest in substring. If no delimiter is given then words are
lowercase letter.
separated by whitespaces.
>>> s="Puja Gupta"
>>> s.istitle() string.split(separator, maxsplit)
True separator (optional): The delimiter on which the
split occurs (default: whitespace).
partition() maxsplit (optional): Maximum number of times
The partition() function is used to split a string the string will be split
into three parts based on a specified separator. It >>> str1 = 'India is a Great Country'
always return a tuple and will have 3 portions >>> str1.split()
>>> str1 = 'India is a Great Country' ['India','is','a','Great', 'Country']
>>> str1.partition('is') >>> str1 = 'an Indian -Great Country'
('India ', 'is', ' a Great Country') >>> str1.split('a')
If the separator is not found then returns the ['', 'n Indi', 'n -Gre', 't Country']
whole string with 2 empty strings
>>> str1.partition('are') text = "apple banana cherry date"
result = text.split(" ", 2) # Max 2
('India is a Great Country',' ',' ') ['apple', 'banana', 'cherry date']
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
startswith(substring,beg,end) join()
startswith() function is used to check whether a str.join(sequence)
returns a string in which the string elements of
given string starts with a particular substring. The
beg is(0) and end is len(s) by default and end not sequence have been joined by str separator. if few
included. of the members of the sequence are not string, error
is generated.
endswith(substring,beg,end) >>> '*-*'.join('Python')
endswith() function is used to check whether a 'P*-*y*-*t*-*h*-*o*-*n'
given string ends with a particular substring. The >>> '*-
beg is(0) and end is len(s) by default and end not *'.join(['Ajay','Abhay','Alok'])
included. 'Ajay*-*Abhay*-*Alok'
>>> '*-
str = "Python Programming" *'.join(['Ajay','Abhay',123])
print(str.startswith("Pyt")) Traceback (most recent call last):
print(str.startswith("Pro",7)) File "<stdin>", line 1, in
print(str.endswith("age")) <module>
print(str.endswith("uage")) TypeError: sequence item 2:
print(str.startswith("Pyts")) expected str instance, int found
Output
True
True
True
True
False
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
LIST IN PYTHON
● List is a sequence i.e. sequenced data type.
● List can store multiple values in a single object.
● List is an ordered sequence of values/elements.
● Elements of a list are enclosed in square brackets [ ], separated by commas.
● List are mutable i.e. values in the list can be modified.
● The elements in a list can be of any type such as integer, float, string, objects etc.
● List is heterogeneous type i.e. collection of different types.
L = [5, 8, 6, 1, 9]
What is a sequence?
Sequence is a positional ordered collection of items, which can be accessed using index. Examples of
sequence are List, Tuple, String etc.
List is Mutable
In Python, lists are mutable. It means that the contents of the list can be changed after it has been created.
>>> L = [1, 5, 7, 2]
>>> L
[1, 5, 7, 2]
>>> L[1]=8
>>> L
[1, 8, 7, 2]
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
For example:
>>> L = [5, 8, 6, 1, 9]
>>> L[0]
>>> L[3]
>>> L[-1]
>>> L[-4]
>>> L[5]
COMPUTER SCIENCE
If we try to access the element from outside the index range then the interpreter raises an IndexError.
LIST OPERATIONS
Slicing in List:
Note: Slicing never gives IndexError even if it is invalid range
Object_name[start : stop : step] # start is included and stop is excluded.
● Default value of start is 0, stop is len(l) (if step is +ive)
● Default value of start is -1 and –(len(l)+1) if step is –ive
● Default value of step is 1
● If step is +ve then slicing is performed from left to right,if the step is -ve then slicing is performed from right
to left. For Ex:
>>> L[1:4:1]
[8, 6, 1]
>>> L[1:5:2]
[8, 1]
>>> L[:5:2]
[5, 6, 9]
Start, stop and interval is not given then they consider as default value
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
>>> L[: :]
[5, 8, 6, 1, 9]
If start>=stop and interval is positive the slicing will return empty list
>>> L[4:2]
[]
If the interval is negative then slicing is performed from right to left. For Ex:
Access the list element where start index is 4 and stop index is 1 in reverse order
>>>L[4:1:-1]
[9, 1, 6]
Access the list element where start index is 5 and stop index is 0 with interval 2 in reverse order
>>>L[5:0:-2]
[9, 6]
>>>L[-1:-4:-1]
[9, 1, 6]
>>>L[-1:-4:-1]
[9, 1, 6]
COMPUTER SCIENCE
>>> L[-1:2:-1]
[9, 1]
Repetition Operator
● The repetition operator makes multiple copies of a list and joins them all together. The general format
is: list * n,
where ‘list’ is a list and n is the number of copies to make.
>>> L=[0]*3
>>> L
[0, 0, 0]
In this example, [0] is a list with one element 0, The repetition operator makes 3 copies of this list and joins
them all together into a single list.
Membership operator
Membership operator is used to check or validate the membership of an element in the list or sequence.
There are two types of membership operators
1. in operator: It return True if a element with the specified value is present in the List
2. not in operator: It return True if a element with the specified value is not present in the List
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Examples:
L = [5,"India", 8, 6, 1]
>>> 5 in L
True
>>> "India" in L
True
>>> 9 in L
False
>>> 9 not in L
True
Output:
5
8
9
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
6
1
2: list()
list() is a function used to convert an iterable object into a list. For Ex:
>>> S="Python"
>>> L=list(S)
>>> L
['P', 'y', 't', 'h', 'o', 'n']
In the above example, a string S is converted into the List.
3: append()
appends an element at the end of the list. The length of the list increases by 1.
list.append(item)
append() adds a single element to the end of a list.
The length of the list increases by one.
The method doesn’t return any value
>>> L = [4,5,9,2,6]
>>> L.append(1)
>>> L
[4, 5, 9, 2, 6, 1]
A list is an object. If we append another list onto a list, the parameter list will be a single object at the end
of the list.
>>> L1=[1,2,3]
>>> L2=[4,5,6]
>>> L1.append(L2)
>>> L1
[1, 2, 3, [4, 5, 6]]
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
4: extend()
extend() is a method of list, which is used to merge two lists. It is to add more than one element in a list.
extend() iterates over its argument and adds each element at the end of the list. The length of the list increases
by a number of elements in its argument.
list.extend(iterable)
Argument of extend() method is any iterable (list, string, set, tuple etc.)
The length of the list increases by a number of elements in its argument.
The method doesn’t return any value
>>> L1=[1,2,3]
>>> L2=[4,5,6]
>>> L1.extend(L2)
>>> L1
[1, 2, 3, 4, 5, 6]
A string is iterable, so if you extend a list with a string, you’ll append each character as you iterate over
the string.
>>> L1=[1,2,3]
>>> S="Python"
>>> L1.extend(S)
>>> L1
[1, 2, 3, 'P', 'y', 't', 'h', 'o', 'n']
5: insert()
append() and extend() method is used to add an element and elements of an iterable object respectively at
the end of the list. If we want to add an element at any index then we can use insert() method of list. If the
the index >=len(l) then it will be added at last and if the –ve index< -len(s)then it will be added at
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
beginning.
Syntax: list_name.insert(index, element)
>>> L=[1,2,3]#Insert element 8 at index 1 i.e. at 2nd position
>>> L.insert(1,8)
[1, 8, 2, 3]
>>> L.insert(99,5)
[1, 2, 3,5]
>>> L. insert(-7,5)
[5,1, 2, 3]
6: count()
count() method returns how many times a given element occurs in a List i.e. it returns the frequency of an
element in the list. If the element does not occur then it returns 0.
Syntax: list_name.count(element)
>>> L = [1, 2, 8, 9, 2, 6, 2]
>>> L
[1, 2, 8, 9, 2, 6, 2]
>>> L.count(2)
3
7: index()
index() is a method of the list, which returns the index of the first occurrence of the element.
Syntax: list_name.index(element, start, end)
element – The element whose index for first occurrence is to be returned.
start (Optional) – The index from where the search begins. Start is included.
end (Optional) – The index from where the search ends. End is excluded.
>>> L = [5, 8, 9, 6, 1, 8]
>>> L.index(8) # looks for 8 from index no 0 till end
1
>>> L.index(8,2) # looks for 8 from index no 2 till end
5
>>> L.index(8,2,6) # looks for 8 from index no 2 till index no 5 as last index not included
5
>>> L.index(8,2,5)
ValueError: 8 is not in list
>>> L.index(8,2,7)
5
8: remove()
remove() method of list is used to delete the first occurrence of the given element. If the given element is
not exist in the list then it will give the ValueError
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Syntax: list_name.remove(element)
>>> L
[5, 8, 9, 6, 1, 8]
>>> L.remove(8)
>>> L
[5, 9, 6, 1, 8]
>>> L.remove(4)
ValueError: list.remove(x): x not in list
9: pop()
Syntax: list_name.pop(index)
Index is optional. If index is not given, pop() method of list is used to remove and return the last element
of the list, otherwise remove and return the element of the given index. If Index is out of range then it
gives IndexError.
>>> L = [5, 8, 9, 6, 1]
>>> L
[5, 8, 9, 6, 1]
#remove the last element from the list
>>> L.pop()
1
>>> L
[5, 8, 9, 6]
#remove the element from the list whose index is 1
>>> L.pop(1)
8
>>> L
[5, 9, 6]
>>> L.pop(4)
IndexError: pop index out of range
10: reverse()
reverse() method of the list used to reverse the order of the elements of the list. It does not return anything rather
makes the changes in the list itself.
Syntax: list_name.reverse()
>>> L = [5, 8, 9, 6, 1]
[5, 8, 9, 6, 1]
>>> L.reverse()
[1, 6, 9, 8, 5]
11: sort()
sort() method can be used to sort List in ascending(default), descending, or user-defined order. It sort the
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
existing list. IT does not return any list rather makes changes in the list.
Syntax: List_name.sort(reverse=True/False)
>>> L = [5, 8, 9, 6, 1]
>>> L
[5, 8, 9, 6, 1]
#sort the elements of the list in ascending order
>>> L.sort()
>>> L
[1, 5, 6, 8, 9]
#sort the elements of the list in descending order
>>> L.sort(reverse=True)
>>> L
[9, 8, 6, 5, 1]
12: sorted()
sorted() is a built-in function of list. sorted() function returns a sorted list in ascending order by default. It
does not sort or change the existing list.
>>> L = [5, 8, 9, 6, 1]
>>> L
[5, 8, 9, 6, 1]
>>> sorted(L)
[1, 5, 6, 8, 9]
>>> L
[5, 8, 9, 6, 1]
#Create a list which contains the element of another list in descending order.
>>> L1=sorted(L, reverse=True)
>>> L1
[9, 8, 6, 5, 1]
13: min()
min() function of the list is used to find the minimum element from the list.
>>> L = [5, 8, 1, 6, 9]
>>> min(L)
1
# If the elements of the list are string then min() returns the minimum element based on the ASCII values.
>>> L=['a','D','c']
>>> min(L)
'D'
14: max()
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
max() function of the list is used to find the maximum element from the list.
>>> L = [5, 8, 1, 6, 9]
>>> max(L)
9
# If the elements of the list are string then max() returns the maximum element based on the ASCII
values.
>>> L=['ananya','De','axe',’Df’]
>>> max(L)
'axe'
15: sum()
sum() is a function of list, which returns the sum of all elements of the list.
>>> L = [5, 8, 9, 6, 1]
>>> sum(L,0)#second argument is by default 0 which will be added to the list elements
29
16. clear()
It removes all the elements from the list and make it an empty list.
L=[1,2,3]
l.clear() # []
COMPUTER SCIENCE
Updating a List-
Since it is of mutable data type , you can make changes to the list.
>>> l=[1,2,3,4,5]
>>> l[0]=11 # single element update
>>> l
[11, 2, 3, 4, 5]
>>> l[1:3]=5 # if u are giving a slicing of list to be update the right hand side should be a list
ERROR - TypeError: can only assign an iterable
>>> l[1:3]=[9,10,11,13]
>>> l
[11, 9, 10, 11, 13, 4, 5]
>>> l[0:0]=[6] # it is like inserting an element 6 at the index 0
>>> l
[6, 11, 9, 10, 11, 13, 4, 5]
Copying a list:
If you make a copy of the list with copy() method or slicing or using built-in function list() then their ids will be different
whereas making copy by writing a=b ( will have same ids for a and b list)
Id of both list A and B are Id of both list A and B are Id of both list A and B are Id of both list A and B are
different. So change in A different. So change in A different. So change in A same. So change in A will
will not affect B and vice will not affect B and vice will not affect B and vice affect B and vice versa.
versa. versa. versa.
>>> A=[1,2,3,4] >>> A=[1,2,3,4] >>> A=[1,2,3,4] >>> A=[1,2,3,4]
>>> B=A.copy() >>> B=A[:] >>> B=list(A) >>> B=A
>>> A+=[9,6,7] >>> A+=[5,6,7] >>> A+=[5,6,7] >>> A+=[5,6,7]
>>> A >>> A >>> A >>> A
[1, 2, 3, 4, 9, 6, 7] [1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 4, 5, 6, 7]
>>> B >>> B >>> B >>> B
[1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4, 5, 6, 7]
Comparing a List:
We can apply all the relational operators to compare two lists if they are of comparable types, otherwise Python
gives an error. While comparing two lists, it checks element-by-element comparison. If the corresponding
elements are equal, it goes on to the next element and so on until it finds the element that differs.
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Note: For comparison operation, Python ignores the type of the elements and compares values only.
l=[2.0,3.0]
a=[2,3]
l==a #True
b=[2.1,3.0]
a==b #False
List Comprehension
This is a way to create a new list using an existing list.
Syntax:
NewList = [ expression for variable in iterable object if condition == True ]
Example1:
list1=[x**2 for x in range(10)]
print(list1)
output:
[ 0,1,4,9,16,25,36,49,64,81]
Example 2:
x=[z**2 for z in range(10) if z>4]
print(x)
Output: [25, 36, 49, 64, 81]
Example 3:
x=[x ** 2 for x in range (1, 11) if x % 2 == 1]
print(x)
Output: [1, 9, 25, 49, 81]
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
TUPLE IN PYTHON:
#Create a tuple with a single element. Comma must be used after the element, parenthesis are optional.
>>> T= (5,)
>>> T
(5,)
>>> type(T)
<class 'tuple'>
COMPUTER SCIENCE
>>> T
'Hello'
>>> type(T)
<class 'str'>
>>> T= (5, 9.8,'Hello', 9)
>>> T
(5, 9.8, 'Hello', 9)
Tuple Indexing
>>> T= (5, 8, 6, 1, 9)
>>> T
(5, 8, 6, 1, 9)
>>> T[2]
6
>>> T[-3]
6
>>> T[6]
IndexError: tuple index out of range
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Tuple Operations
Concatenation
Using + operator
>>> T1=(1,2,3)
>>> T2=(4,5,6)
>>> T=T1+T2
>>> T
(1, 2, 3, 4, 5, 6)
Repetition
Tuple can be created using the repetition operator, *.
The repetition operator makes multiple copies of a tuple and joins them all together. The general format
is: T * n,
Where T is a tuple and n is the number of copies to make.
>>> T= (1, 2)*3
>>> T
(1, 2, 1, 2, 1, 2)
In this example, (1, 2) is a tuple with two elements 1 and 2, The repetition operator makes 3 copies of this
tuple and joins them all together into a single tuple.
Membership
Membership operator is used to check or validate the membership of an element in the tuple or sequence.
There are two types of membership operators
1. in operator: It return True if a element with the specified value is present in the tuple
2. not in operator: It returns True if an element with the specified value is not present in the tuple.
Examples:
T = (5,"India", 8, 6, 1)
>>> 5 in T
True
>>> "India" in T
True
>>> 9 in T
False
>>> 9 not in T
True
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Slicing in Tuple:
Note: Slicing never give IndexError
Syntax:
Object_name[start : stop : interval]
● Here start, stop and interval all have default values.
● Default value of start is 0, stop is n (if interval is +ive) and -1 if interval is –ive
● Default value interval is 1
● In slicing start is included and stop is excluded.
● If interval is +ive then slicing is performed from left to right. For Ex:
>>> T[1:4:1]
(8, 6, 1)
If start>=stop and interval is positive the slicing will return empty list
>>> T[4:2]
()
Access the list element where start index is 5 and stop index is 0 with interval 2 in reverse order
>>>T[5:0:-2]
(9, 6)
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
>>>T[-1:-4:-1]
(9, 1, 6)
>>>T[-1:-4:-1]
(9, 1, 6)
Built-in functions/methods of tuple:
1: len():
len() is a function of tuple.
It returns the total number of elements in the tuple i.e. length of the tuple.
For ex:
>>> T = (8, 6, 'Hello', 9, 1)
>>> len(T)
5
It returns the total numbers of elements in the tuple i.e. 5
2: tuple()
tuple() is a function used to convert an object into tuple.
For Ex:
>>> S="Python"
>>> T=tuple(S)
>>> T
('P', 'y', 't', 'h', 'o', 'n')
In the above example, a string S is converted into the tuple.
3: count()
count() is a function used to count() the number of occurrences of an element in the tuple.
>>> T = (1, 2, 3, 2, 4, 2, 5)
>>> T.count(2)
3
4: index(element,start=0,beg=len(t))
It returns the index of the first occurrence of the element
>>> T = (1, 2, 3, 2, 4, 2, 5)
>>> T.index(2)
1
5: sorted()
It is a built-in function to sort the elements of Tuple.
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
It return a new list of sorted elements of the tuple in ascending order (by default)
It does not change the existing tuple.
T = (1, 2, 3, 2, 4, 2, 5)
print(sorted(T))
Output:
[1, 2, 2, 2, 3, 4, 5]
6: min()
It is a built-in function of the tuple. It returns the smallest element from the tuple.
T = (5, 8, 3, 9, 6, 4)
print(min(T))
Output:
3
7: max()
It is a built-in function of the tuple. It returns the largest element from the tuple.
T = (5, 8, 3, 9, 6, 4)
print(max(T))
Output:
9
8: sum()
It is a built-in function of the tuple. It returns the sum of all elements of the tuple.
T = (5, 8, 3, 9, 6, 4)
print(sum(T))
Output:
35
Nested Tuple
A nested tuple is a tuple that has been placed inside of another tuple.
>>> T = (5, (8, 6, 4), 3, 9)
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
>>> T
(5, (8, 6, 4), 3, 9)
>>> T[1]
(8, 6, 4)
>>> T[1][1]
6
A list can be an element of a tuple. It you make changes to that list it will allow as list is mutable data type
>>> T = (5, [8, 6, 4], 3, 9)
>>> T#(5, [8, 6, 4], 3, 9)
>>> T[1][2]= 77
>>> T#(5, [8, 6, 77], 3, 9)
>>> T[1].append([88,99])
>>> T#(5, [8, 6, 77, [88, 99]], 3, 9)
List is a mutable type. So we can change the value of the list, even if it is nested inside the tuple.
Tuple Unpacking
Access tuple’s individual elements using unpacking Another concept that you may have often heard using
tuples is tuple unpacking, which can allow access to individual elements. Some examples are given below.
Note: The number of items in the tuple should be equal to the number of the variables in the unpacked tuple.
COMPUTER SCIENCE
DICTIONARY IN PYTHON
Introduction to Dictionary:
Dictionary is a mapping data type.
Dictionary is a mutable data type i.e. it can be changed after being created.
Dictionary is denoted by curly braces i.e. {}
Dictionaries are used to store data values in key : value pairs
Keys of the dictionary are unique and of immutable data type.
We can access the values of any key from the dictionary using following syntax:
Dict_Name[key_name]
>>> D[1]
10
>>> D[2]
20
>>> D[3]
30
If the key is duplicated at the time of dictionary creation then the value assigned at the last will be stored in
the key.
>>> D = {1:10, 2:20, 3:30, 1:40, 4:50}
>>> D
{1: 40, 2: 20, 3: 30, 4: 50}
>>> D = {'A':10,'B':20,'C':30}
>>> D.get('A')
10
Mutability of a dictionary:
Mutability means the values of a key can be updated in the dictionary.
Dict_Name[Key_Name] = New_Value
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
>>> D = {'A':10,'B':20,'C':30}
Change the value of key ‘A’ from 10 to 15.
>>> D['A']=15
>>> D
{'A': 15, 'B': 20, 'C': 30}
Traversing a dictionary
You can loop through a dictionary by using for loop.
When looping through a dictionary, the return values are the keys of the dictionary, but there are
methods to return the values as well.
We can use following methods to traversing a dictionary:
keys()
It returns the keys of the dictionary, as a list.
values()
It returns the values of the dictionary, as a list.
COMPUTER SCIENCE
Output:
10
20
30
items()
It returns the key-value pairs of the dictionary, as tuples in a list. It returns List of tuples.
Output:
(1, 10)
(2, 20)
(3, 30)
2. dict()
The dict() function is used to create a dictionary.
>>> D = dict(name = "Shiva", age = 26, country = "India")
>>> D
{'name': 'Shiva', 'age': 26, 'country': 'India'}
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
3. get(k[,d])
Returns the value of the key. If the key does not exist, returns d (defaults to None).
4. update()
The update() method inserts specified elements to the dictionary or merge two dictionaries. If key is already
exist in the dictionary then the value of the existing key will be update:
dictionary.update(iterable)
5. del
del is a keyword.
del is used to delete an element from the dictionary using keyname.
COMPUTER SCIENCE
>>> del D
>>> D
NameError: name 'D' is not defined.
6. clear()
The clear( ) method is used to delete all the elements (key:value pairs) from a dictionary.
It does not delete the structure of the dictionary
7. pop(key[,d])
Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key
is not found, it raises KeyError.
8. popitem()
popitem() method is used to delete the last element from the dictionary. It return the (key, value) pair of
deleted elements in tuple type. If the dictionary is empty then will raise KeyError
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
COMPUTER SCIENCE
9. setdefault(key[,d])
setdefault() method returns the value of the specified key. If the key does not exist in the dictionary it insert
the key into dictionary, with the specified value. If no value is given then add None.
Return the value of key ‘3’. If key is already exists in the dictionary, 2nd argument does not effects
>>> D.setdefault(3,50)
30
Return the value of key ‘4’. If the key is not found in the dictionary, then add the key and specified value
and then return the value of the key.
>>> D.setdefault(4,40)
40
>>> D
{1: 10, 2: 20, 3: 30, 4: 40}
If the key is not found in the dictionary, then add the key and None as the value of key (if value is not passed
in the argument). It will not return anything.
>>> D.setdefault(5)
>>> D
{1: 10, 2: 20, 3: 30, 4: 40, 5: None}
10. max()
max() function returns the largest key from the dictionary. Comparison done on the bases of ASCII values if it’s
a string value.
If keys are string, here ‘h’ has the largest ASCII value.
>>> D={'a':10,'B':20,'h':30}
>>> max(D)
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
'h'
11. min()
min() function returns the smallest key from the dictionary.
>>> D={1: 10, 2: 20, 3: 30, 4: 40}
>>> min(D)
1
If keys are string, here ‘B’ has the largest ASCII value.
>>> D={'a':10,'B':20,'h':30}
>>> min(D)
'B'
12. fromkeys()
The fromkeys() method creates and returns a dictionary. It is useful when we want to create a dictionary
with multiple keys which have the same value.
Syntax: dict.fromkeys(keys, value)
>>> K=('A','B','C')
>>> V=10
>>> D=dict.fromkeys(K,V)
>>> D
{'A': 10, 'B': 10, 'C': 10}
13. copy()
The copy() method returns a copy of the specified dictionary.
dictionary.copy()
>>> D={1:10,2:20}
Create a copy of dictionary D and store in D1
>>> D1=D.copy()
>>> D1
{1: 10, 2: 20}
14. sorted()
sorted() function sort the dictionary keys in ascending order
>>> D={1:10,4:40,3:30,2:20}
Return the keys of dictionary in sorted order
>>> sorted(D)
[1, 2, 3, 4]
Return the keys of dictionary in sorted order
>>> sorted(D.keys())
[1, 2, 3, 4]
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
d={}
for i in range(5):
rno=int(input("Enter roll number"))
name=input("Enter name of student")
d[rno] = name # d[key]=value
print(d)
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Introduction to Modules:
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
COMPUTER SCIENCE
A) 7
B) 2.5
C) 2
D) error
Answer: B) 2.5
10. What is the purpose of the range() function in the for loop in Python?
A) Generating a sequence of numbers
B) performing mathematical operations
C) Checking membership in a list
D) Calculating the factorial of a number
Answer: A) Generating a sequence of numbers
COMPUTER SCIENCE
Answer: B) 123_variable
12. Which operator is used to check whether two values are equal in Python?
A) ==
B) !=
C) <=
D) >
Answer: A) ==
COMPUTER SCIENCE
COMPUTER SCIENCE
C) [5, 4, 8, 3, 2]
D) [4, 8, 3, 2]
Answer: B) [2, 3, 8, 4]
28. Which method deletes the last inserted (key, value) pair from the dictionary?
A) pop()
B) popitem()
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
C) del()
D) del
Answer: B) popitem()
31. To include the use of functions which are present in the random library, we must use the
option:
A) import random
B) random.h
C) import.random
D) random.random
Answer: A) import random
COMPUTER SCIENCE
2. What are the three main types of errors in programming, and briefly explain each type?
Answer:
Syntax errors : errors in the code's structure
Logical errors : errors in the program's logic
Runtime errors : errors that occur during program execution
4. Describe the difference between a mutable and an immutable data type in Python, providing
an example of each.
Answer:
Mutable data types can be changed or modified after creation. Example List
Immutable data types cannot be changed once created. Example tuple.
import random
M=[5, 10, 15, 20, 25, 30]
for i in range(1,3):
F=random.randint(2,5) - 1
S=random.randint(3,6) - 2
T=random.randint(1,4)
print(M[F], M[S], M[T], sep="#")
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
A) 10#25#15
20#25#25
B) 5#25#20
25#20#15
C) 30#20#20
20#25#25
D) 10#15#25#
15#20#10#
Answer:
A) 10#25#15
20#25#25
Output: [2, 5, 2, 3, 4]
Output: 1
COMPUTER SCIENCE
Output:
Input a dictionary: {}
The given dictionary is empty
Input a dictionary: {1:10}
The given dictionary is not empty
Output:
Using | Operator
{1: 'a', 2: 'c', 4: 'd'}
Using ** Operator
{1: 'a', 2: 'c', 4: 'd'}
Using copy() and update()
{1: 'a', 2: 'c', 4: 'd'}
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
A=[0,1,2,3]
for A[2] in A:
print(A[2], end="#")
Output:
0#1#1#3#
L = [None] * 10
print(len(L))
Output:10
Programming Questions
Program 1: Write a program to calculate the sum of two numbers and print their sum.
num1 = 1.5
num2 = 6.3
sum = num1 + num2
print(sum)
Output :
7.8
Program 2: Write a program that accepts the radius of a circle and prints its area.
radius = float(input("Input the radius of the circle : "))
area = (22/7)*radius*radius
print (area)
Output :
Input the radius of the circle : 7.0
154.0
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Output :
Enter Principal: 1000
Enter Rate of Interest (in % per annum) : 20
Enter Time Period : 3
600.0
Program 4: Write a program to take sides of a triangle as input and print its area.
a = float(input("Enter first side: "))
b = float(input("Enter second side: "))
c = float(input("Enter third side: "))
Output :
Enter first side: 5
Enter second side: 6
Enter third side: 7
14.696938456699069
COMPUTER SCIENCE
else:
print("Odd Number")
Output :
Enter a number: 95
Odd Number
Output :
Enter a number to find factorial: 6
The factorial of is 720
Program 7: Write a program to display the Fibonacci sequence up to n-th term where n is provided
by the user
first = 0
second = 1
counter = 0
number_of_terms = int(input("Enter Number of terms : "))
if number_of_terms <= 0:
print("Please enter a positive integer")
else:
while counter < number_of_terms:
print(first, end = " ")
temp = first + second
first = second
second = temp
counter = counter + 1
Output :
Enter Number of terms : 10
0 1 1 2 3 5 8 13 21 34
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Program 8: Write a program in Python to check if a number entered by a user is a prime number or
not.
number = int(input("Enter a positive number greater than one : "))
flag = 0
if number > 1:
for i in range(2,number):
if ((number%i) == 0):
flag = 1
break
if (flag==1):
print("Not prime")
else:
print("Prime")
Output :
Enter a positive number greater than one : 79
Prime
Program 9: Write a Program to check if the input year is a leap year or not
year = int(input("Enter a year : "))
if(((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0)):
print("Leap Year")
else:
print("Non Leap Year")
Output :
Enter a year : 2100
Non Leap Year
COMPUTER SCIENCE
Output :
[2, 4, 10, 20, 5]
Program 11: Write a Python program to count the number of strings of length 2 or more and the first
and last character are same from a given list of strings
Output :
2
Program 12: Write a Python program to find the sum of all even numbers and all odd numbers from
the given tuple.
Output:
Sum of Even Numbers is = 24
Sum of Odd Numbers is = 27
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
Program 13: Write a program in Python, To input a list of numbers. Thereafter increments all even
numbers by 1 and decrements all odd numbers by 1.
Output:
Original List = [8, 10, 13, 5, 6, 9]
Updated List = [9, 11, 12, 4, 7, 8]
Program 14: Write a program in python, to input a dictionary Emp which contains eid and ename as
key value pair and displays the name in uppercase of the values whose names are longer than 5
characters.
For example:
Emp = {101: 'Rahul', 102: 'Hardik', 103: 'Virat', 104:'Jaspreet'}
The output should be:
Hardik
Jaspreet
Emp = {}
c='y'
while c in 'yY':
eid = int(input("Enter the employee id: "))
ename = input("Enter the name of employee: ")
Emp[eid] = ename
c = input("Do you want to add more elements(y/n): ")
print("Dictionary is : ", Emp)
print("Employee name longer than 5 characters: ")
for name in Emp.values():
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
if len(name)>5:
print(name.upper())
Output:
Output :
Year . 0. at All the best
Question :
Match the following: -
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
5) Removes the first item with the specified value (e). split()
(f). pop()
(g). remove()
Answer:
1 - D, 2 - A, 3 - E, 4 - B, 5 - G
COMPUTER SCIENCE
Output :
(22, 44, 66)
N={'A':'B','C':'D'}
for k,v in N.items():
print(k,v)
Output :
AB
CD
Answer : A. Both A and R are true and R is the correct explanation for A
COMPUTER SCIENCE
Reason (R): in operator in Python is used searching for specific elements within sequences like
lists and strings etc.
A. Both A and R are true and R is the correct explanation for A
B. Both A and R are true and R is not the correct explanation for A
C. A is True but R is False
D. A is False but R is True
Answer : A. Both A and R are true and R is the correct explanation for A
4. Assertion (A): Modules in Python are reusable pieces of code that can be imported into other
Python scripts.
Reason (R): import statement must be the first line of the program
5. Assertion (A): pop() used to delete the last element from the dictionary.
Reason (R): popitem() used to delete the specific element from the dictionary.
COMPUTER SCIENCE
Reason (R): items() method is used to display the keys and also the values of the dictionary.
7. Assertion (A): L.len() statement used to return the total number of elements in the list.
Reason (R): count() method is used to find the total number of elements in the list.
COMPUTER SCIENCE
UNIT 3 :
Society, Law and Ethics
Digital Footprints
● Digital footprints are a set of footprints (trackable information or
activity) left behind while using any digital device such as
smartphone, desktop or laptop computers, or performing
activities such as browsing the internet, posting on social media,
playing a game, editing a file etc.
● In other words, it can be considered as the data trail – intentional and unintentional - that is left
behind while surfing the web.
● Digital footprints are the information that others can see or collect about you.
Event Footprints(information)
Visiting a website IP address, cookies, browsing history, interests
Social media post Location, Username, personal Photos
Sending email IP address, Email address
Online shopping IP address, User behavior, Payment information
COMPUTER SCIENCE
Anyone who uses digital technology along with the Internet is a digital citizen or netizen.
A responsible netizen must follow
1. Net etiquettes
2. Communication etiquettes
3. Social media etiquettes
Net etiquettes
Etiquettes : set of rules that govern appropriate and respectful conduct.
Netiquette, (Internet etiquette) refers to the set of guidelines and rules for polite, respectful, and responsible
behavior while using digital communication platforms for communicating online. We should follow certain
etiquettes during our social interactions.
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
● Be Ethical
o ethical : morally correct
o No copyright violation: we should not use copyrighted materials without the permission of
the creator or owner.
o Share the expertise: it is good to share information and knowledge on the Internet so that
others can access it.
● Be Respectful
o Respect privacy
▪ In the physical world : Privacy is the state of being alone, or freedom from
disturbance/intrusion.
▪ In the Digital world also everyone has the right to privacy and the freedom of
personal expression.
o 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.
● Be Responsible
o Avoid cyber bullying
▪ bully : to use your strength or power to hurt or frighten somebody who is weaker
o In Cyber world
▪ Cyberbullying is bullying (to harass, threaten, embarrass) with the use of digital
devices like cell phones, computers, and tablets.
● Don’t get involved in trolling.
An internet troll is a person who posts inflammatory or off topic messages in an online community,
just for amusement or seeking attention. The best way to discourage trolls is not to pay any attention
to their comments
● In Physical world
o communication : the act of sharing or exchanging information, ideas or feelings
● In Digital world
o Digital Communication : Digital communication includes email, texting, instant messaging,
talking on the cell phone, audio or video conferencing, posting on forums, social networking
sites, etc.
● Be Precise
o We should be clear and accurate while communicating online. We should compress very
large attachments before sending.
● Be Polite
o Polite : showing respect for others
o We should be polite and non-aggressive in our communication
Prepared by Ms. Puja Gupta, PGT Comp Sc.
COMPUTER SCIENCE
● Be Credible
o Credible : that can be believed (विशिसनीय)
o We should be cautious while making a comment, replying or writing an email or forum post
as such acts decide our credibility over a period of time.
● Social media is a collective term for websites and applications that facilitates the sharing of ideas,
thoughts, and information
Example : Facebook, Twitter, Instagram
● Be Secure
o Choose password wisely
o Know who you befriend
o Choose Friends Wisely
● Beware of fake information
o we should be able to figure out whether a news, message or post is genuine or fake by
checking Facts (PIB Fact Check)
● Be Reliable
o Think before uploading
Data Protection
● Data or information protection means safeguarding and preserving the privacy of data stored
digitally.
● Data that cause substantial harm, embarrassment, inconvenience and unfairness to an individual, if
breached or compromised is called sensitive information.
For example, financial information, personal information etc.
● The main goal of data protection is to ensure that individuals' personal information is processed and
handled in a secure and lawful manner, protecting their rights and privacy..
COMPUTER SCIENCE
Copyrights
● Copyright grants legal rights to creators for
literary, dramatic, musical, artistic works,
photograph, audio recordings, video recording,
computer software’s.
● The rights include right to copy (reproduce) a
work, right to distribute copies of the work to the
public, and right to publicly display or perform
the work.
Patent
● A patent is usually granted for inventions. 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.
● Example : Pen with scanner (with a machine as
small as a pen, we can transfer text from paper
directly into a computer)
Trademark
1. Trademark is a visual symbol, name, design,
slogan, label, etc., that distinguishes the brand or
commercial enterprise from other brands or
commercial enterprises.
2. Example trademark of Gmail, Macdonald etc
Violation of IPR
When we use some other intellectual property
(idea,image,logo,trademark) without taking consent or permission from the owner. IPR violation
may occur in following ways:
Plagiarism
Presenting someone else’s idea or work as one’s own idea or work is called plagiarism. If we copy
some contents from the Internet, but do not mention the source or the original creator, then it is
considered as an act of plagiarism.
Prepared by Ms. Puja Gupta, PGT Comp Sc.
Copyright Infringement
● Infringement = उललंघन
● Copyright infringement is when we use another person’s work without obtaining their
permission to use or we have not paid for it, if it is being sold.
Trademark Infringement
● Trademark Infringement means unauthorized use of another's trademark on products and
services.
Freeware
● Sometimes, software is freely available for use but source code may not be available. Such
software is called freeware. Examples of freeware are Skype, Adobe Reader, etc.
Proprietary
● When the software to be used has to be purchased from the vendor who has the copyright
of the software, then it is proprietary software.
● The source code is not publicly available. Only the company which has developed it, can
modify it.
● These software’s are developed and tested by individuals or the organization by which it
is owned, not by the public.
● Examples of proprietary software include Microsoft Windows, Quickheal, etc.
License
License : An official document that gives you permission to own, do, or use something.
● A public license or public copyright licenses is a license by which a copyright holder as
licensor can grant additional permissions to others to use and even modify the content.
● The GNU General public license (GPL) and the Creative Commons (CC) are two popular
categories of public licenses.
111
Prepared by Ms. Puja Gupta, PGT Comp Sc.
Cyber Crime:
● Any criminal, illegal or harmful activity conducted using computers, the internet, or other
digital device is referred to as Cyber Crime.
● These activities are committed by individuals or groups to steal or harm someone else's
data, privacy, or online safety.
● Here are some examples of cybercrimes: Cyber bullying, online scams, hacking, stalking,
ransomware attack, phishing etc.
Hacking:
● Hacking is unauthorized access to a computer or a network with the intention of
committing a crime.
● It can also be explained as the act of accessing computer systems, networks, or digital
devices in a skilful and creative manner to explore and find some security loopholes in
order to gain access to confidential information.
● The process of gaining unauthorized access to a computer system, group of systems or an
organization’s data is known as hacking.
● The person engaged in these activities is generally known as a Hacker.
Eavesdropping:
● Eavesdropping is to intercept and listen to private electronic communications, such as
emails, instant messages, or phone calls, without the consent of the parties involved.
● It can be done via hacking or surveillance techniques to access the conversations. The main
purpose of eavesdropping is to steal data.
112
Prepared by Ms. Puja Gupta, PGT Comp Sc.
Phishing:
● Phishing is a cybercrime where criminals attempt to deceive Individuals into revealing
sensitive information like passwords or credit card details by posing as trustworthy entities
through fake emails, websites, or messages.
● For example an email of winning a lottery and asking you to fill your bank details.
Fraud Emails:
● Fraudulent emails are cybercrimes where bad people send fake mails that try to trick people
to get personal information, passwords, or money.
● These dishonest emails may pretend to be from a popular website, but it's essential to be
cautious and never share sensitive details with unknown senders.
Ransomware:
● Ransomware is a cybercrime where bad people create harmful software that locks or
encrypts important files on a computer.
● They then demand ransom from the computer's owner to unlock the files
and make them accessible again.
● It's essential to be careful while using computers and not click on
suspicious links or download unknown files to avoid ransomware
attacks.
Cyber Trolls:
Trolls are visitors who leave inflammatory comments in public comment sections. Whether they
comment on blog posts or online news sites, they are looking to grab the attention of other visitors
and disrupt discussion that would otherwise be about the page's content.
Cyber Bullying:
● Cyber bullying is bullying with the use of digital technologies. It is to
intimidate, harass, demean, defame or humiliate others repeatedly
using digital platforms such as the internet, social media, phone,
internet, instant messengers etc.
● It can cause emotional distress, anxiety, and damage self-esteem.
Examples include: posting embarrassing photos of someone on social
media, sending hurtful messages.
Cyber Safety:
● Cyber Safety refers to the practice of protecting oneself, one's information, and digital
assets from potential internet threats or online threats. Cyber Security is to protect users
from harmful online activities.
● The aim of cyber safety is to promote responsible and secure online behavior to ensure a
safe experience for everyone.
113
Prepared by Ms. Puja Gupta, PGT Comp Sc.
Malware
● Malware (malicious software) is any software/program that is designed to damage and
destroy computers and computer systems.
● Computer Malware is like bad software that can cause problems for your computer or
device. It comes in different forms, like viruses, trojans, and adware.
Virus
● A computer virus is a malware (malicious computer code) that spreads from one device to
another. They are like digital germs that infect and harm your computer by spreading from
one file to another. After entering a computer, a virus attaches itself to another program
(like a document) in such a way that execution of the host program triggers the action of
the virus simultaneously.
● It can self-replicate, inserting itself onto other programs or files, infecting them in the
process. Most viruses perform actions that are malicious in nature, such as damaging
programs, deleting or destroying data.
● Viruses spread when the software or documents they get attached to are transferred from
one computer to another using a network, file sharing methods, or through e-mail
attachments.
114
Prepared by Ms. Puja Gupta, PGT Comp Sc.
Trojan horse :
● It is a file or program, or piece of code that appears to be legitimate and safe, but is actually
malware.
● Trojan horse malware is generally designed to spy on victims or steal data. These programs
perform some malicious activities like upload (send) some security files and information
from the computer and at the same time download some unwanted files onto the computer.
Adware
● 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
Some of the feasible methods of e-waste management are reduce, reuse and recycle.
115
Prepared by Ms. Puja Gupta, PGT Comp Sc.
● The Information Technology Act (IT Act) is an Indian law that was enacted in the year
2000 to provide legal recognition to electronic transactions and to address issues related to
electronic commerce, data protection, and cybercrimes.
● The IT Act aims to facilitate electronic communication and transactions while ensuring the
security and confidentiality of electronic information.
Example: Suppose you want to buy a smartphone online from an e-commerce website. The
transaction involves entering your personal and financial details on the website, such as
your name, address, credit card number, and CVV (Card Verification Value).
Key Points
1. Legal Recognition of Electronic Transactions: The IT Act gives legal validity to
electronic records, including online transactions. So, when you make a purchase
online and receive an electronic receipt, it is legally recognized and can be used as
evidence in case of any disputes.
2. Electronic Signatures: The IT Act recognizes electronic signatures as equivalent
to physical signatures, making contracts and agreements signed electronically
116
Prepared by Ms. Puja Gupta, PGT Comp Sc.
legally binding. When you electronically sign the purchase agreement on the
website, it holds the same legal weight as a physical signature.
3. Data Protection and Privacy: The IT Act includes provisions for data protection
and privacy. The e-commerce website is obligated to take necessary measures to
protect your personal and financial information from unauthorized access or
misuse. They must have a privacy policy in place, and any data collection and
processing must be done with your consent.
4. Cybercrime Provisions: The IT Act addresses cyber crimes such as hacking,
unauthorized access, and data theft. If someone tries to steal your credit card
information during the online transaction, the IT Act provides a legal framework to
prosecute the offender.
Technology and society: Gender and disability issues while teaching and using
computers
Gender Issues
● Preconceived notions
o Notions like boys are better at technical things, girls are good at humanities etc
● Interest development from primitive years
o During primitive years children often played games on the computers and
smartphones. Most of the games are boys centric that increase the interest of boys
in computers.
Disability Issues
● Unavailability of teaching material / aids
Q. Digital footprints are only created by social media activity, such as posting photos and
comments.
Answer: False.
Q. If you delete your information from the internet then your digital footprint is also deleted
.
Answer: False. Deleted information is difficult to trace but it may be accessible through backups
or cached versions.
117
Prepared by Ms. Puja Gupta, PGT Comp Sc.
Q. The Creative Commons license allows creators to retain their copyright while permitting
others to use their work under certain conditions.
Answer: True.
Q. Viruses can spread through email attachments and infect computers when the attachment
is opened.
Answer: True.
Q. Trojans are self-replicating programs that can spread across a network without user
intervention.
Answer: False.
Q. Ransomware is a type of malicious software that locks users out of their systems or
encrypts their files until a ransom is paid.
Answer:True.
118
Prepared by Ms. Puja Gupta, PGT Comp Sc.
Q. What is the appropriate action to take when you receive a suspicious link or message?
A. Click on the link to see where it leads.
B. Report it to the platform or email provider as spam.
C. Share the link with friends to get their opinion.
D. Respond to the message and inquire about its source.
Answer: B
Q. What should you do if you come across offensive content or cyberbullying online?
A. Engage in the conversation to confront the offenders.
B. Ignore it and move on to avoid getting involved.
C. Report the content to the website or platform administrators.
D. Retaliate with offensive content to defend yourself or others.
Answer: C
Q. Which of the following refers to the legal protection of original creations, such as artistic
works and literary pieces?
A. Data Encryption
119
Prepared by Ms. Puja Gupta, PGT Comp Sc.
Q. What type of intellectual property right grants exclusive rights to inventors for their
inventions?
A. Copyright
B. Trademark
C. Patent
D. Creative Commons
Answer: C
Q. Which form of intellectual property right protects logos, brand names, and distinctive
signs used in commerce?
A. Copyright
B. Patent
C. Trade Secret
D. Trademark
Answer: D
Q. What is malware?
A. Software designed to protect computer systems from threats.
120
Prepared by Ms. Puja Gupta, PGT Comp Sc.
Q. Which type of malware disguises itself as legitimate software to trick users into installing
it?
A. Virus
B. Trojan
C. Adware
D. Spyware
Answer: B
Q. What does hacking involve?
A. Legally accessing computer systems
B. Unauthorized access to computer systems
C. Protecting computer networks
D. Improving software efficiency
Answer: B
121
Prepared by Ms. Puja Gupta, PGT Comp Sc.
Q. What is malware?
Answer: Malware is malicious software designed to harm computer systems or steal data.
122
Prepared by Ms. Puja Gupta, PGT Comp Sc.
Answer: The objectives of the IT Act include providing legal recognition for electronic
transactions, facilitating e-governance, and preventing cyber crimes.
Q. How does an individual's digital footprint impact their online privacy and personal
brand? Provide an example to support your answer.
Answer: An individual's digital footprint can expose personal information and influence how they
are perceived online. For instance, sharing inappropriate content on social media may harm their
reputation and affect future opportunities.
Q. Explain how digital footprints are created and expanded through online interactions.
Answer: Digital footprints are formed by an individual's online activities, such as social media
posts, website visits, online purchases, and interactions with others. Each online engagement adds
to the footprint, shaping their online identity.
Q. How can individuals and organizations ensure they are not violating intellectual property
rights while using copyrighted materials for educational or commercial purposes?
Answer: Individuals and organizations should seek proper licensing, obtain permission from the
copyright owner, or use materials that are explicitly labeled for reuse under Creative Commons
licenses.
Q. How can users differentiate between a legitimate software application and a potentially
harmful trojan or malware?
Answer: Users should only download software from reputable sources, check reviews, and verify
the publisher's authenticity to avoid installing trojans or malware.
123
Prepared by Ms. Puja Gupta, PGT Comp Sc.
Case Study1 :
Shreya is a high school student who is an active user of social media platforms. She frequently
posts photos, videos, and personal information online. One day, she notices that some of her private
photos have been shared without her permission. Sarah becomes concerned about her digital
footprint and its potential consequences.
Q1. What is a digital footprint, and how is Shreya’s online activity contributing to it?
Q2. Identify the potential risks and consequences Shreya may face due to her unmanaged
digital footprint.
Q3. As a friend of Shreya, what advice would you give her to better manage and protect her
digital footprint to prevent future incidents?
Answers
A1. A digital footprint is the collection of data left behind by an individual's online activities.
Shreya’s frequent social media posts, photos, and videos contribute to her digital footprint.
A2. Shreya may face privacy breaches, cyberbullying, or negative reputational impact due to her
unmanaged digital footprint.
A3. Shreya should review her privacy settings, limit sharing of personal information, and regularly
audit her online content to manage her digital footprint effectively
Case Study 2:
A software developer named Ravi created a new mobile application and shared it with colleagues
and friends. However, Ravi later discovered that someone had copied the entire code of the
application and released it as their own. Ravi is unsure of what legal actions to take to protect their
intellectual property rights.
Q1. Describe the different types of intellectual property rights, including copyrights, patents,
and trademarks, and their significance for Ravi's mobile application.
Q2. Explain the concept of plagiarism and copyright infringement in the context of the copied
mobile application.
Q3. What are the possible legal measures Ravi can take to address the violation of their
intellectual property rights and seek appropriate recourse?
Answers:
124
Prepared by Ms. Puja Gupta, PGT Comp Sc.
A1. Copyrights protect the code and creative aspects of Ravi's mobile application, while patents
safeguard its novel functionality. Trademarks protect the app's branding.
A2. Plagiarism occurs when someone copies another's work without permission, and copyright
infringement happens when copyrighted material is used without authorization.
A3. Ravi can take legal action against the infringer to protect the intellectual property rights.
125
Prepared by Ms. Puja Gupta, PGT Comp Sc.
Appendix-1
Installing Python
1. Visit the official website of Python
https://www.python.org
2. Go to the Downloads section and choose the Python version for your Operating System
(Windows/macOS etc)
3. Click on Python 3.xx.x (here it is Python 3.12.0) where x may be any sub-version of
Python.
4. Your download will start automatically, save the file at a location of your choice.
126
Prepared by Ms. Puja Gupta, PGT Comp Sc.
6. Click on 'Install Now' to start the installation of Python in the default location.
Alternatively, the location may be changed by clicking on the 'Customize Installation'
option.
7. Wait for the installation to finish.
127
Prepared by Ms. Puja Gupta, PGT Comp Sc.
Appendix - 2
Running Python
Using IDLE in Interactive Mode
1. IDLE may be started by typing 'IDLE' on the Windows Search Bar, or choosing IDLE
from the list of applications in the Windows.
3. >>> shows the prompt where Python statements can be written in the Interactive Mode.
128
Prepared by Ms. Puja Gupta, PGT Comp Sc.
129
Prepared by Ms. Puja Gupta, PGT Comp Sc.
4. Save your Python Script by going to File > Save, and give any valid file name to your
script with the extension .py
6. Once in script mode, choose Run > Run Module or press F5 shortcut to run your script.
7. The output (including errors, if any) will be displayed in the prompt window.
130
Prepared by Ms. Puja Gupta, PGT Comp Sc.
8. To Open an existing Python script, choose File > Open and double click on the python
file to Open it in IDLE Script Mode.
131
Prepared by Ms. Puja Gupta, PGT Comp Sc.
Appendix - 3
1. Go to Google Play Store on your Android Device. Search for 'Pydroid' and Install
the app.
1. Write Python code in the built in code editor or open the existing ones.
132
Prepared by Ms. Puja Gupta, PGT Comp Sc.
2. Write code in the script mode. Run the Python Code by tapping the button (▶). Save
the code.
3. The output is displayed on the screen.
BIBLIOGRAPHY
Google
DOE Notes
ChatGPT
133