0% found this document useful (0 votes)
34 views

Class 11 Cs Study Material

Uploaded by

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

Class 11 Cs Study Material

Uploaded by

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

CREATED BY J.

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.

2. Explain volatile and non-volatile memory.


The memory is which data is lost when power is removed is called volatile memory. The
memory is which data is not lost when power is removed is called non-volatile memory.

3. What is data? What is the output of data processing system?


Data is derived from a word ‘datum’ i.e., a fact. Data is a collection of raw facts and
figures. Data processing system is a computer-based system which converts data into
information.

4. What is the difference between data and information?


Data: Data means facts and figures. Data is unprocessed information. For example:
Siddharth, 40400195, M.
Information: Information means what we get after processing data i.e., processed data. In
other words, information is processed data.
For example:
NAME ROLL NUMBER GENDER
Siddharth 40400195 M

5. Expand the following terms:

1.CPU 2. ALU 3. VLSI 4. MSI 5. LSI 6. SSI 7. IC 8. IPO 9.HLL 10. MB.

1. CPU - Central Processing Unit


2. ALU - Arithmetic Logic Unit
3. VLSI - Very Large-Scale Integration
4. MSI - Medium Scale Integration
5. LSI - Large Scale Integration
6. SSI - Small Scale Integration
7. IC - Integrated Circuits
8. IPO - Input Process Output
9. HLL - High Level Language
10. MB - Mega Byte

6. Write about Memory of Computer


✓ Memory refers to the place where data is stored temporarily or permanently.
✓ Computer Memory is basically of 2 types
1. Primary Memory
1
CREATED BY J.SASIREKHA KATPADI
Primary or main memory stores information (data and instruction)
Types of Primary Memory

❖Random Access Memory (RAM)


● It is the working memory, right from the booting of computer till the computer is
shutdown, this memory is in use to store all the operation done by the computer
● It is used for primary storage in computers to hold active information of data and
instructions.
● It holds data temporarily i.e. Volatile Memory
● Data is lost if Power Off

❖Read Only Memory (ROM)


● ROM (Read Only Memory) is used to store the instructions provided by the
manufacturer, which holds the instructions to check basic hardware inter connecter and
to load operating system from appropriate storage device
● It is also known as FIRMWARE
● Its data is stored permanently on it so it is non-volatile device.
2. Secondary Memory
Stores the data permanently for future retrieval. It is non-volatile memory E.g.-CD, DVD,
Pen drive
3. Cache memory
To speed up the operations of the CPU, a very high speed is placed between the CPU and
the Primary memory is known as cache memory
7. Mention the units of memory.
Units of Memory
➢ BIT = Basic units of memory
➢ 4 BITS = 1 NIBBLE
➢ 8 BITS = 1 BYTE
➢ 1024 BYTES = 1 KILO BYTE(KB)
➢ 1024 KB = 1 MEGA BYTE(MB)
➢ 1024 MB = 1 GIGA BYTE(GB)
➢ 1024 GB = 1 TERA BYTE(TB)
➢ 1024 TB = 1 PETA BYTE(PB)
The elementary unit of memory is a bit (binary digit) i.e., Zero (0) & One (1)
8. Tabulate Measurement units for digital data
KB - 210 bytes PB - 250 bytes
MB - 220 bytes EB - 260 bytes
GB - 230 bytes ZB - 270 bytes
TB - 240 bytes YB - 280 bytes
9. What is BUS?
2
CREATED BY J.SASIREKHA KATPADI
▪ Data are transferred between different components of a computer system using
physical wires called BUS
▪ BUS is of 3 types
1. Data bus
2. Address bus
3. Control bus
9. What is microprocessor?
A processor (CPU) which is implemented on a single microchip is called microprocessor
10. Generation of Microprocessor.

11. Components of computer system

12. Mention the microprocessor specification.

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

17. Why we need software?


Software acts as an interface between users and the hardware

18. What is Application software?


The software used to do particular task termed as application software
Eg – Whatsapp

19. Mention the classification of Application software


i. General purpose software – developed for generic Application eg-GIMP

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

20. what is system software?


The software that provides the basic functionality to a computer
EG – operating system, system utilities, device drivers

21. Write about programming tools


The software used to simplify the program development called as Integrated Development
Environment (IDE) consisting text editor, building tools and debugger

22. Differentiate Free and open-source software


Open-source software Proprietary software
No cost to download Have to pay to download
We can get software along with source We can get software only
code
We can modify the source code We cannot modify the source code
EG - Apache EG - windows

23. What is OS user interface? Mention its types


The user interface (UI) of an operating system (OS) allows users to interact with the
system and its applications.
Types
1. Graphical User Interface
2. Character User Interface
3. Voice Based Interface
4. Touch Based Interface
5. Gesture based Interface

24. Mention the functions of operating system


1) Process Management
2) Memory Management
3) File Management
4) Device Management

25. Difference between RAM and ROM

26. Difference between primary memory and secondary memory

5
CREATED BY J.SASIREKHA KATPADI

27. Difference between microprocessor and micro controller

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

29. What is the primary role of system bus?


System bus is used to transfer data, addresses and control signals between the
components of computer system

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.

CHAPTER 2 ENCODING SCHEMES AND NUMBER SYSTEM


1. Mention the different numbering system
6
CREATED BY J.SASIREKHA KATPADI
1) Decimal
2) Binary
3) Octal
4) Hexadecimal

2. What is radix or base?


The count of number of digits in a number system is called radix or base

3. Write about cryptography


Encryption and decryption done in cryptography technology.

4. What is Encryption, decryption?


Encryption
The process of converting normal text to cipher text is called encryption.
Decryption
The process of converting cipher text to normal text is called decryption.

5. Mention different coding scheme


ASCII, ISCII, UNICODE

6. Mention the ASCII code for characters

7. Write the ASCII and BINARY value for DATA

8. Convert 6510 into Binary

7
CREATED BY J.SASIREKHA KATPADI

9. Convert (122)10 to octal number

10. Convert (122)10 to hexadecimal number.

11. Convert (1101)2 into decimal number.

12. Convert (257)8 into decimal number

13. Convert (3A5)16 into decimal number.


8
CREATED BY J.SASIREKHA KATPADI

14. Convert (10101100)2 to octal number.


Make group of 3-bits of the given
binary number (right to left) 010 101 100
Write octal number for each 3-bit group 2 5 4
Therefore, (10101100)2 = (254)8

15. Convert (705)8 to binary number.


Octal digits 7 0 5
Write 3-bits binary
value for each digit 111 000 101
Therefore, (705)8 = (111000101)2

16. Convert (0110101100)2 to hexadecimal number.


Make group of 4-bits of the given
binary number (right to left) 0001 1010 1100
Write hexadecimal symbol
for each group 1 A C
Therefore, (0110101100)2 = (1AC)16

17. Convert (23D)16 to binary number.


Hexadecimal digits 2 3 D
Write 4-bit binary value
for each digit 0010 0011 1101
Therefore, (23D)16 = (001000111101)2

18. Convert (0.675)10 to binary.


Integer part
0.675 × 2 = 1.350 ->1
0.350 × 2 = 0.700 ->0
0.700 × 2 = 1.400 ->1
0.400 × 2 = 0.800 ->0
0.800 × 2 = 1.600 ->1
0.600 × 2 = 1.200 ->1
0.200 × 2 = 0.400 ->0
Therefore, (0.675)10= (0.1010110)2

19. Convert (0.675)10 to octal.


Integer part
0.675 × 8 = 5.400-> 5
9
CREATED BY J.SASIREKHA KATPADI
0.400 × 8 = 3.200->3
0.200 × 8 = 1.600-> 1
0.600 × 8 = 4.800->4
0.800 × 8 = 6.400->6
Therefore, (0.675)10= (0.53146)8

20. Convert (100101.101)2 into decimal.

21.

22. what is the base value for binary, octal, hexadecimal?


Binary – 2, octal – 8, Hexadecimal – 16

23. Give full form of ASCII and ISCII.


ASCII: - American Standard Code for Information Interchange.
ISCII: - Indian Standard Code for Information Interchange

24. Try the following conversions.


(i) (514) = (?)10 (ii) (220) = (?)2 (iii) (76F) = (?)10
(iv) (4D9) = (?)10 (v) (11001010) = (?)10 (vi) (1010111) = (?)10
(i) (514)8 = (?)10
Digits 5 1 4
Position 2 1 0
Weight 82 81 80
Decimal number = 5×82 + 1×81 + 4×80
= 5×64 + 1×8 + 4× 1
= 320 + 8 + 4
= (332)10

(ii) (220)8 = (?)2


Octal Digits 2 2 0
Binary value 010 010 000
Therefore, Binary number = (010010000)2
10
CREATED BY J.SASIREKHA KATPADI
(iii) (76F)16 = (?)10
Digits 7 6 F(15)
Position 2 1 0
Weight 162 161 160
Decimal number = 7×162 + 6×161 + F×160
= 7×256 + 6×16 + F× 1
= 1792 + 96 + 15
= (1903)10

(iv) (4D9)16 = (?)10


Digits 4 D 9
Position 2 1 0
Weight 162 161 160
Decimal number = 4×162 + 13×161 + 9×160
= 4×256 + 13×16 + 9× 1
= 1024 + 208 + 9
= (1241)10

(v) (11001010)2 = (?)10


Digits 1 1 0 0 1 0 1 0
Position 7 6 5 4 3 2 1 0
Weight 27 26 25 24 23 22 21 20
Decimal number = 1×27+ 1×26+0×25 +0×24 +1×23 +0×22 +1×21 +0×20
= 128+64 +8 + 2
= (202)10

(vi) (1010111)2 = (?)10


Digits 1 0 1 0 1 1 1
Position 6 5 4 3 2 1 0
Weight 2 6 2 5 2 4 23 22 21 20
Decimal number = 1×26+ 0×25+1×24 +0×23 +1×22 +1×21 +1×20
= 64 +16 + 4+ 2 +1= (87)10

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

36. BINARY equivalent for DECIMAL number (0-9) system

15
CREATED BY J.SASIREKHA KATPADI

37. BINARY equivalent for OCTAL number (0-7) system

38. Decimal and binary equivalent of hexadecimal numbers 0–9, A–F

3. INTRODUCTION TO PROBLEM SOLVING


16
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. Steps for problem solving


1. Analyzing the problem
2. Developing the algorithm
3. coding

3. Mention the characteristics of good Algorithm


1. Precision - well defined
2. Uniqueness - steps are uniquely defined
3. Finiteness - contains finite number of steps
4. Input - Receives some input
5. Output - produce some output

4. Tabulate flow chart symbols, functions, descriptions

5. Define pseudo code


1. Pseudo code means ‘not real code’
2. It is non formal language consist of keywords to write Algorithm

6. Mention the Flow of control of program.


1. Sequential
17
CREATED BY J.SASIREKHA KATPADI
An Algorithm where all the steps are executed one after the other

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

7. Define the following


(i) coding (ii) source code (iii) Machine code (iv) Decomposition (v) syntax

(i) coding
The ordered set of instructions are written in that particular programming language
by following its syntax

(ii) source code


A program written in high level language is called source code

(iii) Machine code


High level language translates into object code using interpreter or compiler

(iv) Decomposition
Break down program into small sub problem known as decomposition

(v) syntax
Set of rules to construct a program

4. GETTING STARTED WITH PYTHON

1. Mention the features of python


1. Free and open-source language
2. Simple structure
3. Clearly defined syntax
4. Portable and platform independent
5. Has rich library
6. Helpful in web development
7. Easy to understand
8. Uses indentation for blocks
9. Interpreted language
10. case sensitive

2. Methods to execute a python program


There are two ways to
1. Interactive mode
2. script mode
3. write about Interactive mode
1. We can type python program statement on the >>> prompt directly
2. We can get instant result immediately
3. But we cannot save the coding for later use
18
CREATED BY J.SASIREKHA KATPADI

4. Write about script mode


1. We can type the python program in a file
2. Python scripts are saved the file with extension .py by default
3. We can execute it by Run -> Run module or press F5

5. what is keyword?
1. Keywords are reserved words.
2. Each keyword has a specific meaning to the Python interpreter

6. Mention the python keywords

7. What is identifier?
In programming languages, identifiers are names used to identify a variable, function, or
other entities in a program.

8. What are the rules for define identifier?


1. The name should begin with an uppercase or a lowercase alphabet or an
underscore sign(_).
2. An identifier cannot start with a digit.
3. It can be of any length.
4. It should not be a keyword or reserved word
5. We cannot use special symbols like !, @, #, $, %, etc., in identifiers.

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).

10. Mention the types of comments.


1. Single line comment (start with #)
2. Multi line comment (start and end with triple single quotes ‘’’)

11. Mention python data types.

19
CREATED BY J.SASIREKHA KATPADI

12. Write about Number data type


1. Number data type stores numerical values only.
2. It is further classified into three different types: int, float and complex

13. write about Boolean data type.


1. Boolean data type (bool) is a subtype of integer.
2. It is a unique data type, consisting of two constants, True and False.
3. Boolean True value is non-zero, non-null and non-empty.
4. Boolean False is the value zero

14. what are sequence data type?


sequence data types available in Python are Strings, Lists and Tuples
string
1. String is a group of characters.
2. These characters may be alphabets, digits or special characters including spaces.
3. String values are enclosed either in single quotation marks (e.g., ‘Hello’) or in double
quotation marks (e.g., “Hello”).

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.

16. Write about None data type


1. None is a special data type with a single value.
2. It is used to signify the absence of value in a situation.
3. It is neither same as False nor 0 (zero).

17. what is mapping data type?


1. Mapping is an unordered data type in Python.
2. mapping data type in Python called dictionary

18. write about dictionary data type


1. Dictionary in Python holds data items in key-value pairs.
2. Items in a dictionary are enclosed in curly brackets { }.
3. Every key is separated from its value using a colon (:) sign.
4. The key: value pairs of a dictionary can be accessed using the key.

19. Differentiate mutable, immutable data type


MUTABLE DATA TYPE IMMUTABLE DATA TYPE
Variables whose values can be changed Variables whose values cannot be changed
after they are created and assigned are after they are created and assigned are
called mutable called immutable

Eg – list , set , dictionary Eg – integer, float, Boolean , complex,


string, tuple
20. What is operator and operand?
➢ An operator is used to perform specific mathematical or logical operation on values.
➢ The values that the operators work on are called operands.

21. Write about identity operator.


Identity operators are used to determine whether the value of a variable is of a certain
type or not.

22. Write about membership operator


Membership operators are used to check if a value is a member of the given sequence or
not.

21
CREATED BY J.SASIREKHA KATPADI

23. What is expression?


1. An expression is defined as a combination of constants, variables, and operators.
2. An expression always evaluates to a value.
24. Tabulate precedence of operators in python

25. Write about input(), output()


input()

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)

28. what is debugging? Mention its types


The process of identifying and removing such mistakes, also known as bugs or errors,
from a program is called debugging.
TYPES
i) Syntax errors
ii) Logical errors
iii) Runtime errors

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

7. Difference between else and elif


else elif
Condition in if block will become false Condition in if block will become false
then else block will be executed then program control move to elif and
check the condition
Syntax: Syntax:
if <condition>: if <condition>:
statement statement
else: elif <condition>:
statement statement

8. What is an infinite loop? Give one example


1.The loop statement executed again and again without end
2. Eg:
i=5
if i>0:
print(“EXAM”)
i++
3. the if loop statement execute again and again without end

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

4. what is user defined function?


we can define our own functions while writing the program. Such functions
are called user defined functions

5. what are the points to be noted while defining a user defined


function?
1. A function definition begins with def (short for define).
2. The syntax for creating a user defined function is as follows:

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.

6. What is argument, parameter?


An argument is a value passed to the function during the function call
parameter is identifier defined in function header

7. what is default value?


A default value is a value that is pre decided and assigned to the parameter
when the function call does not have its corresponding argument

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

9. Differentiate global, local variable


GLOBAL LOCAL
a variable that is defined outside A variable that is defined inside any
any function or any block function or a block
accessed in any functions It can be accessed only in the function
or a block where it is defined.

10. what is built in function?


1. Predefined functions in python library is called built in function.
2. Eg – pow(),sqrt()

11. what is module?


1. The program is divided into different parts under different levels, called
modules.
2. A module is a grouping of functions
3. To use a module, we need to import the module.
4. The syntax of import statement is as follows:
import modulename1 [,modulename2, …]

12. what are the built-in module?


1. Python library has many built-in modules
2. some commonly used modules
• math
• random
• statistics

13. Differentiate import statement and from statement


import from
Loading all functions from Loading mentioned function from
mentioned module mentioned module
Syntax Syntax
import modulename from modulename import function
name [, functionname,...]
7.STRINGS
1. What is string?
1. String is a sequence which is made up of one or more UNICODE
characters.
2. The character can be a letter, digit, whitespace or any other symbol.
3. A string can be created by enclosing one or more characters in single,
26
CREATED BY J.SASIREKHA KATPADI
double or triple quote.

2. How to access character from a string?


1. Each individual character in a string can be accessed using a technique
called indexing.
2. The index specifies the character to be accessed in the string and is
written in square brackets [ ].

3. Why string is called as immutable?


A string is an immutable data type. It means that the contents of the string
cannot be changed after it has been created.

4. Mention the string operators


Concatenation (+), repetition (*), membership(.) and slicing []

5. what is traversing a string?


We can access each character of a string or traverse a string using for loop
and while loop

String Traversal Using for Loop:


>>> str1 = 'Hello World!'
>>> for ch in str1:
print(ch,end = '')
Hello World! #output of for loop

String Traversal Using while Loop:


>>> str1 = 'Hello World!'
>>> index = 0
#len(): a function to get length of string
>>> while index < len(str1):
print(str1[index],end = '')
index += 1
Hello World! #output of while loop

6. Tabulate string built in functions

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

vii. print(mySubject[:3] + mySubject[3:])


Answer: Computer Science

viii. print(mySubject.swapcase())
Answer: cOMPUTER sCIENCE

ix. print(mySubject.startswith(‘Comp’))
Answer: True

x. print(mySubject.isalpha())
Answer: False

8. Consider the following string myAddress:


myAddress = “WZ-1,New Ganga Nagar,New Delhi”
What will be the output of following string operations:
i. print(myAddress.lower())
Answer: wz-1,new ganga nagar,new delhi

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’]

vii. 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

11. Write a function deleteChar() which takes two parameters one is a


string and other is a character. The function should create a new
string after deleting all occurrences of the character from the string
and return the new string.

def deleteChar(string, character):


newstring = ""
33
CREATED BY J.SASIREKHA KATPADI
for ch in string:
if ch != character:
newstring += ch
return newstring
string = input("Enter a string : ")
char = input("Enter character want to delete : ")
newstr = deleteChar(string, char)
print("After deleting, string is =>")
print(newstr)
Output:
Enter a string : hello my dear students
Enter character want to delete : e
After deleting, string is =>
hllo my dar studnts

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

13. Write a function that takes a sentence as an input parameter where


each word in the sentence is separated by a space. The function should
replace each blank with a hyphen and then return the modified sentence.

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

2. How to access elements from list?


List elements are accessed using its index position

3. How to traversing a list?


We can access each element of the list or traverse a list using a for loop or a
while loop.
List Traversal Using for Loop:
>>> list1 = ['Red','Green','Blue','Yellow', 'Black']
>>> for item in list1:
print(item)
Output:
Red
Green
Blue
Yellow
Black
Another way of accessing the elements of the list is using range() and
len() functions:
>>> for i in range(len(list1)):
print(list1[i])
Output:
Red
Green
Blue
Yellow
Black
List Traversal Using while Loop:
>>> list1 = ['Red','Green','Blue','Yellow',
'Black']
>>> i = 0
>>> while i < len(list1):
print(list1[i])
i += 1
Output:
Red
Green
Blue
35
CREATED BY J.SASIREKHA KATPADI
Yellow
Black

4. Write a menu driven program to perform various list operations, such


as:
• Append an element
• Insert an element
• Append a list to the given list
• Modify an existing element
• Delete an existing element from its position
• Delete an existing element with a given value
• Sort the list in ascending order
• Sort the list in descending order
• Display the list.
ANSWER
myList = [22,4,16,38,13] #myList already has 5 elements
choice = 0
while True:
print("The list 'myList' has the following elements", myList)
print("\nL I S T O P E R A T I O N S")
print(" 1. Append an element")
print(" 2. Insert an element at the desired position")
print(" 3. Append a list to the given list")
print(" 4. Modify an existing element")
print(" 5. Delete an existing element by its position")
print(" 6. Delete an existing element by its value")
print(" 7. Sort the list in ascending order")
print(" 8. Sort the list in descending order")
print(" 9. Display the list")
print(" 10. Exit")
choice = int(input("ENTER YOUR CHOICE (1-10): "))
if choice == 1:
element = int(input("Enter the element to be appended: "))
myList.append(element)
print("The element has been appended\n")
elif choice == 2:
element = int(input("Enter the element to be inserted: "))
pos = int(input("Enter the position:"))
myList.insert(pos,element)
print("The element has been inserted\n")
elif choice == 3:
newList = eval(input( "Enter the elements separated by commas"))
36
CREATED BY J.SASIREKHA KATPADI
myList.extend(list(newList))
print("The list has been appended\n")
elif choice == 4:
i = int(input("Enter the position of the element to be modified: "))
if i < len(myList):
newElement = int(input("Enter the new element: "))
oldElement = myList[i]
myList[i] = newElement
print("The element",oldElement,"has been modified\n")
else:
print("Position of the element is more than the length of list")
elif choice == 5:
i = int(input("Enter the position of the element to be deleted: "))
if i < len(myList):
element = myList.pop(i)
print("The element",element,"has been deleted\n")
else:
print("\nPosition of the element is more than the length of list")
elif choice == 6:
element = int(input("\nEnter the element to be deleted: "))
if element in myList:
myList.remove(element)
print("\nThe element",element,"has been deleted\n")
else:
print("\nElement",element,"is not present in the list")
elif choice == 7:
myList.sort()
print("\nThe list has been sorted")
elif choice == 8:
myList.sort(reverse = True)
print("\nThe list has been sorted in reverse order")
elif choice == 9:
print("\nThe list is:", myList)
elif choice == 10:
break
else:
print("Choice is not valid")
print("\n\nPress any key to continue..............")
ch = input()
Output:
The list 'myList' has the following elements [22, 4, 16, 38, 13]
LISTOPERATIONS

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

6. Differentiate between append() and extend() functions of list


append() method of list is use to add element at the end of the list.
extend() method of list is use to add a list at the end of another list.

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]

b. myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


del myList[:5]
print(myList)
Answer: [6, 7, 8, 9, 10]

c. myList = [1,2,3,4,5,6,7,8,9,10]
del myList[ : : 2]
print(myList)
Answer: [2, 4, 6, 8, 10]

9. What will be the output of the following code segment:


myList = [1,2,3,4,5,6,7,8,9,10]
for i in range(0,len(myList)):
if i%2 == 0:
print(myList[i])
output:
1
3
5
7
9

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]

ii. Find the output


list1 = [12,32,65,26,80,10]
sorted(list1)
print(list1)

Answer:
[10, 12, 26, 32, 65, 80]
[12, 32, 65, 26, 80, 10]

iii. Find the output


list1 = [1,2,3,4,5,6,7,8,9,10]
list1[::-2]
list1[:3] + list1[3:]

Answer:
[10, 8, 6, 4, 2]
[1,2,3,4,5,6,7,8,9,10]

iv. Find the output


list1 = [1,2,3,4,5]
list1[len(list1)-1]

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’

13. Write a program to find the number of times an element occurs in


the list.
list1 = [2, 5, 1, 6, 7, 2, 9, 2]
n = int(input("Number to count occurrence : "))
t = list1.count(n)
print(n, "occurs", t, "times")
output:
Number to count occurrence : 2
2 occurs 3 times

14.Write a prog to read a list of n integ (positive having all positive


numbers and the other having all negative numbers from the given
list.Print all 3 lists.
n = int(input("How many elements want in list : "))
list1 = []
for i in range(n):
num = int(input(""))
list1.append(num)
positive = []
others = []
for element in list1:
if element < 0:
others.append(element)
else:
positive.append(element)
print(list1)
print(positive)
print(others)
15. Write a function that returns the largest element of the list passed
as parameter.
def Largest(list1):
max1 = number[0]
for n in number:
if max1 < n :
max1 = n
retrun max1
#using builtin method
def Large(list1):
retrun max(list1)
number = eval(input("Enter List : ")) # like this [5,10,65,2,15,39,24]
42
CREATED BY J.SASIREKHA KATPADI
large = Largest(number)
print("Largest: ", large)

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)

18. Write a program to read a list of elements. Input an element from


43
CREATED BY J.SASIREKHA KATPADI
the user that has to be inserted in the list. Also input the position at
which it is to be inserted. Write a user defined function to insert the
element at the desired position in the list.
lst = eval(input("Enter List : "))
newelement = int(input("Enter element to be insert :"))
position = int(input("Enter valid index position "))
lst.insert( position, newelement )
print("List after insertion : ", lst)
EasyDMARC
Stop Spoofing Attacks
Streamline Your DMARC Strategy and Boost Email
Security. Get Started with EasyDMARC!

19. Write a program to read elements of a list.


a) The program should ask for the position of the element to be deleted from
the list. Write a function to delete the element at the desired position in the
list.
b) The program should ask for the value of the element to be deleted from the
list. Write a function to delete the element of this value from the list.
lst = eval(input("Enter List : "))
position = int(input("Enter valid index position, to
delete element "))
lst.pop(position)
print("List after deletion ", lst)
value = int(input("Enter value to be delete :"))
lst.remove( value )
print("List after removing 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]

21. Why list is called as mutable data type?


44
CREATED BY J.SASIREKHA KATPADI
In Python, lists are mutable. It means that the contents of the list can be
changed after it has been created.
>>> list1 = ['Red','Green','Blue','Orange']

#change/override the fourth element of list1


>>> list1[3] = 'Black'
>>> list1 #print the modified list list1
['Red', 'Green', 'Blue', 'Black']

22. Explain list operations


LIST OPERATIONS
The data type list allows manipulation of its contents through various
operations as shown below.
1.Concatenation
Python allows us to join two or more lists using concatenation operator
depicted by the symbol +.
#list1 is list of first five odd integers
>>> list1 = [1,3,5,7,9]

#list2 is list of first five even integers


>>> list2 = [2,4,6,8,10]

#elements of list1 followed by list2


>>> list1 + list2
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
>>> list3 = ['Red','Green','Blue']
>>> list4 = ['Cyan', 'Magenta', 'Yellow' ,'Black']
>>> list3 + list4
['Red','Green','Blue','Cyan','Magenta', 'Yellow','Black']
after concatenation operation. If we want to merge two lists, then we should
use an assignment statement to assign the merged list to another list. The
concatenation operator '+’ requires that the operands should be of list
type only. If we try to concatenate a list with elements of
some other data type, TypeError occurs.
>>> list1 = [1,2,3]
>>> str1 = "abc"
>>> list1 + str1
TypeError: can only concatenate list (not "str") to list

2. Repetition
Python allows us to replicate a list using repetition
operator depicted by symbol *.

45
CREATED BY J.SASIREKHA KATPADI
>>> list1 = ['Hello']

#elements of list1 repeated 4 times


>>> list1 * 4
['Hello', 'Hello', 'Hello', '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']

#list1 is truncated to the end of the list


>>> list1[2:20] #second index is out of range
['Blue', 'Cyan', 'Magenta', 'Yellow',
'Black']
>>> list1[7:2] #first index > second index
[] #results in an empty list

#return sublist from index 0 to 4


>>> list1[:5] #first index missing
['Red','Green','Blue','Cyan','Magenta']

#slicing with a given step size


>>> list1[0:6:2]

46
CREATED BY J.SASIREKHA KATPADI
['Red','Blue','Magenta']
#negative indexes

#elements at index -6,-5,-4,-3 are sliced


>>> list1[-6:-2]
['Green','Blue','Cyan','Magenta']

#both first and last index missing


>>> list1[::2] #step size 2 on entire list
['Red','Blue','Magenta','Black']
#negative step size

#whole list in the reverse order


>>> list1[::-1]
['Black','Yellow','Magenta','Cyan','Blue', 'Green','Red']

9. TUPLES AND DICTIONARIES

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.

2. why tuple is said to be immutable?


Tuple is an immutable data type. It means that the elements of a tuple
cannot be changed after it has been created. An attempt to do this would
lead to an error.
>>> tuple1 = (1,2,3,4,5)
>>> tuple1[4] = 10
TypeError : 'tuple' object does not support item assignment

3. Explain Tuple operations


1. Concatenation
Python allows us to join tuples using concatenation operator depicted by
symbol +. We can also create a new tuple which contains the result of this
concatenation operation.
>>> tuple1 = (1,3,5,7,9)
>>> tuple2 = (2,4,6,8,10)
>>> tuple1 + tuple2

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')

#tuple5 stores elements of tuple3 and tuple4


>>> tuple5 = tuple3 + tuple4
>>> tuple5
('Red','Green','Blue','Cyan','Magenta','Yellow','Black')
Concatenation operator can also be used for extending an existing tuple.
When we extend a tuple using concatenation a new tuple is created.
>>> tuple6 = (1,2,3,4,5)

#single element is appended to tuple6


>>> tuple6 = tuple6 + (6,)
>>> tuple6
(1, 2, 3, 4, 5, 6)

#more than one elements are appended


>>> tuple6 = tuple6 + (7,8,9)
>>> tuple6
(1, 2, 3, 4, 5, 6, 7, 8, 9)

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')

#tuple with single element


>>> tuple2 = ("Hello",)
>>> tuple2 * 4
('Hello', 'Hello', 'Hello', 'Hello')

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)

#elements from index 2 to index 6


>>> tuple1[2:7]
(30, 40, 50, 60, 70)

#all elements of tuple are printed


>>> tuple1[0:len(tuple1)]
(10, 20, 30, 40, 50, 60, 70, 80)

#slice starts from zero index


>>> tuple1[:5]
(10, 20, 30, 40, 50)
#slice is till end of the tuple
>>> tuple1[2:]
(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)

#tuple is traversed in reverse order


>>> tuple1[::-1]
(80, 70, 60, 50, 40, 30, 20, 10)

4.Tuple methods and built-in functions

49
CREATED BY J.SASIREKHA KATPADI

5. write about TUPLE ASSIGNMENT


Assignment of tuple is a useful feature in Python.
It allows a tuple of variables on the left side of the assignment operator to be
assigned respective values from a tuple on the right side. The number of
variables on the left should be same as the number of elements in the tuple.
50
CREATED BY J.SASIREKHA KATPADI
Example
#The first element 10 is assigned to num1 and
#the second element 20 is assigned to num2.
>>> (num1,num2) = (10,20)
>>> print(num1)
10
>>> print(num2)
20

6. What is nested tuple?


A tuple inside another tuple is called a nested tuple.
Eg:
st=((101,"Aman",98), (102,"Geet",95), (103,"Sahil",87), (104,"Pawan",79))

7. Write a program to compute the area and circumference of a circle


using a function.
def circle(r):
area = 3.14*r*r
circumference = 2*3.14*r
return (area,circumference)
radius = int(input('Enter radius of circle: '))
area,circumference = circle(radius)
print('Area of circle is:',area)
print('Circumference of circle is:',circumference)
Output:
Enter radius of circle: 5
Area of circle is: 78.5
Circumference of circle is: 31.40000000000000

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.

9. How to access elements from dictionary?


The items of a dictionary are accessed via the keys rather than via their
relative positions or indices
Eg:
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
>>> dict3['Ram']
51
CREATED BY J.SASIREKHA KATPADI
89

10. Explain Dictionary methods and built in functions

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

>>> ODD = {1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}


>>> ODD
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven', 9: 'Nine'}

(a) Display the keys


>>> ODD.keys()
dict_keys([1, 3, 5, 7, 9])

(b) Display the values


>>> ODD.values()
dict_values(['One', 'Three', 'Five', 'Seven', 'Nine'])

(c) Display the items


>>> ODD.items()
dict_items([(1, 'One'), (3, 'Three'), (5, 'Five'), (7, 'Seven'),
(9, 'Nine')])

(d) Find the length of the dictionary


>>> len(ODD)
5

(e) Check if 7 is present or not


>>> 7 in ODD
True

(f) Check if 2 is present or not


>>> 2 in ODD
False

(g) Retrieve the value corresponding to the key 9


>>> ODD.get(9)
'Nine'

(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'}

12. Write a program to enter names of employees and their salaries as


input and store them in a dictionary.
num = int(input("Enter the number of employees whose data to be stored: "))
count = 1
employee = dict() #create an empty dictionary
while count <= num:
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
count += 1
print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
print(k,'\t\t',employee[k])

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)

Find the output of the following statements:


i. print(tuple1.index(45))
2

ii. print(tuple1.count(45))
3

iii. print(tuple1 + tuple2)


(23, 1, 45, 67, 45, 9, 55, 45, 100, 200)

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)

16. Consider the following dictionary stateCapital:


stateCapital = {“AndhraPradesh”:”Hyderabad”,
“Bihar”:”Patna”,“Maharashtra”:”Mumbai”, “Rajasthan”:”Jaipur”}
Find the output of the following statements:
i. print(stateCapital.get(“Bihar”))
Patna

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

vi. print(“Maharashtra” in stateCapital)


True

vii. print(stateCapital.get(“Assam”))
Guwahati

viii. del stateCapital[“Rajasthan”]


print(stateCapital)
{‘Bihar’: ‘Patna’, ‘Maharashtra’: ‘Mumbai’, ‘Rajasthan’: ‘Jaipur’}

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

18. What advantages do tuples have over lists?


1.Tuples are faster than lists.
2. Tuples make the code safe from any accidental modification.
19. When to use tuple or dictionary in Python. Give some examples of
programming situations mentioning their usefulness.
Tuples are used to store the data which is not intended to change
during the course of execution of the program. For example, if the name of
months is needed in a program, then the same can be stored in the tuple
Dictionary is used to represent the unordered list of the data. Dictionary is
used to store associative data like student’s roll no. and the student’s name.
Here, the roll no. will act as a key to find the corresponding student’s name.
The position of the data doesn’t matter as the data can easily be searched by
using the corresponding key.
58
CREATED BY J.SASIREKHA KATPADI

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.

21. TypeError occurs while statement 2 is running. Give reason. How


can it be corrected?
tuple1 = (5) #statement 1
len(tuple1) #statement 2
tuple1 = (5) statement does not create a tuple type variable, it creates
integer type variable. len() function works with collection/sequence type
variable such tuple, list, dictionary, string.
len() function need sequence value or variable as argument. That’s why
len(tuple1) generate an error TypeError.
Corrected Way :
tuple1 = (5,) #statement 1
len(tuple1) #statement 2
Output:
1

22. To check given string is palindrome or not


a=input(“ENTER STRING”)
if a==a[::-1]:
59
CREATED BY J.SASIREKHA KATPADI
print(“GIVEN STRING IS PALINDROME”)
else:
print(“GIVEN STRING IS NOT PALINDROME”)

23. For reversing the list


L=[91,102,123,142,150]
print(L[::-1])

24. For count repeated elements


list1 = [2, 5, 1, 6, 7, 2, 9, 2]
n = int(input("Number to count occurrence : "))
t = list1.count(n)
print(n, "occurs", t, "times")

25. To accept character and check if it is an alphabet or digit or any


other special character
V=”aeiouAEIOU”
ch=input(“enter character”)
vow=0
spl=0
d=0
for i in ch:
if i>=0 and i<=9:
d+=1
print(“number of digit”,d)
elif i in V:
vow+=1
print(“number of vowels”,vow)
else:
spl+=1
print(“number of special character is “,spl)
26. To accept a number and check if it is positive even number or
negative odd number
N=int(input(“enter number”))
If N>0:
Print(“positive number”)
elif N<0:
print(“negative number”)
elif N==0:
print(“It is Zero”)

27. To accept a character and check if it is vowel or consonant


Ch=input(“Enter character”)
V=”aeiouAEIOU”
60
CREATED BY J.SASIREKHA KATPADI
if Ch in V:
Print(“given character is vowel”)
else:
print(“given character is consonant”)

28. To swap two numbers using a third variable


x = int(input("Enter value of first variable: "))
y = int(input("Enter value of first variable: "))
print("Before Swap: x = ", x, "y = ", y)
x, y = y, x
print("After Swap : x = ", x, "y = ", y)

29. To swap two numbers without using a third variable


x = int(input("Enter value of first variable: "))
y = int(input("Enter value of first variable: "))
print("Before Swap: x = ", x, "y = ", y)
x, y = y, x
print("After Swap : x = ", x, "y = ", y)

30. To print first 25 natural numbers using for loop


for i in range(1,26):
print(i)

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()

33. To calculate the factorial of given number


num = int(input("Enter a number: "))
61
CREATED BY J.SASIREKHA KATPADI
fact = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, num + 1):
fact = fact * i
print("factorial of ", num, " is ", fact)

34. To print multiplication table of given number


n=int(input("enter number"))
for a in range(1,11):
print(n,"X",a,"=",n*a)
print()

35. To check if the given year is leap year or not


year = int(input("Enter a year :"))
if year % 4 == 0:
print(year, "is a leap year")
else:
print(year, "is not a leap year")

36. program for LCM and GCD


a=int(input(“enter number”))
b=int(input(“enter number”))
if a>b:
small=b
else:
small=y
for i in range(1,small+1):
if(a%i==0) and (b%i==0):
HCF=i
LCM=(a*b)/HCF
Print(“HCF of “,a ,“and ”, b,” is”,HCF)
Print(“LCM of ”,a ,”and ”, b ,” is”,LCM)

37. write a program to print the following pattern


A
A B
A B C
A B C D
62
CREATED BY J.SASIREKHA KATPADI
A B C D E
num=int(input("enter value"))
val=ord('A')

for i in range(num+1,6):
for j in range(i+1):
print(chr(val),end=" ")
val=val+1
print()

38. program for Fibonacci series


n=int(input("how many terms"))
a=0
b=1
print("\nFIBONACCI SERIES")
print(a,'\n',b)
for i in range(2,n):
c=a+b
print(c)
a=b
b=c

39. Program to find prime numbers between 2 to 50 using nested for


num = 2
for i in range(2, 50):
j= 2
while ( j <= (i/2)):
if (i % j == 0): #factor found
break
j += 1
if ( j > i/j) :
print ( i, "is a prime number")

40. Using dictionary comprehension to pint square of given number


square_dict = {num: num*num for num in range(1, 11)}
print(square_dict)

41. Menu driven code for list manipulation


myList = [22,4,16,38,13] #myList already has 5 elements
choice = 0
while True:
print("The list 'myList' has the following elements", myList)
63
CREATED BY J.SASIREKHA KATPADI
print("\nL I S T O P E R A T I O N S")
print(" 1. Append an element")
print(" 2. Insert an element at the desired position")
print(" 3. Append a list to the given list")
print(" 4. Modify an existing element")
print(" 5. Delete an existing element by its position")
print(" 6. Delete an existing element by its value")
print(" 7. Sort the list in ascending order")
print(" 8. Sort the list in descending order")
print(" 9. Display the list")
print(" 10. Exit")
choice = int(input("ENTER YOUR CHOICE (1-10): "))
if choice == 1:
element = int(input("Enter the element to be appended: "))
myList.append(element)
print("The element has been appended\n")
elif choice == 2:
element = int(input("Enter the element to be inserted: "))
pos = int(input("Enter the position:"))
myList.insert(pos,element)
print("The element has been inserted\n")
elif choice == 3:
newList = eval(input( "Enter the elements separated by commas"))
myList.extend(list(newList))
print("The list has been appended\n")
elif choice == 4:
i = int(input("Enter the position of the element to be modified: "))
if i < len(myList):
newElement = int(input("Enter the new element: "))
oldElement = myList[i]
myList[i] = newElement
print("The element",oldElement,"has been modified\n")
else:
print("Position of the element is more than the length of list")
elif choice == 5:
i = int(input("Enter the position of the element to be deleted: "))
if i < len(myList):
element = myList.pop(i)
print("The element",element,"has been deleted\n")
else:
print("\nPosition of the element is more than the length
oflist")
elif choice == 6:
64
CREATED BY J.SASIREKHA KATPADI
element = int(input("\nEnter the element to be deleted: "))
if element in myList:
myList.remove(element)
print("\nThe element",element,"has been deleted\n")
else:
print("\nElement",element,"is not present in the list")
elif choice == 7:
myList.sort()
print("\nThe list has been sorted")
elif choice == 8:
myList.sort(reverse = True)
print("\nThe list has been sorted in reverse order")
elif choice == 9:
print("\nThe list is:", myList)
elif choice == 10:
break
else:
print("Choice is not valid")
print("\n\nPress any key to continue..............")
ch = input()

42. To calculate area of circle, perimeter of circle using menu driven


pi=3.14
r=int(input("enter radius"))
print("1.AREA\n2.CIRCUMFERENCE")
ch=int(input("enter choice"))
if ch==1:
area=pi*r*r
print("AREA OF CIRCLE IS",area)
else:
circum=2*pi*r
print("CICUMFERENCE OF CIRCLE IS",circum)

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)

45. Write a program that implements a user defined function that


accepts Principal Amount,Rate, Time, Number of Times the interest is
compounded to calculate and displays compound interest.
def compound_interest(principal,rate,time):
Amount = principal * (pow((1 + rate / 100), time))
CI = Amount - principal
print("Compound interest is", CI)
compound_interest(10000,10.25,5)

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’)

48. Write a program to input names of n students and store them in a


tuple. Also, input a name from the user and find if this student is
present
in the tuple or not.
We can accomplish these by:(a) writing a user defined function
def search_name(tname, name):
if name in tname:
return True
else:
return False
n = int(input("How many students :"))
namelst = []
for i in range(1, n+1):

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")

49. Write a Python program to find the highest 2 values in a dictionary.


numdict = {5 : 555, 8:23, 9:254, 3:658, 7:658}
val = sorted(numdict.values(), reverse = True)
print("Highest two values are ", val[0], "and", val[1])

50. Write a Python program to create a dictionary from a string.


Sample string : ‘w3resource’
Expected output : {‘3’: 1, ‘s’: 1, ‘r’: 2, ‘u’: 1, ‘w’: 1, ‘c’: 1, ‘e’: 2, ‘o’: 1}

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)

4) for <control-variable> in <sequence/items in range>:


<statements inside body of the loop>

5) range([start], stop[, step])

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)

10) max(sequence) or max(x,y,z,...)

11) min(sequence)or min(x,y,z,...)

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)

31) from modulename import functionname[,functionname,...]

32) len(str1)

33) str1.title()
34) str1.lower()

35) str1.upper()

36) count(str,start, end)

37) find(str,start,end)

38) index(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)

54) list1 = list(str1)


55) list1.append(element)

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)

68) copying list(method1)


list2 = list1

69) copying list(method 2)


newList = oldList[:]

70) list()
73
CREATED BY J.SASIREKHA KATPADI
newList = list(oldList)

71) copy()
newList = copy.copy(oldList)

72) creating tuple


(i) Tuple with n number elements
Tuple _ Name = (E1, E2, E2 ………En)
(ii) Elements of a tuple without parenthesis
Tuple_Name = E1, E2, E3 …En

(iii) Tuple with null element


Tuple _ Name = ()

73) Tuple concatenation


tuple1 + tuple2

74) Repetition in Tuple


tuple1 * times in value

75) Count no of character in tuple


len(tuple1)

76) count() in tuple


tuple1.count(element)

77) index() in Tuple


tuple1.index(element)

78) sorted() in Tuple


sorted(tuple1)

79) min() in Tuple


min(tuple1)

80) max() in Tuple


max(tuple1)

81) sum() in Tuple


sum(tuple1)

82) create empty dictionary


dict1 = { }
74
CREATED BY J.SASIREKHA KATPADI

83) dictionary with elements


dict1 = {key1:value1,key2:value2….keyn:valuen}

84) modifying value in dictionary


dict1[key]=new_value
85) membership operator
key in dict1
key not in dict1

86) len() in dictionary


len(dict1)

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()

95) Display the keys


dict1.keys()

96) Display the values

75
CREATED BY J.SASIREKHA KATPADI
dict1.values()

97) Displaying the items


dict1.items()

76

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy