Computer Science Notes
Computer Science Notes
NOTES
PREETI AROROA
SESSION -2025-26
Chapter – 1
Introduction –
1|Page
Python is a high-level, 0object-oriented, interactive, general-purpose programming Language which was
developed by Guido Van Rossum in 1991. It is used in web development, Artificial Intelligence, Machine
Learning and mobile application development.
Python IDLE (Integrated Development and Learning Environment) provides two working mode –
(i) Interactive mode (known as Python shell)
(ii) Script mode; two main window types- the Shell window and the Editor window
(i) Using interactive (Python Shell window) mode, the Python commands are directly typed at >>>. When
press enter key, it display the result immediately. Drawback of command mode is that we cannot save
the commands that we type.
Ex-
(ii) Script mode- we can save the commands in script mode. Shortcut key to open a new file in script
mode is ctrl+N.
Ex-
2|Page
Un v b b derscore (_)
ii. Keywords: the reserved words of python, which have a special fixed meaning, are called
Keywords. No keyword can be used as an identifiers.
iii. Literals: A fixed numeric or non-numeric value is called a literal. Ex- 2, -23.6, “abc”, “INDIA”.
iv. Operators: An operator is a symbol or a word that performs some kind of operation on given
values and returns the result. Ex- +,-, **, / etc.
v. Delimiters: delimiters are symbols which can be used as separators of values or to enclose some
values. Ex- ( ), { }, [ ] , : ; .
Example in the form of program of all tokens:
X= 68
Y=12
Z=X/Y
Print(“X, Y, Z are:”, X, Y, Z )
“X, Y, Z
Tokens X Y Z Print = / 68 12
are:”
Identifier/ Delimiter/
Category Variable Variable Method Operator Literals Literals Literals
variable operator
statement Expressions
(space)Indentation
function call
3|Page
Triple Single quotation (‘’’)/ Triple Double (..-”””) : They are used to write multiple line comments.
d. Functions: Function is a set of instructions defined under a particular name that performs a specific task which, once
written, can be called whenever and wherever required.
e. Block: A block refers to a group of statements which are part of another statement or function.
4|Page
(b) Float/Floating point: they signify real number and are used to store numbers with fractional part. They
can be represented in scientific notation. Ex: ‘e’ or “E” signifies the 10 th power.
Ex: 3.8e2
Output: 380.0
(c) Complex Number: They are pairs of real and imaginary numbers.
Ex- ‘a + bi’ or ‘a + bj’ .
3j – 2
Output: (-2+3j)
a and b are real number and I (iota) and j are imaginary number.
2. Boolean : bool data type represents one of the values: True and False.
Ex- bool_1 = 5 ==6*2
Output: False
3. None : It signifies the absence of value in a situation, represented by None.
Ex: x= None
Type(x)
Output: <class ‘NoneType’>
4. Sequence: A sequence is an ordered collection of items, indexed by integers (both positive as well as
negative). Ex- String, List, Tuple
5. Sets: It is an unordered collection of values of any type with no duplicate entry. Ex: {12,23,34,56,78,89}
6. Mapping: It is unordered and mutable. Ex- Dictionary.
DYNAMIC TYPING
It refers to declaring a variable multiple times when required with different data type.
Ex:
X = 12
Print(X)
Print(type(X))
X = “COMPUTER SCIENCE”
Print(X)
Print(type(X))
X = 12.45
Print(X)
Print(type(X))
KEYWORDS
Keywords are the reserved words used by a Python interpreter to recognize the structure of a program.
They cannot be used as variable names.
To display the list of keywords:
5|Page
Mutable: Variable whose values can be changed at places after they are created and assigned are called mutable.
Ex: list, dictionary, and set.
New_list = [10, 20, 30]
New_list[0] = 100
Print(New_list)
Output: [100, 20, 30]
Immutable: Variables whose value cannot be changed after they are created and assigned are called immutable.
Ex: int, float, complex, bool, string and tuple.
Str1 = “strings immutable”
Str1 [0] = ‘p’
Print(str1)
This statement shall result in TypeError on execution.
Identity operators:
‘Is’ operator: It returns True if both variables are pointing to the same memory location otherwise return False.
‘Is not’ operator: It returns True if both variables are not referring to the same memory location otherwise return False.
Membership operators:
6|Page
‘in’ operators: It returns True if a characters/substring exists in the given string otherwise returns False.
‘not in’ operators: It returns True if a characters/substring does not exists in the given string otherwise returns False.
1. Input(): The input() function accepts and returns the user’s input as a string and stored it in the variable which is
assigned with the assignment operator(=).
Input function takes one string argument. And shows the prompt to the user and waits for the user to input a
value from the keyboard.
+ output
3. eval(): eval() method takes a string as an argument, evaluate this string as a number and returns the numeric
result.
Ex: print(eval(“60*60”))
Output: 3600
7|Page
TYPE CASTING (EXPLICIT CONVERSION)
We can change the data type of a variable in Python from one type to another. Such data type conversion can
happen in two ways:
(a) Explicitly (forced): When the programmer specifies for the interpreter to convert a data type into another type.
Ex: x = 10.0
Print(int(x))
Output: 10
(b) Implicit Conversion: It is also known as ‘coercion’. It happens when data type conversion is done automatically
during run time by python and is not instructed by the programmer.
Ex:
FLOW OF EXECUTION
Execution in a python program begins with the very first statement. It is defined as flow of execution.
This is categorized in three parts:
(a) Sequential statement
(b) Selection/Conditional statement
(c) Iteration or looping constructs
Sequential Statements
Sequential statements in a python program are executed one after the other, from the first statement till the last
statement.
Ex:
Selection/Conditional Statements
Conditional statements are used to perform actions or calculations based on whether a condition is evaluated as True
or False.
8|Page
Iteration/Looping Constructs
The statements in a loop are executed again and again as long as a particular logical condition remains True. Python
provide two types of loops:
(a) For loop
(b) While loop
For loop
The for statement is used to iterate/repeat itself over a range of values or a sequence one by one.
Sequence may be a list, string or tuple
‘else’ statement will be executed after all the iterations of for loop, if provided.
Control_variable is a variable that takes a new value from the range each time the loop is executed.
For loop use a most commonly used build-in-function range().
Range()
The range function is used to create a list containing a sequence of numbers.
Syntax:
range(start, stop, step)
9|Page
While loop
The while loop repeatedly executed the set of statements till the defined condition is True. As soon as the
condition evaluates to False, control, passes to the first line written after the loop.
Syntax:
While <test_expression>:
Body of while
Else:
Body of else
Ex:
Output:
STRINGS
A string is a sequence of characters that may be comprises letters, numbers and special symbols enclosed
within single or double quotes.
String Operations
String can be manipulated using operators like concatenation (+), repetition (*), and membership operators
(in, not in).
Ex:
Traversing a String:
Traversig a string means accessing all the elements of th rstring onr after the other by using the subscript or index value.
Indivdual elements can be accessed by typing index value inside square brackets [].
Ex:
w
i
t
h
p
y
t
11 | P a g e
h
o
n
(b) String traversal using range():
Ex:
Str1 = ‘Programming with python’
for I range (0, len(str1),2):
print (str1[i])
output:
P
o
r
m
i
g
w
t
y
h
n
h
t
i
w
g
n
i
m
m
a
r
12 | P a g e
g
o
r
p
string slicing:
syntex:
string_name[start:stop:step]
Ex:
Build-In-String Methods:
1. Isalpha() :-
Ex:- str1 = “Good”
Print(str.isalpha())
>>> True
Str2 = “This is a string”
Print(str2.isalpha())
>>>False #(due to space in the given string)
2. Isdigit():-
Ex:- str = “123456”
Print(str.isdigit())
>>> True # (no space and alphabate)
Str1 = “Ram bagged 1st position”
Print(str1)
>>> False # (space and digit is present in the above string)
3. len():- word = “Good Morning”
len(word)
>>> 12
Ex: str1 = “This is Meera\’s pen”
Len(str1)
>>> 19
4. split():- x = “CS; IP; IT”
x.split(“ ; ”)
13 | P a g e
>>> [‘CS’, ‘IP’, ‘IT’]
Print(x.split(‘ ; ‘ , 2))
[‘CS’ , ‘IP’ , ‘IT’]
print(x.split(‘ ; ’ , 1)) #maxsplit is 1
>>> [‘CS’, ‘IP;IT’]
(-1 means no limit on the number of splits)
5. lower() :- str1 = “” Learning PYTHON”
print(str1.lower())
>>> lerning python
6. islower():- str1 = “python”
print(str1.islower())
>>> True
str1 = “Python”
print(str1.islower())
>>> False
7. upper():- str1 = “welcome”
print (str1.upper())
>>> WELCOME
8. isupper() :- str1 = “PYTHON”
print(str1.isupper())
>>> True
str1 = “pythOn”
print(str1.isupper())
>>> False
str1 = “PYTHON123”
print(str1.isupper())
>>> True
9. replace:- str2 = “cold Coffee”
print(str2.replace(“cold”, “Hot”))
>>> “Hot Coffee”
10. find():- word = “Green Revolution”
result = word.find(‘Green’)
print(result)
>>> 0
If the given string is not find, it will return -1.
word = “Green Revolution”
result = word.find(‘green’)
print(result)
>>> -1
Syntax:- string variable.find(sub, start, end)
Ex:- str1 = “Swachh Bhatrat Swasth Bharat”
print (str1.find(“Bharat”, 13, 28) )
>>> 21
11. lstrip() or lstrip():- It remove the spacefro the left string.
Ex:- i) str1 = “ Good Revolution”
Print(str1.lstrip())
14 | P a g e
>>> Good Revolution # When no argument was given, hence it removed all leading whitespace from
the left of the string.
II) str2 = “Good Revolution”
Print(str1.lstrip(“Gr”))
>>>een Revolution
iii) str2 = “Good Revolution”
Print(str1.lstrip(“rG”))
#Here, all elements of the given argument are matched with the left of the str2 and, if found, are removed.
12. rstrip() or rstrip(chars):-
Ex:- i) str1 = “Green Revolution ”
Print(str1.rstrip())
>>> Green Revolution
# When no argument was given, hence it removed all leading whitespace from the right of the string.
ii) str1 = “Green Revolution”
Print(str1.rstrip(“on”))
>>> Green Revoluti
#Here, all elements of the given argument are matched with the right of the str1 and, if found, are
removed.
13. Isspace():-
Ex:- str1 = “ “
print(str1.isspace())
True
# return true if string contain only white space. Otherwise false.
Str1 = “ Python ”
Print(str1.isspace())
False
14. Istitle():-
Ex: str1 = “All Learn Python”
print(str1.istitle())
>>> True
str1= “All learn python”
print(str1.istitle())
>>> False
S = “This Is @ Symbol”
print(S.istitle())
>>> True
S = “PYTHON”
print(S.istitle())
>>> False
15. Join():-
Ex: str1= “12345”
S= “-”
print(S.join(str1))
>>> “1-2-3-4-5”
16. Swapcase():-
Ex :- str1 = “Welcome”
print(Str1.swapcase())
15 | P a g e
>>>“wELCOME”
Ex :- str1 = “pYThoN”
print(Str1.swapcase())
>>>“PytHOn”
17. Partition(seprator):- ‘seprator’ argument is required to seprate a string. If the seprator is not found, it
returns the string itself, followed by two empty string within the parentheses, as tuple.
Ex:- s = ‘[email protected]’
print( s.partition(‘ ‘))
>>>( ‘[email protected]’, ‘ ‘ , ‘ ‘ ) # output is in the form of tuple.
s = ‘[email protected]’
print( s.partition(‘@‘))
>>>( ‘xyz’ , ‘@’ , ‘gmail.com’ )
18. endwith():- Output will always be in boolean – True or False.
Ex:- a = “Artificial Intelligence”
a.endwith(‘Intelligence’)
>>> True
a = “Artificial Intelligence”
a.endwith(‘Artificial)
>>> False
19. startwith():- Output will always be in boolean – True or False.
Ex:- a = “Machine Learning”
a.startwith(‘Mac’)
>>> True
a = “Machine Learning”
a.startwith(‘Learning’)
>>> False
20. ord() :- It return the ASCII code of the character.
Ex:- ch = ‘b’
ord(ch)
>>> 98
21. chr():- Function returns character represented by the inputted ASCII number.
Ex :- chr(97)
‘a’
QUES:- Write a program to input a string and count the numbner of uppercase and lower case letter. (Page-1.32)
UNPACKING A STRING:-
16 | P a g e
LIST:-
A list in python is formed by enclosing the values inside square brackets []. List are mutable.
LIST COMPREHENSION
List comprehension consisit of an expresion followed by ‘for’ statement inside square brackets.
17 | P a g e
LIST SLICING:-
Slicing is used to retrive a subset of values. It allows us to obtain a subset of items.
18 | P a g e
METHODS :-
append(): Adds an element to the end of the list.
Ex:- a = [1, 2, 3]
a.append(4) # Add 4 to the end of the list
print(a)
>>> [1, 2, 3, 4]
copy(): Returns a shallow copy of the list.
Ex:- a = [1, 2, 3]
b = a.copy() # Create a copy of the list
print(b)
>>> [1, 2, 3]
clear(): Removes all elements from the list.
Ex:- a = [1, 2, 3]
a.clear() # Remove all elements from the list
print(a)
>>> [ ]
count(): Returns the number of times a specified element appears in the list.
Ex:- a = [1, 2, 3, 2]
print(a.count(2)) # Count occurrences of 2 in the list
>>> 2
extend(): Adds elements from another list to the end of the current list.
Ex:- a = [1, 2]
a.extend([3, 4]) # Extend list a by adding elements from list [3, 4]
print(a)
>>> [1,2,3,4]
index(): Returns the index of the first occurrence of a specified element.
Ex:- a = [1, 2, 3]
print(a.index(2)) # Find the index of 2 in the list
>>> 1
insert(): Inserts an element at a specified position.
Ex:- a = [1, 3]
a.insert(1, 2) # Insert 2 at index 1
print(a)
>>> [1, 2, 3]
pop(): Removes and returns the element at the specified position (or the last element if no index is specified).
Ex:- a = [1, 2, 3]
a.pop() # Remove and return the last element in the list
print(a)
>>> [1, 2]
remove(): Removes the first occurrence of a specified element.
Ex:- a = [1, 2, 3]
a.remove(2) # Remove the first occurrence of 2
print(a)
>>> [1, 3]
reverse() : Reverses the order of the elements in the list.
19 | P a g e
Ex:- a = [1, 2, 3]
a.reverse() # Reverse the list order
print(a)
>>> [3, 2, 1]
sort(): Sorts the list in ascending order (by default).
Ex:- a = [3, 1, 2]
a.sort() # Sort the list in ascending order
print(a)
>>> [1, 2, 3]
COPYING A LIST:
We can create a copy or clone of the list as a distinct object by three methods:
1. Using slicing:
original_list = [1, 2, 3, 4, 5]
copied_list = original_list[:] #copies all elements
print(copied_list) # Output: [1, 2, 3, 4, 5]
original_list[0] = 10 # Modifying the original list
print(original_list) # Output: [10, 2, 3, 4, 5]
print(copied_list) # Output: [1, 2, 3, 4, 5] - Remains unchanged
2. Using list()
original_list = [1, 2, 3, 4, 5]
copied_list = list(original_list)
print("Original list:", original_list)
print("Copied list:", copied_list)
copied_list[0] = 10
print("Original list after modification:", original_list)
print("Copied list after modification:", copied_list)
output:
Original list: [1, 2, 3, 4, 5]
Copied list: [1, 2, 3, 4, 5]
Original list after modification: [1, 2, 3, 4, 5]
Copied list after modification: [10, 2, 3, 4, 5]
3. Using copy()
Ex:-
original_list = [1, 2, [3, 4]]
copied_list = original_list.copy()
copied_list[0] = 10
copied_list[2][0] = 30
print("Original list:", original_list)
print("Copied list:", copied_list)
output:
Original list: [1, 2, [3, 4]]
Copied list: [10, 2, [30, 4]]
20 | P a g e
TUPLE
A Tuple is a collection of Python objects separated by commas. Tuple is a sequence of immutable Python objects.
It is represented and enclosed by parentheses (). To define a single value to tuple we have to add ‘,’ at the end,
ex- (1, ).
21 | P a g e
TUPLE FUNCTIONS:
len(): Returns the number of items in a tuple.
EX:
my_tuple = (1, 2, 3, 4, 5)
print(len(my_tuple)) # Output: 5
max(): Returns the largest item in a tuple.
EX:
my_tuple = (1, 5, 2, 8, 3)
print(max(my_tuple)) # Output: 8
min(): Returns the smallest item in a tuple.
EX:
my_tuple = (1, 5, 2, 8, 3)
print(min(my_tuple)) # Output: 1
sum(): Returns the sum of all items in a tuple.
EX:
my_tuple = (1, 2, 3, 4, 5)
print(sum(my_tuple)) # Output: 15
sorted(): Returns a new sorted list from the items in a tuple.
EX:
my_tuple = (5, 2, 8, 1, 9)
print(sorted(my_tuple)) # Output: [1, 2, 5, 8, 9]
tuple(): Converts an iterable (e.g., list, string) to a tuple.
EX:
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3)
count(): Returns the number of times a specified value occurs in a tuple.
EX:
my_tuple = (1, 2, 2, 3, 2)
print(my_tuple.count(2)) # Output: 3
index(): Returns the index of the first occurrence of a specified value in a tuple.
EX:
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple.index(30)) # Output: 2
all(): Returns True if all elements in the tuple are true (or if the tuple is empty).
EX:
tuple1 = (True, True, True)
tuple2 = (True, False, True)
print(all(tuple1)) # Output: True
print(all(tuple2)) # Output: False
DICTIONARY
Dictionary can be accessed using unique key, which can be a number, string or a tuple. The items can be
changed but keys are an immutable data type. Key and values are separated by a colon (:), ley value pair are
separated by commas (,).Dictionary are enclosed in curly braces {}.
Ex:
dict1 = {‘subject’ : ‘Informatics Practices’, ‘class’ : ‘11’}
print(dict1)
print(“subject :”, dict1[‘subject’])
22 | P a g e
print(“class :”, dict1 [‘class’])
>>> {‘subject’ : ‘Informatics Practices’, ‘class’ : ‘11’}
Subject : Informatics Practices
Class : 11
pop(key, default): Removes and returns the element with the specified key.
Ex:
my_dict = {'a': 1, 'b': 2}
print(my_dict.pop('a'))
# Expected output: 1
print(my_dict)
# Expected output: {'b': 2}
update(other): Updates the dictionary with the key-value pairs from another dictionary or iterable.
Python.
Ex:
my_dict = {'a': 1, 'b': 2}
my_dict.update({'c': 3})
print(my_dict)
# Expected output: {'a': 1, 'b': 2, 'c': 3}
24 | P a g e
setdefault(key, default): Returns the value of the key if it is in the dictionary. If not, it inserts the key with a default value.
Python.
Ex:
my_dict = {'a': 1, 'b': 2}
print(my_dict.setdefault('a', 0))
# Expected output: 1
print(my_dict.setdefault('c', 0))
# Expected output: 0
print(my_dict)
# Expected output: {'a': 1, 'b': 2, 'c': 0}
***************END*******************
25 | P a g e