Class 11 Cs Study Material
Class 11 Cs Study Material
SASIREKHA KATPADI
CLASS – 11 COMPUTER SCIENCE 2024-25
1. COMPUTER SYSTEM
1. Define computer. Give it’s characteristics.
A computer is an electronic device which can perform various operations correctly and
fast. For example data processing, huge calculations etc. Characteristics of computer :
▪ Speed : Its speed is very fast. A modern computer can execute millions of
instructions in one second.
▪ Accuracy : A computer can give accurate results up to 20 to 30 places of decimal.
▪ High storage capacity : A computer can store large amount of data in very small
space.
▪ Versatility : A computer c3n do different types of tasks like data processing,
graphics, audio and visual effects.
▪ Repetitive: A computer makes no mistake in repeating anything as many times.
1.CPU 2. ALU 3. VLSI 4. MSI 5. LSI 6. SSI 7. IC 8. IPO 9.HLL 10. MB.
3
CREATED BY J.SASIREKHA KATPADI
Microprocessors are classified on the basis of different features word size, memory size,
clock speed, cores
1. Word size
Word size is the maximum number of bits that a microprocessor can process at a
time
2. Memory size
The set of machine-level instructions that a microprocessor executes is the
instruction set. The operations involved in the instructions can be as follows:
✓ Arithmetic operations
✓ Logical operations
✓ Data transfer
✓ Input/output operations
✓ control flow
3. clock speed
The clock speed indicated the speed at which the computer can execute
instructions. It is measured in Hertz (Hz)
4. Cores
Core is the basic computation unit of the CPU.CPU with four, eight core called dual
core
13. What is micro controller?
The microcontroller is a small computing device which has a CPU, a fixed amount of RAM,
ROM and other peripherals all embedded on a single chip
EG – Washing machine, remote control
14. What are the types of Data?
▪ Structured data
▪ Unstructured data
▪ SEMI structured data
15. What is software?
o These are set of instruction used to perform tasks in a particular application area
o EG - word processors, spreadsheet software, presentation software, database
software and multimedia software.
16. What are the types of software?
It is categorized in to 3 types
1. Application software
2. System software
3. programming tools
4
CREATED BY J.SASIREKHA KATPADI
ii. Customized software – developed to meet the specific requirements of a specific
organization or an individual also called as Tailor-made software eg – Accounting
software
5
CREATED BY J.SASIREKHA KATPADI
28. why is the execution time of machine code is less than that of source code?
The source code is converted by a translator into the machine-understandable form
called object (machine) code and then executes that program. While machine code directly
executes without using the translator. That's why the execution time of the machine code
is less than that of the source code
30. How does the computer understand program written in high level language?
A computer can't understand a high-level language directly, so it needs to be translated
into machine code. This can be done through compilation or interpretation.
7
CREATED BY J.SASIREKHA KATPADI
21.
25. Express the following octal numbers into their equivalent decimal numbers.
(i) 145 (ii) 6760 (iii) 455 (iv) 10.75
(i) 145
Digits 1 4 5
Position 2 1 0
Weight 82 81 80
Decimal number = 1×82 +4×81 + 5×80
=1×64 + 4×8 + 5× 1
=64 + 32 + 5
= (101)10
(ii) 6760
Digits 6 7 6 0
11
CREATED BY J.SASIREKHA KATPADI
Position 3 2 1 0
Weight 8 3 82 81 80
Decimal number = 6×83 +7×82 +6×81 + 0×80
=6×512 + 7×64 +6×8 + 0× 1
=3072 + 448 + 48+0
= (3568)10
(i) 455
Digits 4 5 5
Position 2 1 0
Weight 82 81 80
Decimal number = 4×82 +5×81 + 5×80
=4×64 + 5×8 + 5× 1
=256 + 40 + 5
= (301)10
(iv) 10.75
Digits 1 0 7 5
Position 1 0 -1 -2
Weight 81 80 8-1 8-2
Decimal number = 1×81+0×80+7×8-1+5×8-2
=1×8+0×1+7×0.125+5×0.015625
=8+0+0.875+0.078125
= (8.953125)10
26. Express the following hexadecimal numbers into equivalent decimal numbers. (i) 4A2 (ii)
9E1A (iii) 6BD (iv) 6C.34
(i) 4A2
Digits 4 A 2
Position 2 1 0
Weight 162 161 160
Decimal number = 4 × 16 2 + A × 16 1+ 2 × 16 0
= 4 × 256 + 10 × 16 + 2 × 1
= (1186)10
(ii) 9E1A
Digits 9 E 1 A
Position 3 2 1 0
Weight 16 3 16 2 161 160
Decimal number = 9 × 163 + E × 162 + 1 × 161 + A × 160
= 9 × 4096 + 14 × 256 + 1 × 16 + 10 × 1
= (40474)10
(iii) 6BD
12
CREATED BY J.SASIREKHA KATPADI
Digits 6 B D
Position 2 1 0
Weight 16 2 161 160
Decimal number = 6 × 162 + B × 161 + D × 160
= 6 × 256 + 11 × 16 + 13 × 1
= (1725)10
(iv) 6C.34
Digits 6 C 3 4
Position 1 0 -1 -2
Weight 161 160 16-1 16-2
Decimal number = 6 × 16^1 + C × 16^0 + 3 × 16^-1 + 4 × 16^-2
= 96 + 12 × 1 + 0.1875 + 0.015625 [as C = 12 in base 16]
= (108.203125)10
27. Write binary equivalent of the following octal numbers. (i) 2306 (ii) 5610 (iii) 742
(iv) 65.203
(i) 2306
OCTAL 2 3 0 6
BINARY 010 011 000 110
Binary Number = (10011000110)2
(ii) 5610
OCTAL 5 6 1 0
BINARY 101 110 001 000
Binary Number = (101110001000)2
(iii) 742
OCTAL 7 4 2
BINARY 111 100 010
Binary Number = (111100010)2
(iv) 65.203
Digits 6 5 2 0 3
Weight 110 010 000 011
Binary Number = (110101.010000011)2
28. Write binary representation of the following hexadecimal numbers. (i) 4026 (ii)
BCA1 (iii) 98E (iv) 132.45
(i) 4026
HEXADECIMAL 4 0 2 6
BINARY 0100 0000 0010 0110
Binary Number = (100000000100110)2
(ii) BCA1
HEXADECIMAL B C A 1
BINARY 1011 1100 1010 0001
Binary Number = (1011110010100001)2
(iii) 98E
13
CREATED BY J.SASIREKHA KATPADI
HEXADECIMAL 9 8 E
BINARY 1001 1000 1110
Binary Number = (100110001110)2
(iv) 132.45
HEXADECIMAL 1 3 2 4 5
BINARY 0001 0011 0 010 0100 0101
Binary Number = (100110010.01000101)2
29. How does computer understand the following text? (hint: 7 bit ASCII code). (i)
HOTS (ii) Main (iii) CaSe
(i) HOTS: 072 078 084 083
H 072
O 078
T 084
S 83
(ii) Main: 077 097 105 110
M 077
a 097
i 105
n 110
(iii) CaSe: 067 097 083 101
C 067
a 097
S 083
e 101
30. The hexadecimal number system uses 16 literals (0–9, A–F). Write down its base
value.
The base value of hexadecimal system is 16.
31. Let X be a number system having B symbols only. Write down the base value of
this number system.
The base value of t number system X will be B. Because base value is the number of bits
the number system contain.
32. What is the advantage of preparing a digital content in Indian language using
UNICODE font?
UNICODE language is universally acceptable. There is no need to install any special
software to recognize unlike Hindi, Marathi. UNICODE provide special value for each
character. Hence, digital content in Indian language is prepared using UNICODE
language.
33. Explore and list the steps required to type in an Indian language using
UNICODE.
Step 1: write the characters, words, sentence in Indian language.
Step 2: Unicode provide unique value for each character which is readable by machine.
Step 3: system converts our Unicode to binary language/ machine language.
14
CREATED BY J.SASIREKHA KATPADI
34. Encode the word ‘COMPUTER’ using ASCII and convert the encode value into
binary values.
WORD ASCII BINARY VALUE
C 067 01000011
O 079 01001111
M 077 01001101
P 080 01010000
U 085 01010101
T 084 01010100
E 069 01000101
R 082 01010010
ASCII:
067 079 077 080 085 084 069 082
BINARY VALUE:
01000011 01001111 01001101 01010000 01010101 01010100 01000101 01010010
35. shows the integer and fractional part of decimal number 237.25 along with
computation of the decimal number using positional values
15
CREATED BY J.SASIREKHA KATPADI
1. What is Algorithm?
Step by step instructions should be given by us to solve the problem called algorithm
2. Selection
Decision making involves selection of one of the alternatives based on outcome of a
condition
3. Iteration
Certain set of steps are repeating finite number of times based on condition
(i) coding
The ordered set of instructions are written in that particular programming language
by following its syntax
(iv) Decomposition
Break down program into small sub problem known as decomposition
(v) syntax
Set of rules to construct a program
5. what is keyword?
1. Keywords are reserved words.
2. Each keyword has a specific meaning to the Python interpreter
7. What is identifier?
In programming languages, identifiers are names used to identify a variable, function, or
other entities in a program.
9. What is comment?
1. Comments are used to add a remark or a note in the source code.
2. Comments are not executed by interpreter.
3. In Python, a comment starts with # (hash sign).
19
CREATED BY J.SASIREKHA KATPADI
List
1. List is a sequence of items separated by commas
2. the items are enclosed in square brackets [ ].
Tuple
1. Tuple is a sequence of items separated by commas
2. items are enclosed in parenthesis ( ).
3. we cannot change the tuple elements.
15. Write about set data type
1. Set is an unordered collection of items separated by commas
20
CREATED BY J.SASIREKHA KATPADI
2. the items are enclosed in curly brackets { }.
3. it cannot have duplicate entries.
21
CREATED BY J.SASIREKHA KATPADI
22
CREATED BY J.SASIREKHA KATPADI
1. The input() function for taking the user input
2. The syntax for input() is: input ([Prompt])
Output()
1. The print() function to output data to the screen.
2. The syntax for print() is: print(value [, ..., sep = ' ', end = '\n'])
26. What is type conversion?
Type conversion:
1. we can change the data type of a variable in Python from one type to another.
2. data type conversion can happen in two ways: either explicitly (forced) or implicitly
27. Differentiate implicit conversion and explicit conversion
Implicit conversion Explicit conversion
Done by the python interpreter Done by programmer
Eg Eg
int a=50 int a=67
float b=9.2 float b=9
c=a/c #a automatically convert as float c=a/int(b)#data type of b converted by user
print(c) print(c)
5. FLOW OF CONTROL
1. what is flow of control?
1. The order of execution of the statements in a program is known as flow of control
2. The flow of control can be implemented using control structures
3. Python supports two types of control structures—selection and repetition.
2. what is indentation?
1. Leading whitespace (spaces and tabs) at the beginning of a statement is called
indentation
2. Python uses indentation for block as well as for nested block structures
3. write about for loop
1. The for statement is used to iterate over a range of values or a sequence.
2. Syntax of the For Loop
for <control-variable> in <sequence/items in range>:
<statements inside body of the loop>
4. Write about range()
1. In function range(), start, stop and step are parameters.
2. Syntax of range() function is:
23
CREATED BY J.SASIREKHA KATPADI
range([start], stop[, step])
3. The start and step parameters are optional.
4. If start value is not specified, by default the list starts from 0.
5. If step is also not specified, by default the value increases by 1 in each iteration.
6. All parameters of range() function must be integers.
7. The step parameter can be a positive or a negative integer excluding zero.
5. write about while loop
1. The while statement executes a block of code repeatedly as long as the control
condition of the loop is true
2. Syntax of while Loop
while test_condition:
body of while
[else:
Statement body]
6. Differentiate break and continue
break continue
terminates the current statement is encountered, the control
loop skips the execution of remaining statements
inside the body of the loop for the current
iteration and jumps to the beginning of the
loop for the next iteration
Syntax: break Syntax: continue
6.FUNCTIONS
1. What is function?
24
CREATED BY J.SASIREKHA KATPADI
Function can be defined as a named group of instructions that accomplish a
specific task when it is invoked.
2. Mention the types of function
1. User defined function
2. Built in function
3. What are the advantages of function?
1. Increases readability
2. easy to understand
3. Reduces code length
4. makes debugging easier
5. Increases reusability
6. avoid repetitions
7. Easily updated a function
8. Easily removed function if it is not need able in a program
3. The items enclosed in "( )" are called parameters and they are
optional. Hence, a function may or may not have parameters. Also, a
function may or may not return a value.
4. Function header always ends with a colon (:).
5. Function name should be unique.
25
CREATED BY J.SASIREKHA KATPADI
8. What is scope of variable?
The part of the program where a variable is accessible can be defined as the
scope of that variable
27
CREATED BY J.SASIREKHA KATPADI
28
CREATED BY J.SASIREKHA KATPADI
29
CREATED BY J.SASIREKHA KATPADI
30
CREATED BY J.SASIREKHA KATPADI
7. Consider the following string mySubject:
mySubject = "Computer Science"
What will be the output of the following string operations :
i. print(mySubject[0:len(mySubject)])
Answer: Computer Science
ii. print(mySubject[-7:-1])
Answer: Scienc
iii. print(mySubject[::2])
Answer: Cmue cec
iv. print(mySubject[len(mySubject)-1])
Answer: e
v. print(2*mySubject)
Answer: Computer ScienceComputer Science
vi. print(mySubject[::-2])
Answer: eniSrtpo
viii. print(mySubject.swapcase())
Answer: cOMPUTER sCIENCE
ix. print(mySubject.startswith(‘Comp’))
Answer: True
x. print(mySubject.isalpha())
Answer: False
ii. print(myAddress.upper())
Answer: WZ-1,NEW GANGA NAGAR,NEW DELHI
31
CREATED BY J.SASIREKHA KATPADI
iii. print(myAddress.count(‘New’))
Answer: 2
iv. print(myAddress.find(‘New’))
Answer: 5
v. print(myAddress.rfind(‘New’))
Answer: 21
vi. print(myAddress.split(‘,’))
Answer: [‘WZ-1’, ‘New Ganga Nagar’, ‘New Delhi’]
viii. print(myAddress.replace(‘New’,’Old’))
Answer: WZ-1,Old Ganga Nagar,Old Delhi
ix. print(myAddress.partition(‘,’))
Answer: (‘WZ-1’, ‘,’, ‘New Ganga Nagar,New Delhi’)
x. print(myAddress.index(‘Agra’))
Answer: ValueError: substring ‘Agra’ not found
9. Write a program to input line(s) of text from the user until enter is
pressed. Count the total number of characters in the text (including
white spaces),total number of alphabets, total number of digits, total
number of special symbols and total number of words in the given
text. (Assume that each word is separated by one space).
def counter(string):
alpha = 0
space = 0
digit = 0
symbol = 0
noofchars = len(string)
for ch in string:
if ch.isalpha():
alpha = alpha + 1
elif ch.isdigit():
digit = digit + 1
32
CREATED BY J.SASIREKHA KATPADI
elif ch.isspace():
space = space + 1
else:
symbol = symbol + 1
print("Number of characters : ", noofchars)
print("Number of alphabets : ", alpha)
print("Number of digits : ", digit)
print("Number of symbols : ", symbol)
print("Number of spaces : ", space)
print("Number of words : ", space + 1)
sentence = input("Enter a sentence : ")
counter(sentence)
Output :
Enter a sentence : hello 259 & how ^ you @; ,
Number of characters : 26
Number of alphabets : 11
Number of digits : 3
Number of symbols : 5
Number of spaces : 7
Number of words : 8
10. Write a user defined function to convert a string with more than
one word into title case string where string is passed as parameter.
(Title case means that the first letter of each word is capitalised)
def titlecase(string):
return string.title()
sentence = input("Enter a sentence : ")
newstr = titlecase(sentence)
print(newstr)
Output:
Enter a sentence : my cs tutorial dot in
My Cs Tutorial Dot In
12. Input a string having some digits. Write a function to return the
sum of digits present in this string.
def sumofdigits(string):
sum = 0
for ch in string:
if ch.isdigit():
sum = sum + int(ch)
return sum
string = "my 23 cs 85 tutorial25"
print("Sum of digits ", sumofdigits(string))
Output:
Sum of digits 25
def replacespace2(sentence):
return sentence.replace(' ','-')
sentence = input("Enter a sentence : ")
newsentence = replacespace2(sentence)
print(newsentence)
Output
Enter a sentence : my cs tutorial
my-cs-tutorial
34
CREATED BY J.SASIREKHA KATPADI
8. LIST
1. what is list?
The data type list is an ordered sequence which is mutable and made up of
one or more elements
37
CREATED BY J.SASIREKHA KATPADI
1. Append an element
2. Insert an element at the desired position
3. Append a list to the given list
4. Modify an existing element
5. Delete an existing element by its position
6. Delete an existing element by its value
7. Sort the list in ascending order
8. Sort the list in descending order
9. Display the list
10. Exit
ENTER YOUR CHOICE (1-10): 8
The list has been sorted in reverse order
The list 'myList' has the following elements [38, 22, 16, 13, 4]
LISTOPERATIONS
1. Append an element
2. Insert an element at the desired position
3. Append a list to the given list
4. Modify an existing element
5. Delete an existing element by its position
6. Delete an existing element by its value
7. Sort the list in ascending order
8. Sort the list in descending order
9. Display the list
10. Exit
ENTER YOUR CHOICE (1-10): 5
Enter the position of the element to be deleted: 2
The element 16 has been deleted
The list 'myList' has the following elements [38, 22, 13, 4]
LISTOPERATIONS
1. Append an element
2. Insert an element at the desired position
3. Append a list to the given list
4. Modify an existing element
5. Delete an existing element by its position
6. Delete an existing element by its value
7. Sort the list in ascending order
8. Sort the list in descending order
9. Display the list
10. Exit
5. A program to calculate average marks of n students using a function
where n is entered by the user.
Answer:
def computeAverage(list1,n):
total = 0
for marks in list1:
38
CREATED BY J.SASIREKHA KATPADI
total = total + marks
average = total / n
return average
list1 = []
print("How many students marks you want to enter: ")
n = int(input())
for i in range(0,n):
print("Enter marks of student",(i+1),":")
marks = int(input())
list1.append(marks)
average = computeAverage(list1,n)
print("Average marks of",n,"students is:",average)
Output:
How many students marks you want to enter:
5
Enter marks of student 1:
45
Enter marks of student 2:
89
Enter marks of student 3:
79
Enter marks of student 4:
76
Enter marks of student 5:
55
Average marks of 5 students is: 68.8
7. Consider a list:
list1 = [6, 7, 8, 9]
What is the difference between the following operations on list1:
a. list1 * 2
b. list1 *= 2
c. list1 = list1 * 2
Answer: (a)
In list1 * 2, * operator work as replication operator. Which replicate the
list1 two times. list1 * 2 will generate a list [6, 7, 8, 9, 6, 7, 8, 9].But
list1 is not changed.
(b) list1 *=2, in this *=is a replication and assignment operator. It means it
replicate the list1 two times and update list1.New list1 is [6,7,8,9,6 7,8,9]
39
CREATED BY J.SASIREKHA KATPADI
(c) list1 = list1 * 2, this statement will create a new list1 containing the two
times replicated value of list1.
>>> list1 = [6, 7, 8, 9]
>>> list1 * 2
[6, 7, 8, 9, 6, 7, 8, 9]
8. What will be the output of the following code segment:
a. myList = [1,2,3,4,5,6,7,8,9,10]
del myList[3:]
print(myList)
Answer: [1, 2, 3]
c. myList = [1,2,3,4,5,6,7,8,9,10]
del myList[ : : 2]
print(myList)
Answer: [2, 4, 6, 8, 10]
10. Consider the following list myList. What will be the elements of myList
after the following two operations:
myList = [10,20,30,40]
i. myList.append([50,60])
ii. myList.extend([80,90])
Answer:
(i) [10,20,30,40,[50,60]]
(ii) [10,20,30,40,[50,60], 80,90]
40
CREATED BY J.SASIREKHA KATPADI
11. Find the output
(i)
list1 = [12,32,65,26,80,10]
list1.sort()
print(list1)
Answer: [10, 12, 26, 32, 65, 80]
Answer:
[10, 12, 26, 32, 65, 80]
[12, 32, 65, 26, 80, 10]
Answer:
[10, 8, 6, 4, 2]
[1,2,3,4,5,6,7,8,9,10]
Answer:
5
12. The record of a student (Name, Roll No., Marks in five subjects and
percentage of marks) is stored in the following list:
stRecord = [‘Raman’,’A-36′,[56,98,99,72,69], 78.8].Write Python statements
to retrieve the following information from the list stRecord.
a) Percentage of the student
b) Marks in the fifth subject
c) Maximum marks of the student
d) Roll no. of the student
e) Change the name of the student from ‘Raman’ to ‘Raghav’
Answer:
(a) print(” Percentage of the student : “, stRecord[3])
41
CREATED BY J.SASIREKHA KATPADI
b) print(“Marks in the fifth subject : “, stRecord[2][4])
c) print(“Maximum marks of the student :”, max(stRecord[2]))
d) print(“Roll no. of the student :”, stRecord[1])
e) stRecord[0] = ‘Raghav’
16. Write a function to return the 2nd largest number from a list of
number
max1 = number[0]
max2 = number[0]
for n in number:
if max1 < n :
max2 = max1
max1 = n
elif max2 < n:
max2 = n
retrun max2
number = eval(input("Enter List : ")) # like this [5,10,65,2,15,39,24]
large2 = secondLargest(number)
print("Largest 2 : ", large2)
16. Write a program to read a list of n integers and find their median.
Note: The median value of a list of values is the middle one when they
are arranged in order. If there are two middle values then take their
average. Hint: You can use an built-in function to sort the list.
lst = eval(input("Enter list : "))
lst.sort()
length = len(lst)
mid = length // 2
if length % 2 != 0:
median = lst[mid]
else:
mid1, mid2 = mid-1, mid
median = (lst[mid1] + lst[mid2]) // 2
print("The Median Value is ", median)
17. Write a program to read a list of elements. Modify this list so that it
does not contain any duplicate elements, i.e., all elements occurring
multiple times in the list should appear only once.
lst = eval(input("Enter List : "))
newlist = []
for num in lst:
if num not in newlist:
newlist.append(num)
lst = newlist
print("List without duplicate element : ", lst)
20. Read a list of n elements. Pass this list to a function which reverses
this list in-place without creating a new list.
def reverseList(list1):
length = len(list1)
k = length-1
for j in range(length):
list1[j],list1[k] = list1[k], list1[j]
k = k-1
if j == k:
break
numbers = eval(input("Enter a list : "))
[2,4,6,7]
2. Repetition
Python allows us to replicate a list using repetition
operator depicted by symbol *.
45
CREATED BY J.SASIREKHA KATPADI
>>> list1 = ['Hello']
3.Membership
Like strings, the membership operators in checks if
the element is present in the list and returns True, else returns False.
>>> list1 = ['Red','Green','Blue']
>>> 'Green' in list1
True
>>> 'Cyan' in list1
False
The not in operator returns True if the element is not present in the list, else
it returns False.
>>> list1 = ['Red','Green','Blue']
>>> 'Cyan' not in list1
True
>>> 'Green' not in list1
False
4.Slicing
Like strings, the slicing operation can also be applied to lists.
>>> list1 =['Red','Green','Blue','Cyan', 'Magenta','Yellow','Black']
>>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']
46
CREATED BY J.SASIREKHA KATPADI
['Red','Blue','Magenta']
#negative indexes
1. what is Tuple?
1. A tuple is an ordered sequence of elements of different data types, such
as integer, float, string, list or even a tuple.
2. Elements of a tuple are enclosed in parenthesis and are separated by
commas.
47
CREATED BY J.SASIREKHA KATPADI
#concatenates two tuples
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
>>> tuple3 = ('Red','Green','Blue')
>>> tuple4 = ('Cyan', 'Magenta', 'Yellow' ,'Black')
Repetition
Repetition operation is depicted by the symbol *. It is used to repeat elements
of a tuple. We can repeat the tuple elements. The repetition operator requires
the first operand to be a tuple and the second operand to be an integer only.
>>> tuple1 = ('Hello','World')
>>> tuple1 * 3
('Hello', 'World', 'Hello', 'World', 'Hello', 'World')
Membership
The in operator checks if the element is present in the tuple and returns
True, else it returns False.
>>> tuple1 = ('Red','Green','Blue')
>>> 'Green' in tuple1
48
CREATED BY J.SASIREKHA KATPADI
True
The not in operator returns True if the element is not present in the tuple,
else it returns False.
>>> tuple1 = ('Red','Green','Blue')
>>> 'Green' not in tuple1
False
Slicing
Like string and list, slicing can be applied to tuples also.
#tuple1 is a tuple
>>> tuple1 = (10,20,30,40,50,60,70,80)
#step size 2
>>> tuple1[0:len(tuple1):2]
(10, 30, 50, 70)
#negative indexing
>>> tuple1[-6:-4]
(30, 40)
49
CREATED BY J.SASIREKHA KATPADI
8. what is dictionary?
1. The data type dictionary fall under mapping.
2. It is a mapping between a set of keys and a set of values.
3. The key-value pair is called an item.
4. A key is separated from its value by a colon(:) and consecutive items are
separated by commas.
52
CREATED BY J.SASIREKHA KATPADI
11. Create a dictionary ‘ODD’ of odd numbers between 1 and 10, where
the key is the decimal number and the value is the corresponding
number in words. Perform the following operations on this dictionary:
(a) Display the keys
(b) Display the values
53
CREATED BY J.SASIREKHA KATPADI
(c) Display the items
(d) Find the length of the dictionary
(e) Check if 7 is present or not
(f) Check if 2 is present or not
(g) Retrieve the value corresponding to the key 9
(h) Delete the item from the dictionary corresponding to the key 9
(h) Delete the item from the dictionary corresponding to the key 9
>>> del ODD[9]
54
CREATED BY J.SASIREKHA KATPADI
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven'}
Output:
Enter the number of employees to be stored: 5
Enter the name of the Employee: 'Tarun'
Enter the salary: 12000
Enter the name of the Employee: 'Amina'
Enter the salary: 34000
Enter the name of the Employee: 'Joseph'
Enter the salary: 24000
Enter the name of the Employee: 'Rahul'
Enter the salary: 30000
Enter the name of the Employee: 'Zoya'
Enter the salary: 25000
EMPLOYEE_NAME SALARY
'Tarun' 12000
'Amina' 34000
'Joseph' 24000
'Rahul' 30000
'Zoya' 25000
13. Write a program to count the number of times a character appears
in a given string.
st = input("Enter a string: ")
dic = {} #creates an empty dictionary
for ch in st:
if ch in dic: #if next character is already in the dictionary
dic[ch] += 1
55
CREATED BY J.SASIREKHA KATPADI
else:
dic[ch] = 1
for key in dic:
print(key,':',dic[key])
Output:
Enter a string: HelloWorld
H:1
e:1
l:3
o:2
W:1
r:1
d:1
14. Write a function to convert a number entered by the user into its
corresponding number in words. For example, if the input is 876 then
the output should be ‘Eight Seven Six’.
def convert(num):
numberNames={0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',5:'Five',6:'Six',7
:'Seven',8:'Eight',9:'Nine'}
result = ''
for ch in num:
key = int(ch)
value = numberNames[key]
result = result + ' ' + value
return result
num = input("Enter any number: ") #number is stored as string
result = convert(num)
print("The number is:",num)
print("The numberName is:",result)
Output:
Enter any number: 6512
The number is: 6512
The numberName is: Six Five One Two
15. Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:
i. print(tuple1.index(45))
ii. print(tuple1.count(45))
iii. print(tuple1 + tuple2)
iv. print(len(tuple2))
56
CREATED BY J.SASIREKHA KATPADI
v. print(max(tuple1))
vi print(min(tuple1))
vii. print(sum(tuple2))
viii. p r i n t ( s o r t e d ( t u p l e 1 ) )
print(tuple1)
ii. print(tuple1.count(45))
3
iv. print(len(tuple2))
2
v. print(max(tuple1))
67
vi print(min(tuple1))
1
vii. print(sum(tuple2))
300
viii. print(sorted(tuple1))
print(tuple1)
[1, 9, 23, 45, 45, 45, 55, 67]
(23, 1, 45, 67, 45, 9, 55, 45)
ii. print(stateCapital.keys())
dict_keys([‘Assam’, ‘Bihar’, ‘Maharashtra’, ‘Rajasthan’])
57
CREATED BY J.SASIREKHA KATPADI
iii. print(stateCapital.values())
dict_values([‘Guwahati’, ‘Patna’, ‘Mumbai’, ‘Jaipur’])
iv. print(stateCapital.items())
dict_items([(‘Assam’, ‘Guwahati’), (‘Bihar’, ‘Patna’), (‘Maharashtra’,‘Mumbai’),
(‘Rajasthan’, ‘Jaipur’)])
v. print(len(stateCapital))
4
vii. print(stateCapital.get(“Assam”))
Guwahati
17. With the help of an example show how can you return more than
one value from a function.
A function can return multiple values in the form of tuples.
Eg:
def square(n1, n2, n3):
sq = n1**2, n2**2, n3**2
rerurn sq
20. Prove with the help of an example that the variable is rebuilt in case
of immutable data types.
A tuple once created cannot be changed Even if you try to make changes in
the tuple and give it the same name, Python Internally will create a
new tuple and store it at a different memory location.
For example
>>> tup1 = (1,2,'mycstutorial.in')
>>> id(tup1)
61944840
>>> print(tup1)
(1, 2, 'mycstutorial.in')
>>> tup1 = tup1 + ('ncert solution','xi','computer','science')
>>> tup1
(1, 2, 'mycstutorial.in', 'ncert solution', 'xi','computer', 'science')
>>> id(tup1)
59301336
>>> print(tup1)
(1, 2, 'mycstutorial.in', 'ncert solution', 'xi','computer', 'science')
>>>
Check the id printed in two different statements. As you can observe in both
cases variable name is the same but it is printed different id’s, it means that
tuple is immutable data type, and if you try to change it, it will not make
the change in-place, it creates a new variable.
31. To print the even numbers in a given sequence using for loop
N=int(input(“enter number”))
for i in range(1,N+1):
if i%2==0:
print(i)
32. Write a program to print the following pattern
1
12
123
1234
12345
rows=int(input("enter number of rows"))
for i in range(rows+1):
for j in range(1,i+1):
print(j,end=" ")
print()
for i in range(num+1,6):
for j in range(i+1):
print(chr(val),end=" ")
val=val+1
print()
43. To accept Students marks from users and calculate total, average
a= int(input("Enter the marks of first subject: "))
b = int(input("Enter the marks of second subject: "))
c = int(input("Enter the marks of third subject: "))
total = a+b+c
avg = total/3
print("Total marks: ",total)
print("Average marks: ",avg)
65
CREATED BY J.SASIREKHA KATPADI
44. Write a python program to accept numbers from user and calculated
mean
numbers = []
for i in range(5):
numbers.append(int(input("Enter a number: ")))
mean=sum(numbers)/len(numbers)
print(mean)
46. Write a program using a user defined function that displays sum of
first n natural numbers, where n is passed as an argument
def sumSquares(n):
sum = 0
for i in range(1,n+1):
sum = sum + i
print("The sum of first",n,"natural numbers is: ",sum)
num = int(input("Enter the value for n: "))
sumSquares(num)
46. Write a program using a user defined function that displays sum of
first n natural numbers, where n is passed as an argument
def sumSquares(n):
sum = 0
for i in range(1,n+1):
sum = sum + i
print("The sum of first",n,"natural numbers is: ",sum)
num = int(input("Enter the value for n: "))
sumSquares(num)
47. Write a program to read email IDs of n number of students and store
them in a tuple. Create two new tuples, one to store only the usernames
from the email IDs and second to store domain names from the email
IDs. Print all three tuples at the end of the program. [Hint: You may use
the function split()]
emailids = []
66
CREATED BY J.SASIREKHA KATPADI
n = int(input("Enter How many students email id's you want to add : "))
for i in range(1, n+1):
email = input("Enter email id of student"+str(i)+" : ")
emailids.append(email)
emailtuple = tuple(emailids)
idlst = []
domain =[]
for email in emailtuple:
lst = email.split('@')
idlst.append(lst[0])
domain.append(lst[1])
unametuple = tuple(idlst)
domaintuple = tuple(domain)
print("User name ==> ")
print(unametuple)
print("Domain name ==> ")
print(domaintuple)
Output:
Enter How many students email id’s you want to add : 2
Enter email id of student1 : abc@gmail.com
Enter email id of student2 : xyz@yahoo.com
User name ==>
(‘abc’, ‘xyz’)
Domain name ==>
(‘gmail.com’, ‘yahoo.com’)
67
CREATED BY J.SASIREKHA KATPADI
name = input("Enter Name : ")
namelst.append(name)
nametup = tuple(namelst)
name = input("Enter name to search : ")
if search_name(nametup, name):
print("Found")
else:
print("Not Found")
string = ‘w3resource’
dict = {}
index = 0
for char in string:
if char not in dict:
dict[char] = index
index = index + 1
print("Dictionary :", dict)
Output is :
Dictionary : {‘w’: 0, ‘3’: 1, ‘r’: 2, ‘e’: 3, ‘s’: 4, ‘o’: 5, ‘u’: 6, ‘c’: 8}
51. Write a program to input your friends’ names and their Phone
Numbers
and store them in the dictionary as the key-value pair. Perform the
a) Display the name and phone number of all your friends
b) Add a new key-value pair in this dictionary and display the modified
dictionary
c) Delete a particular friend from the dictionary
d) Modify the phone number of an existing friend
e) Check if a friend is present in the dictionary or not
f) Display the dictionary in sorted order of names
phonedict = {}
68
CREATED BY J.SASIREKHA KATPADI
n = int(input("How many friends details want to add :"))
for t in range(n):
name = input("Enter Friends Name : ")
phone = input("Enter Phone Number : ")
if name not in phonedict:
phonedict[name] = phone
print("Friends Dictionary is : ", phonedict)
while True:
print("1. Display All Friends")
print("2. Add Friend ")
print("3. Delete a friend ")
print("4. Modify phone number :")
print("5. Search friend")
print("6. Sorted on Names")
print("7. Exit")
choice = int(input("Enter your choice (1-7)"))
if choice == 1:
print("Name\t Phone Number")
for key in phonedict:
print(key, phonedict[key])
elif choice == 2:
name = input("Enter Friends Name : ")
phone = input("Enter Phone Number : ")
if name not in phonedict:
phonedict[name] = phone
else:
print("Name already exists")
elif choice == 3:
name = input("Enter Name to delete : ")
if name in phonedict:
del phonedict[name]
else:
print("No such name exist")
elif choice == 4:
name = input("Enter Name to delete : ")
if name in phonedict:
phone = input("Enter new phone number : ")
phonedict[name] = phone
else:
print("No such name exist")
elif choice == 5:
name = input("Enter Name to Search : ")
if name in phonedict:
69
CREATED BY J.SASIREKHA KATPADI
print(name, "\t", phonedict[name])
else:
print("Friend does not exists")
elif choice == 6:
keys = sorted(phonedict)
print("Sorted Phone Directory is ")
for k in keys:
print(k, "\t", phonedict[k])
elif choice == 7:
break
else:
print("invalid choice, please input valid")
syntax
1) if condition:
statement(s)
2) if condition:
statement(s)
else:
statement(s)
3) if condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
6) while test_condition:
body of while
70
CREATED BY J.SASIREKHA KATPADI
7) def <function_name>(parameter1,parameter2,….):
statement
return[(value)]
8) abs(x)
9) divmod(x,y)
12) pow(x,y[,z])
13) sum(x[,num])
14) len(x)
15) math.ceil(x)
16) math.floor(x)
17) math.fabs(x)
18) math.factorial(x)
19) math.fmod(x,y)
20) math.gcd(x,y)
21) math.pow(x,y)
22) math.sqrt(x)
23) math.sin(x)
24) random.random()
25) random.randint(x,y)
26) random.randrange(y)
27) random.randrange(x,y)
71
CREATED BY J.SASIREKHA KATPADI
28) statistics.mean(x)
29) statistics.median(x)
30) statistics.mode(x)
32) len(str1)
33) str1.title()
34) str1.lower()
35) str1.upper()
37) find(str,start,end)
39) str1.endswith('char')
40) str1.startswith('char')
41) str1.isalnum()
42) str1.islower()
43) str1.isupper()
44) str1.isspace()
45) str1.istitle()
46) str1.lstrip()
47) str1.rstrip()
48) str1.strip()
49) replace(oldstr,newstr)
72
CREATED BY J.SASIREKHA KATPADI
50) str2.join(str1)
51) str1.partition('char')
52) str1.split('char')
53) len(list1)
56) list1.extend(list2)
57) list1.insert(position,element)
58) list1.count(element)
59) list1.index(element)
60) list1.remove(element)
61) list1.pop()
62) list1.reverse()
63) list1.sort()
64) sorted(list1)
65) min(list1)
66) max(list1)
67) sum(list1)
70) list()
73
CREATED BY J.SASIREKHA KATPADI
newList = list(oldList)
71) copy()
newList = copy.copy(oldList)
87) dict()
dict2=dict(dict1)
88) keys()
dict1.keys()
89) values()
dict1.values()
90) items()
dict1.items()
91) get()
dict1.get(key)
92) update()
dict1.update(dict2)
93) del
del dict1
(or)
del dict1[key]
94) clear()
dict1.clear()
75
CREATED BY J.SASIREKHA KATPADI
dict1.values()
76