0% found this document useful (0 votes)
14 views37 pages

Class 11 Python Notes

The document provides a comprehensive review of Python, covering its characteristics, data types, variables, and error handling. It highlights Python's object-oriented nature, ease of use, and support for various programming paradigms, along with details on tokens, expressions, and operators. Additionally, it discusses common errors and exceptions, as well as the concept of modules in Python programming.

Uploaded by

rishitalk25
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)
14 views37 pages

Class 11 Python Notes

The document provides a comprehensive review of Python, covering its characteristics, data types, variables, and error handling. It highlights Python's object-oriented nature, ease of use, and support for various programming paradigms, along with details on tokens, expressions, and operators. Additionally, it discusses common errors and exceptions, as well as the concept of modules in Python programming.

Uploaded by

rishitalk25
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

REVIEW OF PYTHON

LET US REVISE THE CONCEPTS THAT WE LEARNED IN CLASS XI


Characteristics of Python:
1. Python is Object-Oriented
Python supports concepts such as polymorphism, operator overloading and
multiple inheritance.
2. Indentation
Indentation is one of the greatest features in python – indentation identifies the
blocks of code.
3. Open source Programming Language
Python is an open source programming language.
It can be freely downloaded. Installing python is free and easy
4. It’s Powerful
 Dynamic typing
 Built-in types and tools
 Library utilities
 Third party utilities (e.g. NumPy, SciPy)
 Automatic memory management
5. It’s Portable and Platform independent
 Python runs virtually in every major platform used today
 As long as you have a compatible python interpreter installed, python
programs will run in exactly the same manner, irrespective of platform.
6. It’s easy to use and learn
 No intermediate compiler
 Python Programs are compiled automatically to an intermediate form called
byte code, which the interpreter then reads.
 This gives python the development speed of an interpreter without the
performance loss inherent in purely interpreted languages.
 Structure and syntax are pretty intuitive and easy to grasp.
7. Interpreted Language
Python is processed at runtime by python Interpreter
8. Interactive Programming Language
Users can interact with the python interpreter directly for writing the programs
9. Straight forward syntax
The formation of python syntax is simple and straight forward which also makes it
popular.

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 1
Character Set of Python:
Set of all characters recognised by python. It can be any alphabet, digit or any symbol.
Python uses ASCII character set.
Python Supports the following character set:
Letters: A- Z and a -z
Digits: 0-9
Special Symbols: + , - , /, % , ** , * , [ ], { }, #, $ etc.
White spaces: Blank space, tabs, carriage return, newline, form feed
Other Characters: All ASCII and UNICODE characters.
Tokens:
Tokens are smallest identifiable units.
Different tokens are:
 Keywords: reserved words which are having special meaning.
 Examples: int, print, input, for, while
 Identifiers: name of given by the user to identify variables, functions, constants,
etc.
 Literals: literals are constant values. It can be numeric or non-numeric
 Operators: triggers an operation. Parameters provided to the operators are called
 operands
 Examples: + - * % ** / //
 Delimiters: Symbols used as separators.
 Examples: {} , [ ] ; :
Rules for identifier names:
 Keywords and operators are not to be used
 Start with an alphabet or an underscore.
 Special characters other than underscores are allowed.
 Space is not allowed.
 Cannot start with a number.
 Note: Python is case sensitive and hence uppercase and lowercase are treated
differently.
 Example:
o engmark, _abc , mark1, mark2

Variables and data types:


Variables are used to store data. In Python a variable is an object. Variables are nothing
but reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory. Memory locations are addressable.

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 2
The data stored in memory can be of many types. For example, a student roll number is
stored as a numeric value and his or her address is stored as alphanumeric characters.
Python has various standard data types that are used to define the operations possible on
them and the storage method for each of them. Some are mutable and some are
immutable.

 Numeric Types: int, float, complex


 Boolean – True or False values. Used when comparisons are made and the result
can be expressed as True or False
 None – a special type with an unidentified value or absence of value.
 Sequence: an ordered collection of elements. String, List and Tuples are sequences.
Items/elements are Identified by its index.
 Sets – an unordered collection of any type without duplicate entry.
 Mappings – Dictionaries are mappings. Elements of dictionaries are key-value
pairs. Keys are used to access values. Keys are immutable.

Based on the data type of a variable, the interpreter allocates memory and decides what
can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals or characters in these variables.

Mutable and Immutable types:


If the values can be changed after creating the variable and assigning values, then it is
called mutable. If the value assigned cannot be changed after creating and initializing it,
then it is known as Immutable.
When an attempt is made to update the immutable type, a new memory location is used
with name remaining the same.

Assigning Values to Variables:


Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The assignment
operator (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to
the right of the = operator is the value stored in the variable.
For example –
a= 100 #an integer is signed
b = 1000.0 # A floating point value
c = "John" # A string
d = ‘’’ Hello world
good morning’’’ # multi line string

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 3
Multiple Assignments:
Python allows you to assign a single value to several variables simultaneously.

For example: a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned to
the same memory location. You can also assign multiple objects to multiple variables.

For example −
a,b,c = 1,2,"kvsch“
Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
Also, it is possible to define and initialize multiple variables with different values as given
below
a, b, c = 5,10,20
The above instruction will create three variables named a,b,c and initialize them with
values 5, 10 20 respectively.

Output Variables:
The Python print statement is often used to output [Link] do not need to be
declared with any particular type. Different type of data can be assigned even after
initializing them with some type of data.
x = 5 # x is of type int
x = "kve " # x is now of type str print(x)
Output: kve

To combine both text and a variable, Python uses the “+” character:
Example
x = "awesome"
print("Python is " + x)
Output of the above code is:
Python is awesome

You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z = x + y print(z)
Output:
Python is awesome

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 4
Expressions:
An expression is a combination of values, variables, and operators.
An expression is evaluated using assignment operator.
Examples: Y=x + 17
>>> x=10
>>> z=x+20
>>> z
30

>>> x=10
>>> y=20
>>> c=x+y
>>> c
30

A value all by itself is a simple expression, and so is a variable.


>>> y=20
>>> y
20
Python also defines expressions with identifiers, literals, and operators. So,

Operators:
In Python you can implement the following operations using the corresponding operators.
Operators trigger an operation. Some operators need one operand, some need more than
one operand to perform the operation.

Python supports different types of operators including Arithmetic Operators, Relational


Operators, Logical Operators etc.

Operator Token

addition +

subtraction -

multiplication *

Integer Division /

remainder %

Binary left shift <<

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 5
Binary right shift >>

and &

or \

Less than <

Greater than >

Less than or equal to <=

Greater than or equal to >=

Check equality ==

Check not equal !=

Statements:
A statement is an instruction that the Python interpreter can execute. We have normally
two basic statements, the assignment statement and the print statement. Some other
kinds of statements that are if statements, while statements, and for statements generally
called as control flows.

Examples:
An assignment statement creates new variables and gives them values:

>>> x=10
>>> school="kve"

A ‘print’ statement is to display something on the screen/monitor. We use the print()


function for this purpose. And input() function is used to receive the input from the user
through the keyboard.
Precedence of Operators:
Operator precedence affects how an expression is evaluated. Each operator is having a
priority when used in an expression in combination with other operators.
For example, x = 7 + 3 * 2;
here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first
multiplies 3*2 and then adds into 7.
Example 1:
>>> 3+4*2 11
Multiplication gets evaluated before the addition operation

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 6
>>> (10+10)*2 40
Parentheses () overriding the precedence of the arithmetic operators

Example 2:
a = 20
b = 10
c = 15
d=5
e=0

e = (a + b) * c / d #( 30 * 15 ) / 5
print("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print("Value of ((a + b) * c) / d is ", e)
e = (a + b) * (c / d) # (30) * (15/5)
print("Value of (a + b) * (c / d) is ", e)

e = a + (b * c) / d; # 20 +(150/5)
print("Value of a + (b * c) /d is", e)

Output:
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) /d is 50.0

Comments:
Comments are discarded by the Python interpreter. Comments acts as some message to
the
Programmer. It can be used as documents.

Single-line comments begins with a hash(#) symbol and is useful in mentioning that the
whole line should be considered as a comment until the end of line.
A Multi line comment is useful when we need to comment on many lines. In python, triple
double quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting.
Example:
# this is a single line comment
‘’’ I am a multi line comment’’’

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 7
Errors and Exceptions:
Python Errors and Built-in Exceptions: Python (interpreter) raises exceptions when it
encounters errors. When writing a program, we, more often than not, will encounter
errors. Error caused by not following the proper structure (syntax) of the language is called
syntax error or parsing error.

ZeroDivisionError: ZeroDivisionError in Python indicates that the second argument used


in a division (or modulo) operation was zero.

Overflow Error: OverflowError in Python indicates that an arithmetic operation has


exceeded the limits of the current Python runtime. This is typically due to excessively large
float values, as integer values that are too big will opt to raise memory errors instead.

Import Error: It is raised when you try to import a module which does not exist. This may
happen if you made a typing mistake in the module name or the module doesn't exist in
its standard path. In the example below, a module named "non_existing_module" is being
imported but it doesn't exist, hence an import error exception is raised.

Index Error: An IndexError exception is raised when you refer a sequence which is out of
range. In the example below, the list abc contains only 3 entries, but the 4th index is being
accessed, which will result an IndexError exception.

Type Error: When two unrelated type of objects are combined, TypeErrorexception is
[Link] example below, an int , and a string is added, which will result in TypeError
exception.

Indentation Error: Unexpected indent - As mentioned in the "expected an indented block"


section, Python not only insists on indentation, it insists on consistent indentation. You
are free to choose the number of spaces of indentation to use, but you then need to stick
with it.

Syntax errors: These are the most basic type of error. They arise when the Python parser
is unable to understand a line of code. Syntax errors are almost always fatal, i.e. there is
almost never a way to successfully execute a piece of code containing syntax errors

Run-time error: A run-time error happens when Python understands what you are saying,
but runs into trouble when following your instructions.

Key Error : Python raises a KeyError whenever a dict() object is requested (using
the format a= adict[key]) and the key is not in the dictionary.

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 8
Value Error: In Python, a value is the information that is stored within a certain object. To
encounter a ValueError in Python means that is a problem with the content of the object
you tried to assign the value to.

Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong. In Python, users can define such exceptions by creating a new
class. This exception class has to be derived, either directly or indirectly, from
Exception class.
Different types of exceptions:
 ArrayIndexOutOfBoundException.
 ClassNotFoundException.
 FileNotFoundException.
 IOException.
 InterruptedException.
 NoSuchFieldException.
 NoSuchMethodException

Modules:
Python module can be defined as a python program file which contains a python code
including python functions, class, or variables. In other words, we can say that our python
code file saved with the extension (.py) is treated as the module. We may have a runnable
code inside the python module. A module in Python provides us the flexibility to organize
the code in a logical way. To use the functionality of one module into another, we must
have to import the specific module.

Syntax:
import <module-name>
Every module has its own functions, those can be accessed with . (dot)
Note: In python we have help ()

Enter the name of any module, keyword, or topic to get help on writing Python programs
and using Python modules. To quit this help utility and return to the interpreter, just type
"quit".
Some of the modules like os, date, and calendar so on……

>>> import sys


>>> print ([Link])
3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)]

>>> print(sys.version_info)

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 9
sys.version_info(major=3, minor=8, micro=0, release level='final', serial=0)

>>> print([Link](2020))
True
>>> print([Link](2017))
False

Control Structures
Flow of execution means the way in which the instructions are executed. It can be
1. Sequential execution
2. Selection/ Conditional statements
3. Iterations/loop
Sequential execution means executing the statements one by one starting from the first
instruction onwards.

Selection:
Selection or Conditional statements helps us to execute some statements based on
whether the condition is evaluated to True or False.

Use of if statement:
The if statement contains a logical expression using which data is compared and a decision
is made based on the result of the comparison.

Syntax:
if <expression>:
statement(s)

If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. If boolean expression evaluates to FALSE, then the first set of code
after the end of the if statement(s) is executed.

Flow chart representing the execution of ‘if’ statement:

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 10
Example: Python if Statement
a=3
if a > 2:
print(a, "is greater")
print("done")
a = -1
if a < 0:
print(a, "a is smaller")
print(“Finish”)

Output:
3 is greater
done
-1 a is smaller
Finish

a=10
if a>9:
print("A is Greater than 9")
Output:
A is Greater than 9

Alternative if (If-else):
An else statement can be combined with an if statement. An else statement contains the
block of code (false block) that executes if the conditional expression in the if statement
resolves to 0 or a FALSE value.

The else statement is an optional statement and there could be at most only one else
Statement following if.

Syntax of if - else:
if test expression:
Body of if stmts
else:
Body of else

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 11
Flow Chart:

Example of if - else:
a=int(input('enter the number'))
if a>5:
print("a is greater")
else:
print("a is smaller than the input given")
Output:
enter the number 2
a is smaller than the input given
----------------------------------------
a=10 b=20
if a>b:
print("A is Greater than B")
else:
print("B is Greater than A")

Output:
B is Greater than A
Chained Conditional: (If-elif-else):
The elif statement allows us to check multiple expressions for TRUE and execute a block
of code as soon as one of the conditions evaluates to TRUE. Similar to the else, the elif
statement is optional. However, unlike else, for which there can be at most one statement,
there can be an arbitrary number of elif statements following an if.

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 12
Syntax of if – elif - else :
If <test expression>:
Body of if stmts
elif < test expression>:
Body of elif stmts
else:
Body of else stmts

Flow Chart:

Example of if - elif – else:


a=int(input('enter the number'))
b=int(input('enter the number'))
c=int(input('enter the number'))
if a>b:
print("a is greater")
elif b>c:
print("b is greater")
else:
print("c is greater")
Output:
enter the number 5
enter the number 2
enter the number 9
a is greater
>>>
enter the number 2

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 13
enter the number 5
enter the number 9
c is greater
-----------------------------
var = 100
if var == 200:
print("1 - Got a true expression value")
print(var)
elif var == 150:
print("2 - Got a true expression value")
print(var)
elif var == 100:
print("3 - Got a true expression value")
print(var)
else:
print("4 - Got a false expression value")
print(var)
Output:
3 - Got a true expression value
100

Iteration/Repetition:
A loop statement allows us to execute a statement or group of statements multiple times
as long as the condition is true. Repeated execution of a set of statements with the help
of loops is called iteration.
Loops statements are used when we need to run same code again and again, each time
with a different value.

In Python Iteration (Loops) statements are of three types:


 While Loop
 For Loop
 Nested For Loops

While loop:
Loops are either infinite or conditional. Python while loop keeps iterating a block of code
defined inside it until the desired condition is met.
 The while loop contains a Boolean expression and the code inside the loop is
repeatedly executed as long as the Boolean expression is true.
 The statements that are executed inside while can be a single line of code or a block
of multiple statements

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 14
Syntax:
while(expression):
Statement(s)

Flow Chart:

Example Programs:
i=1
while i<=6:
print("KV School")
i=i+1
Output:
KV School
KV School
KV School
KV School
KV School
KV School
_____________________________________________
i=1
while i<=3:
print("KV School",end=" ")
j=1
while j<=1:
print("CS DEPT",end="")
j=j+1
i=i+1
print()

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 15
Output:
KV School CS DEPT
KV School CS DEPT
KV School CS DEPT

For loop:
Python for loop is used for repeated execution of a group of statements for the desired
number of times. It iterates over the items of lists, tuples, strings, the dictionaries and
other iterable objects.

Syntax:
for <loopvariable> in <sequence>:
Statement(s)

A sequence or iterable object is used to execute the loop. The for loop executes for a
definite number of times. During each of the iteration, the loop variable holds a value from
the sequence.
Example 1:
L = [ 1, 2, 3, 4, 5]
for var in L:
print( var, end=’ ‘)

Output of the above code is:


12345
Example 2:
for k in range(10):
print(k, end =’ , ‘)

output: 0,1,2,3,4,5,6,7,8,9
Example 3:
for k in range(1, 10):
if k% 2 ==0:
print(k, end = ‘ , ‘)
Output: 2, 4, 6, 8

Example 4:
list = ['K','V','S','C','H']
i=1
for item in list:

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 16
print ('School ',i,' is ',item)
i = i+1
Output:
School 1 is K
School 2 is V
School 3 is S
School 4 is C
School 5 is H

Example 5:
#Iterating over a Tuple:
tuple = (2,3,5,7)
print ('These are the first four prime numbers ')
#Iterating over the tuple
for a in tuple:
print (a)

Output:
These are the first four prime numbers 2
3
5
7

Example 6:
# Iterating over a dictionary:
#creating a dictionary
college = {"ces":"block1","it":"block2","ece":"block3"}
#Iterating over the dictionary to print keys
print ('Keys are:')
for keys in college:
print (keys)
#Iterating over the dictionary to print values
print ('Values are:')
for blocks in [Link]():
print(blocks)

Output:
Keys are:
ces
it

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 17
ece
Values are:
block1
block2
block3
Example 7:
#Iterating over a String:
#declare a string to iterate over
college = 'KVSCH'
#Iterating over the string
for name in college:
print (name)

Output:
K
V
S
C
H

Nested For loop:


When one Loop is defined within another, it is called Nested Loops.

Syntax:
for val in sequence1:
for val in sequence2:
statements

# Example 1 of Nested For Loops (Pattern Programs)


for i in range(1,6):
for j in range(0,i):
print(i, end=" ")
print('')
Output:
1
22
333
4444
55555

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 18
# Example 2 of Nested For Loops (Pattern Programs)
for i in range(1,6):
for j in range(5,i-1,-1):
print(i, end=" ")
print('')

Output:
111111
2222
333
44
5

Break and continue:


In Python, break and continue statements can alter the flow execution of a normal loop.
Sometimes we wish to terminate the current iteration or even the whole loop without
checking test expression/completing it. The break and continue statements are used in
these cases.
‘break:’ statement
The break statement terminates the loop containing it and control of the program flows
to the statement specified immediately after the body of the loop. If ‘break’ statement is
written within a nested loop (loop inside another loop), break will terminate the
innermost loop.
‘continue’ Statement
The ‘continue’ statement is used to skip the current iteration / rest of the code inside a
loop for the current iteration only. Loop does not terminate but continues on with the
next iteration.
‘pass’ statement:
In Python programming, pass is a null statement. The difference between a comment
and
pass statement in Python is that, while the interpreter ignores a comment entirely, pass
is not ignored. ‘pass’ is just a place holder for functionality to be added later.

Strings:
A string is a group/ a sequence of characters. Since Python has no provision for arrays, we
simply use strings. A sequence of any type of characters enclosed within quotes, is a string.
This is how we declare a string. We can use a pair of single or double quotes. Every string
object is of the type ‘str’.
>>> type("name")
<class 'str'>

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 19
>>> name=str()
>>>name
''
>>> a=str('kvsch')
>>> a
' kvsch'
>>> a=str(kvsch)
>>> a[2]
's'
>>> fruit = 'banana'
>>> letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to letter. The
expression in brackets is called an index. The index indicates which character in the
sequence we want.

String slices:
A segment or a part of a string is called a slice. Selecting a slice is similar to selecting a
character:
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting
at 0 in the beginning of the string and working their way from -1 at the end.
Slice out substrings, sub lists, sub Tuples using index.
Syntax:
[Start: stop: steps]
 Slicing will start from index and will go up to stop in step of steps.
 Default value of start is 0,
 Stop is last index of list
 And for step default is 1
For example, 1:
str = 'Hello World!'
print (str) # Prints complete string
print (str[0] )# Prints first character of the string
print (str[2:5] ) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print ( str * 2 )# Prints string two times
print (str + "TEST") # Prints concatenated string
Output:
Hello World!
H
llo
llo World!

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 20
Hello World!Hello World!
Hello World!TEST

Example 2:
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[1:6:2]
'opt'
>>> x[3:]
puter
>>> x[:5]
'compu'
>>> x[-1]
'r'
>>> x[-3:]
'ter'
>>> x[:-2]
'comput'
>>> x[::-2]
'rtpo'
>>> x[::-1]
'retupmoc'

Note: strings are immutable, which means we can’t change an existing string.
The best we can do is create a new string that is a variation from the original:

String concatenation and repetition operators:


‘+’ is called concatenation operator. When both the operands are strings, it will combine
them.

‘*’ is called repetition operator and it causes repetition of the characters the specified
number of times.

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 21
String functions and methods:
There are many methods to operate on String.
[Link] Method name Description
1. isalnum() Returns true if string has at least 1
character and all characters are
alphanumeric and false otherwise.
2. isalpha() Returns true if string has at least 1
character and allcharacters are alphabetic
and false otherwise.
3. isdigit() Returns true if string contains only
digits and falseotherwise.
4. islower() Returns true if string has at least 1 cased character and all
casedcharacters are in lowercase and false
otherwise.
5. isnumeric() Returns true if a string contains
only numericcharacters and false
otherwise.
6. isspace() Returns true if string contains only
whitespace characters and false
otherwise.
7. istitle() Returns true if string is properly
“titlecased” andfalse otherwise.
8. isupper() Returns true if string has at least one cased character and
allcased characters are in uppercase
and false otherwise.
9. replace(old,new[, max]) Replaces all occurrences of old in string
with new or at most max occurrences if
max given.
10. split() Splits string according to delimiter str
(space if not provided) and returns list
of substrings;
11. count() Occurrence of a string in another string
12. find() Finding the index of the first occurrence of a string
inanother string
13. swapcase() Converts lowercase letters in a string to
uppercaseand viceversa
14. startswith(str,beg=0 Determines if string or a substring of string (if starting
, end=len(string)) index beg and ending index end are given) starts with
substring str; returns true if so and false
otherwise.

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 22
List:
With the help of lists, we can store different types of items in a variable. It helps us to
store collection of data. List items are ordered, changeable and can be repeated. Indexes
are used to access the items.
Lists are mutable.

Python has a set of built-in methods that you can use on lists
Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Whenever we need an array, we can use lists. We can construct / create list in many ways.
Example 1:
list1=[1,2,3,'A','B',7,8,[10,11]]
print(list1)

output:
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]

Example 2:
x=list()
print(x)
output:
x []

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 23
Example 3:
Name = “ abcdefg”
L = list(Name)
print(L)
Output:
[ ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’]

Basic List Operations:


Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.

Python Expression Results Description


len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership


for x in [1, 2, 3]: print x, 123 Iteration

Note: indexing and slicing are similar to that of strings.


For example:
L= ['kvsch', 'school', 'KVSCH!']

Python Expression Results Description

L[2] KVSCH Offsets start at zero

L[-2] school Negative: count from the right

L[1:] ['school', 'KVSCH!'] Slicing fetches sections

List slices: - Examples


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

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 24
>>> list1[2:5]
Output: [3, 4, 5]
>>> list1[:6]
Output: [1, 2, 3, 4, 5, 6]
>>>list1 [1:2:4]
Output:[2]
>>> ist1[1:8:2]
output: [2, 4, 6, 8]

List Comprehension:
This is a way to create a new list using an existing list.
Syntax:
NewList = [ expression for variable in iterableobject if condition == True ]

Example1:
list1=[x**2 for x in range(10)]
print(list1)
output:
[ 0,1,4,9,16,25,36,49,64,81]

Note: in the above given code, a new list named list1 is created using the expression x**2,
where the for loop is used to assign different values to ‘x’ using the range( ) function.

Example 2:
x=[z**2 for z in range(10) if z>4]
print(x)
Output: [25, 36, 49, 64, 81]

Example 3:
x=[x ** 2 for x in range (1, 11) if x % 2 == 1]
print(x)
Output: [1, 9, 25, 49, 81]

Tuples:
A tuple is a collection which is ordered and unchangeable. In Python tuples are created by
enclosing items within round brackets.
 Supports all operations for sequences.
 Immutable, but member objects may be mutable.
 If the contents of a list shouldn’t change, use a tuple to prevent items from
accidently being added, changed, or deleted.

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 25
 Tuples are more efficient than list due to python’s implementation.
We can create tuple in different ways.
X=( ) # an empty tuple
X=(1,2,3) # a tuple with three elements
X=tuple(list1)
X=1,2,3,4

Accessing elements of a tuple:


We can use index to access the elements of a tuple. From left to right, index varies from 0
to n-1, where n is total number of elements in the tuple. From right to left, the index starts
with -1 and the index of the leftmost element will be –n, where n is the number of
elements.

Syntax:
<Name of the tuple>[index]
Example:
T = ( 1, 2,4,6)
print(T[0])
Output: 1
print(T[--1])
Output: 6

Modifying the elements of a tuple:


Once created, we cannot modify the elements of a tuple. Tuple is immutable. If we try to
modify the Element, it will generate ‘TypeError’

Some important functions which can be used with tuple:


count (): Returns the number of times a specified value occurs in a tuple
Example:
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> [Link](2)
output: 4

index (): Searches the tuple for a specified value and returns its position in the tuple.

>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> [Link](2)
Output: 1
(Or)

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 26
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=[Link](2)
>>> print(y)
Output: 1

len(): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
output: 12

Tuple comprehension:
Tuple Comprehensions are special: The result of a tuple comprehension is special. You
might expect it to produce a tuple, but what it does is produce a special "generator" object
that we can iterate over.
For example:
>>> x = (i for i in 'abc') #tuple comprehension
>>> x
<generator object <genexpr> at 0x033EEC30>

>>> print(x)
<generator object <genexpr> at 0x033EEC30>

You might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr>
at 0x02AAD710>. The result of a tuple comprehension is not a tuple: it is actually a
generator. The only thing that you need to know now about a generator is that you can
iterate over it, but ONLY ONCE.

Example:
>>> x = (i for i in 'abc')
>>> for i in x:
print(i)

Output:
a
b
c
Example:
Create a list of 2-tuples like (number, square):
>>> z=[(x, x**2) for x in range(6)]

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 27
>>> z
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

Set comprehension:
Similarly, to list comprehensions, set comprehensions are also supported by Python:

Example:
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
Output:
{'r', 'd'}

>>> x={3*x for x in range(10) if x>5}


>>> x

Output:
{24, 18, 27, 21}

Note: In case of set, elements are enclosed within { }.

Dictionaries:
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are created with curly brackets, and they have keys and values. It is a
mapping. Values can be of any type. Only immutable types are allowed as keys. It is not
possible to repeat keys. They are to be unique.
 Key-value pairs
 Unordered

We can construct or create dictionary like:


X={1:’A’,2:’B’,3:’c’}X=dict([(‘a’,3) (‘b’,4)]
X=dict(‘A’=1,’B’ =2)

Example:
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> dict1
{'brand': 'mrcet', 'model': 'college', 'year': 2004}

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 28
Functions available for handling dictionary:

Method Description

clear() Remove all items form the dictionary.

copy() Return a shallow copy of the dictionary.


Return a new dictionary with keys from seq and valueequal to
fromkeys(seq[, v]) v (defaults to None).
Return the value of key. If key does not exit, return d
get(key[,d]) (defaults to None).

items() Return a new view of the dictionary's items (key,value).

keys() Return a new view of the dictionary's keys.

Remove the item with key and return its value or d ifkey is not
pop(key[,d])
found. If d is not provided and key is not found, raises KeyError.

Remove and return an arbitary item (key, value). Raises


popitem() KeyError if the dictionary is empty.

If key is in the dictionary, return its value. If not,insert key


with a value of d and
setdefault(key[,d]) return d (defaults to None).

Update the dictionary with the key/value pairs fromother,


update([other]) overwriting existing keys.

values() Return a new view of the dictionary's values

remove(): It removes or pop the specific item of dictionary

del( ) Deletes a particular item

len( ) we use len() method to get the length of dictionary


Note: keys are used to access or modify the items of a dictionary.

Comprehension:
Dictionary comprehensions can be used to create dictionaries from arbitrary key and
value expressions
Syntax:
<dictionary> = { expression for <variable> in sequence }

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 29
Example:
>>> z={x: x**2 for x in (2,4,6)}
>>> z
{2: 4, 4: 16, 6: 36}
>>> dict11 = {x: x*x for x in range(6)}
>>> dict11
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Important Points to remember:


 Data types: int, float, complex, Boolean, string, list, tuple, set, dictionary
 Variables are used to hold data. They are having memory address and values of
particular types are stored.
 It is not possible to modify immutable types/objects.
 Mutable objects/types can be modified.
 Dictionary uses keys to identify values. Key can be of any immutable type and is
not possible to change or duplicate.
 Values of a dictionary can be of any type.
 Three different programming constructs supported by Python are Sequence,
Selection, and Iteration.
 For selection, Python uses if, if..else, and if,,,elif…elif,,,else constructs.
 Different types of loops are while loop and for loop.
 While loop will continue till the specified number of times or till the given test
expression is True.
 ‘for’ loop is used when we have to iterate over a sequence. How many times it is
to be repeated is Known.
 Strings are sequence of characters. If enclosed in single or double quotes, it must
be confined to a line.
 String enclosed within triple quotes can be of multiple lines and are also called as
docstrings.
 List comprehension is a way to create a new list using an existing sequence.
 Examples for immutable types: int, float, string, tuple
 Examples for mutable types: list

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 30
Multiple Choice Questions
1. Which of the following is not a keyword?
a) Eval b) assert c) nonlocal d) pass
2. What is the order of precedence in python?
(i) Parentheses ii) Exponential iii) Multiplication iv) Division v) Addition vi)
Subtraction
a) i,ii,iii,iv,v,vi
b) ii,i,iii,iv,v,vi
c) ii,i,iv,iii,v,vi
d) i,ii,iii,iv,vi,v

3. What error occurs when you execute the following Python code snippet?
apple = mango
a) SyntaxError
b) NameError
c) ValueError
d) TypeError

4. Find the output.


def example(a):
a = a+2
a=a*2
return a
>>>example("hello")
a. indentation Error
b. cannot perform mathematical operation on strings
c. hello2
d. hello2hello2

5. What will be the value of X in the following Python expression?


X = 2+9*((3*12)-8)/10

a) 30.0
b) 30.8
c) 28.4
d) 27.2

6. Select all options that print. hello-how-are-you

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 31
a. print(‘hello’, ‘how’, ‘are’, ‘you’)
b. print(‘hello’, ‘how’, ‘are’, ‘you’ + ‘-‘ * 4)
c. print(‘hello-‘ + ‘how-are-you’)
d. print(‘hello’ + ‘-‘ + ‘how’ + ‘-‘ + ‘are’ + ‘you’)

7. Which of the following can be used as valid variable identifier(s) in Python?


a. total
b. 7Salute
c. Que$tion
d. global

8. Which of the following statement is correct for an AND operator?


a) Python only evaluates the second argument if the first one is False
b) Python only evaluates the second argument if the first one is True
c) Python only evaluates True if any one argument is True
d) Python only evaluates False if any one argument is False

9. Which of the following forces an expression to be converted into specific type?


a) Implicit type casting b) Mutable type casting
c) Immutable type casting d) Explicit type casting
10. Which point can be considered as difference between string and list?
a. Length c. Indexing and Slicing
b. Mutability d. Accessing individual elements

[Link] of the following statement is true for extend () list method?


a) adds element at last c) adds multiple elements at last
b) adds element at specified index d) adds elements at random index

[Link] statement del l[1:3] do which of the following task?


a) delete elements 2 to 4 elements from the list
b) delete 2nd and 3rd element from the list
c)deletes 1st and 3rd element from the list
d)deletes 1st, 2nd and 3rd element from the list

[Link] l=[11,22,33,44], then output of print(len(l)) will be


a)4 b)3 c) 8 d) 6

[Link] of the following method is used to delete element from the list?
a)del()
b)delete()
c)pop()
d)All of these

[Link] step argument in range() function .


a. indicates the beginning of the sequence

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 32
b. indicates the end of the sequence
c. indicates the difference between every two consecutive numbers in the sequence
d. generates numbers up to a specified value

Answers of MCQ:
1) A 2)A 3)B 4)A 5)D 6)C 7)A 8)B 9) D 10)B 11)B 12)B 13)A 14)C
15)C

Very Short Answer Type Questions


1. Give the output of the following

Sum = 0
for k in range(5):
Sum = Sum+k
print(Sum)

2. Give the output of the following

Sum = 0
for k in range(10 , 1, -2):
Sum = Sum+k
print(Sum)

3. Give the output of the following

for k in range(4):
for j in range(k):
print(‘*’, end = ‘ ‘)
print()

4. Give the output of the following

for k in range(5,0, -1):


for j in range(k):
print(‘*’, end=’ ‘)
print()

5. How many times the following loop will execute? Justify your answer
A=0
while True:
print(A)
A =A+1
6. Give the output of the following. Also find how many times the loop will execute.

A=0
while A<10:

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 33
print(A, ‘ , ‘)
A =A+1

7. Give the output of the following. Also find how many times the loop will execute.
A=0
while A<10:
print(A, ‘ , ‘)
A =A+1
print(‘\n’, A)

8. Give the output of the following

T = (5)
T = T*2
print(T)

9. Give the output of the following


T = (5, )
T = T*2
print(T)

10. What kind of error message will be generated if the following code is executed
A=5
B = ‘hi’
d = A+B
print(D)

11. Give the output of the following


L = [1,2,3,4,5,6,7,8,9]
print(L[:])

12. Give the output of the following


L = [1,2,3,4,5,6,7,8,9]
print(L[: -1])

13. Find the output of the following

S = ‘abcdefgh’
L = list(S)
print(L[1:4])

14. Give the output of the following


L = [1,2,3,4,5,6,7,8,9]
print([Link](2))
print([Link](2)

15. Write python code to sort the list, L, in descending order.

16. Give the output of the following


x=[4,5,66,9]
y=tuple(x)

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 34
print( y)

Answers for VSA Questions

1)10
2)30
3)
*
* *
* * *

4) * * * * *
* ***
* * *
* *
*
5)infinite loop. Condition / test expression is always Ture.

6) 0,1,2,3,4,5,6,7,8,9

7) 0,1,2,3,4,5,6,7,8,9
10

8) 10 Note: here T is an integer

9) (5, 5), Note: here T is tuple

10)TypeError

11) [1,2,3,4,5,6,7,8,9]

12) [1,2,3,4,5,6,7,8]

13) ['b', 'c', 'd']

14) 1
1

15) [Link](reverse= True)


16) (4, 5, 66, 9)

Short Answer Type Questions


[Link] the following dictionary ‘D’. Display all the items of the dictionary as
individual tuple
D = {‘A’: 20, ‘B’: 30, ‘C’:40. ‘D’: 50}

[Link] Python code to remove an element as entered by the user form the list, L

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 35
[Link] a list k, by selecting all the od numbers within the given range, m and n. User
will input the values of m , n at run time

[Link] Python code to create and add items to a dictionary. Ask the user to input key
value pairs. Continue as long as the user wishes.

[Link] Python code to find whether the given item is present in the given list using for
loop.
[Link] a list, L, with the squares of numbers from 0 to 10
[Link]. Rahul wants created a dictionary to store the details of his students and to
manipulate thedata.
He wrote a code in Python, help him to complete the code:

studentDict = ______ # stmt 1


n = int(input("How Many Students you Want To Input?"))
for i in range(___ ): # stmt 2 - to enter n number of students data
rollno = input("Enter Roll No:")
name = input("Enter Name:")
physicsMarks = int(input("Enter Physics Marks:"))
chemistryMarks = int(input("Enter Chemistry Marks:"))
mathMarks = int(input("Enter Maths Marks:"))
studentDict[rollno]=__________ # stmt 3

Answers /Hints: Short answer Type Questions.


1) for k in [Link]():
print(k)

2) a =int(‘input the item to be deleted’)


[Link](a)

3) m = int(input(‘lower limit’))
n = int(input(‘upper limit’))
n = n+1
L = [x for x in range(m, n) if x%2!=0]
4)
D={}
while Ture:
K = input(‘type a key’)
V = int(input(‘type the value’)
D[K] = V
C = input(‘type ‘y’ to add more’)

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 36
if C!=’y’:
break
5) flag = 0
L = eval(input(‘input a list on numbers’))
E = int(input(‘item to be searched’)
K =len(L)
for p in range(K):
if E ==L(p):
flag = 1
print(‘found and index is ‘,p)
if flag==0:
print(‘not found’)
6)
list1=[]
for x in range(10):
[Link](x**2)
list1
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
OR
list1=list(map(lambda x:x**2, range(10)))
7)
Statement 1 : StudentDict = dict( )
Statement 2 = for i in range( n ):
Statement 3: studentDict[rollno]=[name, physicsMarks, chemistryMarks, mathMarks]

KVS RO EKM - STUDENT SUPPORT MATERIAL (COMPUTER SCIENCE-083) FOR THE ACADEMIC YEAR 2022-23 37

You might also like