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

Revision Tour

Uploaded by

magevay740
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)
122 views

Revision Tour

Uploaded by

magevay740
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/ 49

Revision Tour -1

Data Types: Data Type specifies which type of value a variable can
store. type() function is
used to determine a variable's type in Python
Data Types In Python
1. Number
2. String
3. Boolean
4. List
5. Tuple
6. Set
7. Dictionary
Python tokens :
(1) keyword :
Keywords are reserved words. Each keyword has a specific meaning to
the Python interpreter, and we can use a keyword in our program only
for the purpose for which it has been defined. As Python is case
sensitive, keywords must be written exactly.
(2) Identifier: Identifiers are names used to identify a variable, function,
or other entities in a program. The rules for naming an identifier in
Python are as follows:
• The name should begin with an uppercase or a lowercase alphabet or
an underscore sign (_). This may be followed by any combination of
characters a–z, A–Z, 0–9 or underscore (_). Thus, an identifier cannot
start with a digit.
• It can be of any length. (However, it is preferred to keep it short and
meaningful).
It should not be a keyword or reserved word
• We cannot use special symbols like !, @, #, $, %, etc., in identifiers.
(3) Variables: A variable in a program is uniquely identified by a name
(identifier). Variable
in Python refers to an object — an item or element that is stored in the
memory.
Comments: Comments are used to add a remark or a note in the
source code. Comments are not executed by interpreter. a comment
starts with # (hash sign). Everything following the # till the end of that
line is treated as a comment and the interpreter simply ignores it while
executing the statement.
Mutable and immutable data types : Variables whose values can be
changed after they are created and assigned are called mutable.
Variables whose values cannot be changed after they are created and
assigned are called immutable.

(4) Operators: An operator is used to perform specific mathematical or


logical operation on values. The values that the operators work on are
called operands.
Arithmetic operators :four basic arithmetic operations as well as modular
division, floor
division and exponentiation. (+, -, *, /) and (%, //, **)
Relational operators : Relational operator compares the values of the
operands on its either side and determines the relationship among them.
==, != , > , < , <=, , >=
Logical operators : There are three logical operators supported by
Python. These operators (and, or, not) are to be written in lower case
only. The logical operator evaluates to either True or False based on the
logical operands on either side. and , or ,not
Assignment operator : Assignment operator assigns or changes the
value of the variable on its left. a=1+2 Augmented assignment operators
: += , -= , /= *= , //= %= , **=
Identity operators : is, is not
Membership operators : in, not in
Type Conversion:
The process of converting the value of one data type (integer, string,
float, etc.) to another data type is called type conversion.Python has two
types of type conversion.
Implicit Type Conversion /automatic type conversion
Explicit Type Conversion
CONTROL STATEMENTS
Control statements are used to control the flow of execution depending
upon the specified condition/logic.
There are three types of control statements:
1. Decision Making Statements (if, elif, else)
2. Iteration Statements (while and for Loops)
3. Jump Statements (break, continue, pass)
Questions and Answers
1 Mark questions
Q1. Which of the following is not considered a valid identifier in Python:
(i)three3 (ii)_main (iii)hello_kv1 (iv)2 thousand
Q2.Which of the following is the mutable data type in python:
(i)int (ii) string (iii)tuple (iv)list
Q3. Which of the following statement converts a tuple into a list in
Python:
(i) len(string) (ii)list(tuple) (iii)tup(list) (iv)dict(string)
Q4. The process of arranging array elements in a specified order is
termed as
i)indexing ii) slicing iii) sorting iv) traversing
Q5. What type of value is returned by input() function bydefault?
i)int ii)float iii)string iv)list
Q6. Which of the following operators cannot be used with string
(i) + ii) * iii) - iv) All of these
Q7. If L = [0.5 * x for x in range(0,4)] , L is
i)[0,1,2,3] ii)[0,1,2,3,4] iii) [0.0,0.5,1.0,1.5] iv) [0.0,0.5,1.0,1.5,2.0]
Q8. Write the output of the following python code:
x = 123
for i in x:
print(i)
i)1 2 3 ii) 123 iii)infinite loop iv) error
Q9. write the ouput of following code
A = 10/2
B = 10//3
print(A,B)
i)5,3.3 ii) 5.0 , 3.3 iii) 5.0 , 3 iv) 5,4
Q10. Name the built-in mathematical function / method that is used to
return square root
of a number.
i)SQRT() ii)sqrt() iii) sqt() iv) sqte()

2 MARK QUESTIONS
Q1. Find the following python expressions:
a) (3-10**2+99/11)
b) not 12 > 6 and 7 < 17 or not 12 < 4
c) 2 ** 3 ** 2
d) 7 // 5 + 8 * 2 / 4 – 3
Q2. i) Convert the following for loop into while loop
for i in range(10,20,5):
print(i)
ii) Evaluate:- not false and true or false and true
Q3. What are advantages of using local and global variables ?
Q4. Remove the errors from the following code Rewrite the code by
underlining the errors .
x = int((“enter the value”)
for i in range [0,11]:
if x = y
print x+y
else:
print x-y
Q5. Rewrite the following code in python after removing all syntax errors.
Underline each correction done in the code:
def func(x):
for i in (0,x):
if i%2 =0:
p=p+1
else if i%5= =0
q=q+2
else:
r=r+i
print(p,q,r)
func(15)
Q6. Write the output of the following code:-
String1="Coronavirus Disease"
print(String1.lstrip("Covid"))
print(String1.rstrip("sea"))
Q7. Write the ouput of the following code:-
Text = "gmail@com"
L=len(Text)
Ntext=""
for i in range(0,L):
if Text[i].isupper():
Ntext=Ntext+Text[i].lower()
elif Text[i].isalpha():
Ntext= Ntext+Text[i].upper()
else:
Ntext=Ntext+'bb'
print(Ntext)
Q8. L = [“abc”,[6,7,8],3,”mouse”]
Perform following operations on the above list L.
i)L[3:] ii) L[: : 2] iii)L[1:2] iv) L[1][1]
Q9.Write the output of the following:
word = 'green vegetables'
print(word.find('g',2))
print(word.find('veg',2))
print(word.find('tab',4,15))
3 MARK QUESTIONS
Q1. Write the python program to print the index of the character in a
string.
Example of string : “pythonProgram”
Expected output:
Current character p position at 0
Current character y position at 1
Current character t position at 2
Q2. Find and write the output of the following python code:
string1 = "Augmented Reality"
(i) print(string1[0:3]) (ii) print(string1[3:6]) (iii) print(string1[:7])
(iv) print(string1[-10:-3]) (v) print(string1[-7: :3]*3) (vi)
print(string1[1:12:2])
Q3. Find the output of the give program :
x = "abcdef"
j = "a"
for i in x:
print(j, end = " ")
Q4. Find output generated by the following code:
i=3
while i >= 0:
j=1
while j <= i:
print(j,end = ' ')
j=j+1
print()
i=i-1
Q5. Find output generated by the following code:
i=1
y = 65
while i<=5:
j=i
while j<=I:
print(chr(y),end=’ ‘)
j= j+1
y = y+1
print()
i=i+1
4 MARK QUESTIONS
Q1.Differentiate between break and continue statement used in python.
Q2What is comment in python ? Explain its significance.
Q3.Explain the types of errors occurring in python programming
language.
5 MARK QUESTIONS
Q1.Differentiate between type conversion and type casting in python
with examples.
Q2.Explain mutable and immutable objects in python with examples.
Q3. What is the use of else statement in for loop and in while loop ?
Explain.
ANSWERS
ANSWER OF 1 MARK QUESTIONS
1) (iv)
2) (iv)
3) (ii)
4) (iii)
5) (iii)
6) (iii)
7) (iii)
8) (iv)
9) (iii)
10) (ii)
ANSWER OF 2 MARK QUESTIONS
1) a) -88.0 b) True c)512 d)2.0
2) (i) i=10
while(i<20):
print(i)
i+=5
(i) true
3. Advantages of Local Variable
o The same name of a local variable can be used in different functions
as it is only recognized by the function in which it is declared.
o Local variables use memory only for the limited time when the function
is executed; after that same memory location can be reused.
Advantages of Global Variable
o Global variables can be accessed by all the functions present in the
program.
o Only a single declaration is required.
o Very useful if all the functions are accessing the same data.
4.
x = int(input(“enter the value”))
for y in range(0,11):
if x = = y:
print(x+y)
else:
print(x - y)
5. def func(x):
for i in range(0,x): Error 1
if i%2 ==0: Error 2
p=p+1
elif i%5= =0 Error 3
q=q+2
else:
r=r+i
print(p,q,r)
func(15)

6. ronavirus Disease
Coronavirus Di
7. GMAILbbCOM
8. I) [‘mouse’] ii) [‘abc’,3] iii)[ [ 6,7,8] ] iv) 7
9. 8
6
10

ANSWER FOR 3 MARK QUESTIONS


1) string1 = input("enter string")
for i in range(len(string1)):
print("current character",string1[i],"position at",i)
2) (i) Aug (ii) men (iii) Augment (iv)ed Real (v)RlyRlyRly (vi) umne e
3) aaaaaa
4) 1 2 3
12
1
5) A
BC
DEF
G H IJ
KLMNO
ANSWER FOR 4 MARK QUESTIONS
1) The break statement terminates the current loop , i.e the loop in which
it appears, and resumes execution at the next statement immediately
after the end of that loop.if break statement is inside a nested loop(loop
inside another loop), break will terminate the innermost loop.
When a continue statement is encountered, the control jumps to the
beginning of the loop for next iteration, thus skipping the execution of
statements inside the body of loop for the current iteration. As usual, the
loop condition is checked to see if the loop should continue further or
terminate. If the condition of the loop is entered again, else the control is
transferred to the statement immediately following the loop.
2) Comments in Python are identified with a hash symbol, #, and extend
to the end of the line. Hash characters in a string are not considered
comments, however. There are three ways to
write a comment - as a separate line, beside the corresponding
statement of code, or as a multi-line comment block.
here are multiple uses of writing comments in Python. Some significant
uses include:
Increasing readability
Explaining the code to others
Understanding the code easily after a long-term
Including resources
Re-using the existing code
3. There are three types of Python errors.
1. Syntax errors
Syntax errors 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.
2.Logical errors
These are the most difficult type of error to find, because they will give
unpredictable results and may crash your program. A lot of different
things can happen if you have a logic error.
3.Run time errors
Run time errors arise when the python knows what to do with a piece of
code but is unable to perform the action. Since Python is an interpreted
language, these errors will not occur until the flow of control in your
program reaches the line with the problem. Common example of runtime
errors are using an undefined variable or mistyped the variable name.
ANSWER FOR 5 MARK QUESTIONS
1.Type Conversion
In type conversion, the python interpreter automatically converts one
data type to another. Since Python handles the implicit data type
conversion, the programmer does not have to convert the data type into
another type explicitly.
The data type to which the conversion happens is called the destination
data type, and the data type from which the conversion happens is
called the source data type.
x = 20
y = 25.5
Z=x+y
Here value in z, int type is converted to float type
Type Casting
n type casting, the programmer has to change the data type as per their
requirement manually. In this, the programmer explicitly converts the
data type using predefined functions like int(), float(), str(), etc. There is a
chance of data loss in this case if a particular data type is converted to
another data type of a smaller size.
x = 25
float(x)
It converts into float type
2.Mutable in Python can be defined as the object that can change or be
regarded as something changeable in nature. Mutable means the ability
to modify or edit a value.
Mutable objects in Python enable the programmers to have objects that
can change their values. They generally are utilized to store a collection
of data. It can be regarded as something that has mutated, and the
internal state applicable within an object has changed.
Immutable objects in Python can be defined as objects that do not
change their values and attributes over time. These objects become
permanent once created and initialized, and they form a critical part of
data structures used in Python.
Python is used in numbers, tuples, strings, frozen sets, and user-defined
classes with some exceptions. They cannot change, and their values
and it remains permanent once they are initialized and hence called
immutable.
3. Else with loop is used with both while and for loop. The else block is
executed at the end of loop means when the given loop condition is false
then the else block is executed.
i=0
while i<5:
i+=1
print("i =",i)
else:
print("else block is executed")
Explanation
declare i=0
we know then while loop is active until the given condition is true. and
we check i<5 it’s true till the value of i is 4.
i+=1 increment of i because we don’t want to execute the while loop
infinite times.
print the value of i
else block executed when the value of i is 5.
l = [1, 2, 3, 4, 5]
for a in l:
print(a)
else:
print("else block is executed")
Explanation
declare a list l=[1,2,3,4,5]
for loop print a.
else block is executed when the for loop is read last element of list.
In type conversion, the destination data of a smaller size is converted to
the source data type of larger size. This avoids the loss of data and
makes the conversion safe to use.

STRINGS
A sequence of characters is called a string. Strings are used by
programming languages to manipulate text such as words and
sentences.
Strings literal in Python are enclosed by double quotes or single quotes.
String literals can span multiple lines, to write these strings triple quotes
are used.
>>> a = ‘’’ Python
Programming
Language’’’
Empty string can also be created in Python .
>>> str = ‘ ‘
Accessing values in Strings:
Each individual character in a string can be assessed using a technique
called indexing .
Python allows both positive and negative indexing.
S = “Python Language”
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
PythonLanguage
-15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
>>> S[7]
L
Deleting a String
>>>S[-10]
n
As we know, strings are immutable, so we cannot delete or remove the
characters from the string but we can delete entire string using del
keyword.
>>> strl = " WELCOME "
>>> del strl
>>> print ( str1 )
NameError : name ' strl ' is not defined .
String Slicing
To access some part of a string or substring, we use a method called
slicing.
Syntax: string_name[start : stop]
>>> str1 = " Python Program "
>>> print ( str1[ 3: 8])
hon P
>>> print ( str1 [ : -4 ] )
Python Pro
>>> print ( strl [ 5 : ] )
n Program
Strings also provide slice steps which used to extract characters from
string that are not consecutive. Syntax string_name [ start : stop : step ]
>>> print ( stri [ 2 : 12 : 3 ] )
tnrr
We can also print all characters of string in reverse order using [ ::-1 ]
>>> print ( strl [ :: - 1 ] )
margorP nohtyP
Traversing a String
1. Using ' for’ loop: for loop can iterate over the elements of a sequence
or string . It is used when you want to traverse all characters of a string.
eg.
>>> sub = " GOOD "
>>> for i in subs:
print ( i )
Output:
G
O
O
D

2. Using ' for ' loop with range


>>> sub = " COMPUTER "
>>> for i in range ( len ( sub ) ) :
print ( sub [ i ], ‘-’, end = ‘ ‘)
Output: Output C - O - M - P - U - T - E - R
String Operations
Concatenation
To concatenate means to join. Python allows us to join two strings using
the concatenation operator plus which is denoted by symbol +.
>>> str1 = 'Hello' #First string
>>> str2 = 'World!' #Second string
>>> str1 + str2 #Concatenated strings 'HelloWorld!'
String Replication Operator ( * )
Python allows us to repeat the given string using repetition operator
which is denoted by symbol (*) .
>>> a = 2 * " Hello "
>>> print ( a )
HelloHello
Comparison Operators
Python string comparison can be performed using comparison operators
( == , > , < , , < = , >
= ) . These operators are as follows
>>> a = ' python ' < ' program '
>>> print ( a )
False
>>> a = ' Python '
>>> b = ' PYTHON "
>>> a > b
True
Membership Operators are used to find out whether a value is a member
of a string or not .
(i) in Operator:
>>> a = "Python Programming Language"
>>> "Programming" in a
True
(ii) not in Operator:
>>> a = "Python Programming Language"
>>> "Java" not in a
True
BUILT IN STRING METHODS
LIST
List is an ordered sequence, which is used to store multiple data at the
same time. List contains a sequence of heterogeneous elements. Each
element of a list is assigned a number to its position or index. The first
index is 0 (zero), the second index is 1 , the third index is 2 and so on .
Creating a List In Python,
a = [ 34 , 76 , 11,98 ]
b=['s',3,6,'t']
d=[]
Creating List From an Existing Sequence: list ( ) method is used to
create list from an existing sequence .
Syntax: new_list_name = list ( sequence / string )
You can also create an empty list . eg . a = list ( ) .
Similarity between List and String
• len ( ) function is used to return the number of items in both list and
string .
• Membership operators as in and not in are same in list as well as string
.• Concatenation and replication operations are also same done in list
and string.
Difference between String and List
Strings are immutable which means the values provided to them will not
change in the program. Lists are mutable which means the values of list
can be changed at any time.
Accessing Lists
To access the list's elements, index number is used.
S = [12,4,66,7,8,97,”computer”,5.5,]
>>> S[5]
97
>>>S[-2]
Computer
Traversing a List
Traversing a list is a technique to access an individual element of that
list.
1. Use for loop when you want to traverse each element of a list.
>>> a = [‘p’,’r’,’o’,’g’,’r’,’a’,’m’]
>>> for x in a:
print(x, end = ‘ ‘)
output : p r o g r a m
2. Using for loop with range( )
>>> a = [‘p’,’r’,’o’,’g’,’r’,’a’,’m’]
>>> for x in range(len(a)):
print(x, end = ‘ ‘)
output : p r o g r a m
List Operations
1. Concatenate Lists
List concatenation is the technique of combining two lists . The use of +
operator can easily add the whole of one list to other list . Syntax list list1
+ list2 e.g.
2. Replicating List
Elements of the list can be replicated using * operator .
Syntax list = listl * digit e.g. >>> L1 = [ 3 , 2 , 6 ]
>>> L = L1 * 2
>>> L [ 3 , 2 , 6 , 3 , 2 , 6 ]
>>> L1 = [ 43, 56 , 34 ]
>>> L2 = [ 22 , 34 , 98 ]
>>> L = L1 + L2
>>> L [ 43, 56, 34, 22 , 34 , 98 ]
3. Slicing of a List: List slicing refers to access a specific portion or a
subset of the list for some operation while the original list remains
unaffected .
Syntax:- list_name [ start: end ]
>>> List1 = [ 4 , 3 , 7 , 6 , 4 , 9 ,5,0,3 , 2]
>>> S = List1[ 2 : 5 ]
>>> S
[ 7, 6, 4 ]
Syntax: list_name [ start: stop : step ]
>>> List1 = [ 4 , 3 , 7 , 6 , 4 , 9 ,5,0,3 , 2]
>>> S = List1[ 1 : 9 : 3 ]
>>> S
[ 3, 4, 0 ]
List Manipulation
Updating Elements in a List
List can be modified after it is created using slicing e.g.
>>> l1= [ 2 , 4, " Try " , 54, " Again " ]
>>> l1[ 0 : 2 ] = [ 34, " Hello " ]
>>> l1
[34, ' Hello ', ' Try ', 54, ' Again ']
>>> l1[ 4 ] = [ "World " ]
>>> l1
[34, ' Hello ', ' Try ', 54, ['World ']]
Deleting Elements from a List
del keyword is used to delete the elements from the list .
Syntax:-
del list_name [ index ] # to delete individual element:
>>> list1 = [ 2.5 , 4 , 7 , 7 , 7 , 8 , 90 ]
>>> del list1[3]
>>> list1
[2.5, 4, 7, 7, 8, 90]
del 11st_name [ start : stop ] # to delete elements in list slice e.g.
>>> del list1[2:4]
>>> list1
[2.5, 4, 8, 90]
TUPLES
A tuple is an ordered sequence of elements of different data types. Tuple
holds a sequence of heterogeneous elements, it store a fixed set of
elements and do not allow changes
Tuple vs List
Elements of a tuple are immutable whereas elements of a list are
mutable.
Tuples are declared in parentheses ( ) while lists are declared in square
brackets [ ].
Iterating over the elements of a tuple is faster compared to iterating over
a list.
Creating a Tuple
To create a tuple in Python, the elements are kept in parentheses ( ),
separated by commas.
a = ( 34 , 76 , 12 , 90 )
b=('s',3,6,'a')
Accessing tuple elements, Traversing a tuple, Concatenation of tuples,
Replication of tuples and slicing of tuples works same as that of List.
DICTIONARY
Dictionary is an unordered collection of data values that store the key :
value pair instead of single value as an element . Keys of a dictionary
must be unique and of immutable data types such as strings, tuples etc.
Dictionaries are also called mappings or hashes or associative arrays.
Creating a Dictionary
To create a dictionary in Python, key value pair is used .
Dictionary is list in curly brackets , inside these curly brackets , keys and
values are declared .
Syntax dictionary_name = { key1 : valuel , key2 : value2 ... }
Each key is separated from its value by a colon ( :) while each element
is separated by commas .
>>> Employees = { " Abhi " : " Manger " , " Manish " : " Project Manager "
, " Aasha " : "Analyst " , " Deepak " : " Programmer " , " Ishika " : " Tester
"}

Accessing elements from a Dictionary


Syntax: dictionary_name[keys]
>>> Employees[' Aasha ']
' Analyst '
Traversing a Dictionary
1. Iterate through all keys
>>> for i in Employees:
print(i)
Output:
Abhi
Manish
Aasha
Deepak
Ishika
2. Iterate through all values
>>> for i in Employees:
print(Employees[i])
Output:
Manger
Project Manager
Analyst
Programmer
Tester
3. Iterate through key and values
>>> for i in Employees:
print(i, " : ", Employees[i])
Output:
Abhi : Manger
Manish : Project Manager
Aasha : Analyst
Deepak : Programmer
Ishika : Tester
4, Iterate through key and values simultaneously
>>> for a,b in Employees.items():
print("Key = ",a," and respective value = ",b)
Output:
Key = Abhi and respective value = Manger
Key = Manish and respective value = Project Manager
Key = Aasha and respective value = Analyst
Key = Deepak and respective value = Programmer
Key = Ishika and respective value = Tester
Adding elements to a Dictionary
Syntax: dictionary_name[new_key] = value
>> Employees['Neha'] = "HR"
>>> Employees
{' Abhi ': ' Manger ', ' Manish ': ' Project Manager ', ' Aasha ': ' Analyst ', '
Deepak ': 'Programmer ', ' Ishika ': ' Tester ', 'Neha': 'HR'}
Updating elements in a Dictionary
Syntax: dictionary_name[existing_key] = value
>>> Employees['Neha'] = " Progammer "
>>> Employees
{' Abhi ': ' Manger ', ' Manish ': ' Project Manager ', ' Aasha ': ' Analyst ', '
Deepak ': 'Programmer ', ' Ishika ': ' Tester ', 'Neha': ' Progammer '}

Membership operators in Dictionary


Two membership operators are in and not in. The membership operator
in checks if the key is present in the dictionary.
>>> " Ishika " in Employees
True
>>> ' HR ' not in Employees
True
QUESTIONS:
1 MARK QUESTIONS
1. What will be the output of the following set of commands
>>> str = "hello"
>>> str[:2]
a. lo b. he c. llo d. el
2. Which type of object is given below
>>> L = 1,23,"hello",1
a. list b. dictionary c. array d. tuple
3. Which operator tells whether an element is present in a sequence or
not
a. exist b. in c. into d. inside
4. Suppose a tuple T is declared as T = (10,12,43,39), which of the
following is incorrect
a. print(T[1]) b. T[2] = -2 c. print(max(T)) d. print(len(T))
5. Which index number is used to represent the last character of a string
a. -1 b. 1 c. n d. n – 1
6. Which function returns the occurrence of a given element in a list?
a. len() b. sum() c. extend() d. count()
7. which type of slicing is used to print the elements of a tuple in reverse
order
a. [:-1] b. [: : -1] c. [1 : :] d. [: : 1]
8. Dictionaries are also called
a. mapping b. hashes c. associative array d. all of these
9. Which function returns the value of a given key, if present, from a
dictionary?
a. items() b. get() c. clear() d. keys()
10. The return type of input() function is:
a. list b. integer c. string d. tuple
2 MARKS QUESTIONS
Q1. Rewrite the following code in python after removing all syntax
error(s). Underline each
correction done in the code.
STRING=""WELCOME
NOTE""
for S in range[0,8]:
print (STRING(S))
Q2. Find output generated by the following code:
Str=”Computer”
Str=Str[-4:]
print(Str*2)
Q3. What will be the output of the following question
L = [10,19,45,77,10,22,2]
i) L.sort() ii) max(L)
print(L)
Q4. Find the output
L = [10,19,45,77,10,22,2]
i) L[3:5] ii) L[: : -2]
Q5. Distinguish between list and tuple.
Q6. Read the code given below and show the keys and values
separately.
D = {‘one’ : 1, ‘two’ : 2, ‘three’ : 3}
Q7. Observe the given list and answer the question that follows.
List1 = [23,45,63, ‘hello’, 20, ‘world’,15,18]
i) list1[-3] ii) list1[3]
Q8. Assertion (A) :
s = [11, 12, 13, 14]
s[1] = 15
Reasoning (R) : List is immutable.
(A) Both A and R are true and R is the correct explanation of assertion.
(B) A and R both are true but R is not the correct explanation of A .
(C) A is true, R is false.
(D) A is false, R is true.
Q9. a=(1,2,3)
a[0]=4
Assertion: The above code will result in error
Reason: Tuples are immutable. So we can’t change them.
(A) Both Assertion and reason are true and reason is correct explanation
of assertion.
(B) Assertion and reason both are true but reason is not the correct
explanation of assertion.
(C) Assertion is true, reason is false.
(D) Assertion is false, reason is true.

2 MARKS ANSWERS
Q1. CORRECTED CODE:-
STRING= "WELCOME"
NOTE=" "
for S in range (0, 7) :
print (STRING [S])
Also range (0,8) will give a runtime error as the index is out of range. It
should be range(0,7)
Q2. uteruter
Q3. [2, 10, 10, 19, 22, 45, 77]
Q4. [77, 10]
[2, 10, 45, 10]
Q5.

Q6.
Keys: ‘one’, ‘two’, ‘three’
Values: 1,2,3
Q7.
‘world’
‘hello’

Q8. (C)
Q9. (A)

3 MARKS QUESTIONS
Q1. Which of the string built in methods are used in following conditions?
ii)Returns the length of a string
iii)Removes all leading whitespaces in string
iv) Returns the minimum alphabetic character from a string
Q2. Write a program to remove all the characters of odd index value in a
string
Q3. Write a python program to count the frequencies of each elements
of a list using dictionary
Q4. what will be the output of the following python code
L = [10,20]
L1 = [30,40]
L2 = [50,60]
L.append(L1)
print(L)
L.extend(L2)
print(L)
print(len(L)
Q5. Find the output of the given question
t = (4,0,’hello’,90,’two’,(‘one’,45),34,2)
i) t[5]
ii) t[3:7]
iii) t[1] + t[-2]

3MARKS ANSWERS
Q1. i) len() ii) lstrip() iii)min()
Q2. str = input("Enter a string \n")
final =" "
for i in range(len(str)):
if (i%2 == 0):
final = final + str[i]
print("The removed odd index characters:", final)
Q3. def CountFreq(li):
freq = {}
for item in li:
if (item in freq):
freq[item] += 1
else:
freq[item] = 1
print(freq)
li =[1, 1, 3, 2, 6, 5, 3, 1, 3, 3, 1, 4, 6, 4, 4, 2, 2, 2, 2]
CountFreq(li)
Output: {1: 4, 3: 4, 2: 5, 6: 2, 5: 1, 4: 3}
Q4. [10, 20, [30, 40]]
[10, 20, [30, 40], 50, 60]
5
Q5. ('one', 45)
(90, 'two', ('one', 45), 34)
34

4 marks questions
Q1. Find the output
i) 'python'.capitalize()
ii) max('12321')
iii) 'python'.index('ho')
iv) 'python'.endswith('thon')
Q2. Consider the following code and answer the question that follows.
book = {1:'Thriller',2:'Mystery',3:'Crime',4:'Children Stories'}
library = {5:'Madras Diaries',6:'Malgudi Days'}
v)Ramesh wants to change the book ‘Crime’ to ‘Crime Thriller’. He has
written the following code:
book['Crime'] = 'Crime Thriller'
but he is not getting the answer. Help him to write the correct command.
vi)Ramesh wants to merge the dictionary book with the dictionary library.
Help him to write the command.
Q3. Write the suitable method names for the conditions given below:
i) Add an element at the end of the list
ii) Return the index of first occurrence of an element
iii) Add the content of list2 at the end of list1
iv) Arrange the elements of a list1 in descending order
4 MARKS ANSWERS
Q1.
i) 'Python' ii) '3' iii) 3 iv) True
Q2. i) book[3] = 'Crime Thriller'
ii) library.update(book)
Q3. list1=[2,1,8,5,6,2,3]
list1.sort(reverse=True)
list1
5 MARKS QUESTIONS
Q1. Find the output of the following code:
a = (5,(7,5,(1,2)),5,4)
print(a.count(5))
print(a[1][2])
print(a * 3)
print(len(a))
b = (7,8,(4,5))
print(a + b)
Q2. Explain the following string functions with examples.
i) title() ii) count( ) iii) find() iv) index() v) join()
5 MARKS ANSWERS
Q1: 2
(1, 2)
(5, (7, 5, (1, 2)), 5, 4, 5, (7, 5, (1, 2)), 5, 4, 5, (7, 5, (1, 2)), 5, 4)
4
(5, (7, 5, (1, 2)), 5, 4, 7, 8, (4, 5))
Q2. i) title()
Returns the string with first letter of every word in the string in
uppercase and rest in lowercase.
>>> str1 = 'hello WORLD!'
>>> str1.title()
'Hello World!'
ii) count( )
Returns number of times substring str occurs in the given string. If we do
not give start index and end index then searching starts from index 0
and ends at length of the string.
>>> str1 = 'Hello World! Hello Hello'
>>> str1.count('Hello',12,25)
2
>>> str1.count('Hello')
3
iii) find()
Returns the first occurrence of index of substring str occurring in the
given string. If we do not give start and end then searching starts from
index 0 and ends at length of the string. If the substring is not present in
the given string, then the function returns -1
>>>str1= 'Hello World! Hello Hello'
>>> str1.find('Hello',10,20)
13
>>> str1.find('Hello',15,25)
19
>>> str1.find('Hello')
0
>>> str1.find('Hee')
-1
iv) index( )
Same as find() but raises an exception if the substring is not present in
the given string
>>> str1 = 'Hello World! Hello Hello'
>>> str1.index('Hello')
0
>>> str1.index('Hee')
ValueError: substring not found
v) join()
Returns a string in which the characters in the string have been joined
by a separator
>>> str1 = ('HelloWorld!')
>>> str2 = '-' #separator
>>> str2.join(str1)
'H-e-l-l-o-W-o-r-l-d-!'

FUNCTION IN PYTHON
Functions: types of function (built-in functions, functions defined in
module, user defined functions), creating user defined function,
arguments and parameters, default parameters, positional parameters,
function returning value(s), flow of execution, scope of a variable (global
scope, local scope)
Let us revise
A function is a block of code that performs a specific task.
Advantages of function: Reusability of code, Reduce size of code,
minimum number of statements, minimum storage, Easy to manage and
maintain
Types of functions: Built-in-functions, Functions defined in module,
User defined function
Built-in functions are the functions whose functionality is pre-defined in
python like abs(), eval(), input(), print(), pow()
Some functions are defined inside the module like load() and dump()
function defined inside the pickle module.
A function that can be defined by the user is known as user defined
function.
def keyword is used to define a function.
There is a colon at the end of def line, meaning it requires block
User Defined function involved two steps:
defining
calling
Syntax for user defined function:
def <function name>( [parameter list ]):
[””function’s doc string ””]
<statement>
[<statement>]
Python supports three types of formal arguments/ parameters:
Positional Arguments,
Default parameters, Keyword (or named) Arguments
Positional Arguments: When the function call statement must match
the number and order of arguments as defined in the function definition,
this is called the positional argument matching.
A parameter having default value in the function header is known as a
default parameter.
Keyword Arguments are the named arguments with assigned values
being passed in the function call statement.
A function may or may not return one or more values.
A function that does not return a value is known as void function and
returns legal empty value None.
Functions returning value are also known as fruitful functions.
The flow of execution refers to the order in which statements are
executed during a program.
A variable declared in a function body (block) is said to have local
scope. i.e. it can be accessed within this function.
A variable declared outside of all functions/top level of segment of a
program is said to have global scope. i.e. it can be accessible in whole
program and all block functions and the other blocks contained within
program.
Multiple Choice Questions (1 Mark)
1. What is the default return value for a function that does not return any
value explicitly?
(a) None (b) int (c) double (d) null
2. Which of the following items are present in the function header?
(a) Function name only (b) Parameter list only
(c) Both function name and parameter list (d) return value
3. Which of the following keyword marks the beginning of the function
block?
(a) func (b) define (c) def (d) function
4. Pick one of the following statements to correctly complete the function
body in the given code snippet.
def f(number):
# Missing function body
print (f(5))
(a) return “number” (b) print(number) (c) print(“number”) (d) return
number
5. Which of the following function header is correct?
(a) def f(a=1,b): (b) def f(a=1,b,c=2):
(c) def f(a=1, b=1, c=2): (d) def f(a=1,b=1,c=2,d);
6. Which of the following statements is not true for parameter passing to
functions?
(a) You can pass positional arguments in any order.
(b) You can pass keyword arguments in any order.
(c) You can call a function with positional and keyword arguments.
(d) Positional arguments must be before keyword arguments in a
function call
7. A variable defined outside all the functions referred to as………..
(a) A static variable (b)A global variable (c) A local variable (d) An
automatic variable
8. What is the order of resolving scope of a name in a python program?
(L: Local namespace, E: Enclosing namespace, B: Built-In namespace,
G: Global namespace)
(a) BGEL (b) LEGB (c) GEBL (d) LBEG
9. Assertion (A):- If the arguments in a function call statement match the
number and order of arguments as defined in the function definition,
such arguments are called positional arguments.
Reasoning (R):- During a function call, the argument list first contains
default argument(s) followed by positional argument(s).
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
10. The .........................refers to the order in which statements are
executed during a program run.
(a) Token (b) Flow of execution (c) Iteration (d) All of the above
11. Choose the correct option:
Statement1: Local Variables are accessible only within a function or
block in which it is declared.
Statement2: Global variables are accessible in the whole program.
(a) Statement1 is correct but Statement2 is incorrect
(b) Statement2 is correct but Statement1 is incorrect
(c) Both Statements are Correct
(d) Both Statements are incorrect
12. The ............................of a variable is the area of the program where
it may be referenced
a) external b) global c) scope d) local
ANSWERS FOR 1 MARK QUESTIONS

Short Questions (2 Marks)


Q1. What do you mean by a function? How is it useful?
Answer: A function is a block of code that performs a specific task.
Functions are useful
as they can be reused anywhere through their function call statements.
Q2. Observe the following Python code very carefully and rewrite it after
removing all
syntactical errors with each correction underlined.
def execmain():
x = input("Enter a number:")
if (abs(x)= x):
print("You entered a positive number")
else:
x=*-1
print("Number made positive : ",x)
execmain()
Answer:
def execmain():
x = int(input("Enter a number:"))
if (abs(x)== x):
print("You entered a positive number")
else:
x*=-1
print("Number made positive : ",x)
execmain()

Q3. What is an argument? Give an example.


Answer: An argument is data passed to a function through function call
statement. It is also called actual argument or actual parameter. For
example, in the statement print(math.sqrt(25)), the integer 25 is an
argument.

Q4. What is the output of the program given below?


x = 75
def func (x) :
x = 10
func (x)
print ('x is now', x)

Answer: x is now 75

Q5. What will be the output of the following code:

total=0
def add(a,b):
global total
total=a+b
print(total)
add(6,6)
print(total)

Answer: 12
12

Q6. Is return statement optional? Compare and comment on the


following two return statements:
(i) return
(ii) return val

Answer: The return statement is optional only when the function does
not return a value. A function that returns a value must have at least one
return statement.
From the given two return statements,
(i) The statement return is not returning any value. Rather it returns the
control to caller along with empty value None.
(ii) The statement return val is returning the control to caller along with
the value contained in variable val.

Q7. Divyansh, a python programmer, is working on a project which


requires him to define a function with name CalculateInterest(). He
defines it as:
def CalculateInterest(Principal,Rate=.06, Time): # Code
But this code is not working, Can you help Divyansh to identify the error
in the above function and with the solution?

Answer. Yes, here non-default argument is followed by default argument


which is wrong as per python’s syntax. (while passing default arguments
to a function ,all the arguments to its right must also have default values,
otherwise it will result in an error.)

Q8. Write a function that takes a positive integer and returns the one’s
position digit of the integer.

Answer:
def getOnes(num):
oneDigit=num%10 # return the ones digit of the integer num
print(oneDigit)
return(oneDigit)
getOnes(11)

Q9. Anita has written a code to input a number and check whether it is
prime or not. Her code is having errors. Rewrite the correct code and
underline the corrections made.
def prime():
n=int(input("Enter number to check :: ")
for i in range (2, n//2):
if n%i=0:
print("Number is not prime \n")
break
else:
print("Number is prime \n’)

Answer:
def prime():
n=int(input("Enter number to check :: ")) #bracket missing
for i in range (2, n//2):
if n%i==0: # = missing
print("Number is not prime \n")
break #wrong indent
else:
print("Number is prime \n”) # quote mismatch

Q10. What is the difference between parameter and argument?


Answer:
Parameters are temporary variable names within functions. The
argument can be thought of as the value that is assigned to that
temporary variable.
For instance, let’s consider the following simple function to calculate sum
of two numbers.
def sum(a,b):
return a+b
sum(10,20)
Here a, b are the parameters for the function ‘sum’. Arguments are used
in procedure calls, i.e., the values passed to the function at runtime.10,
20 are the arguments for the function sum.

Q11. What is the significance of having functions in a program?


Answer: Creating functions in programs is very useful. It offers the
following advantages:
(i) The program is easier to understand.
(ii) Redundant code is at one place, so making changes is easier.
(iii) Reusable functions can be put in a library in modules.
Q12. What is the difference between local variable and global variable?
Also give a suitable Python code to illustrate both.

Answer:
Local Variable Global Variable
It is a variable which is declared It is a variable which is declared
within a function or within a block. outside all the functions or in a
global space.
It cannot be accessed outside the It is accessible throughout the
function but only within a program in which it is declared.
function/block of a program.

For example, in the following code x, xcubed are global variables and n
and cn are local variables.
def cube(n): # n and cn are local variables
cn=n*n*n
return cn
x=10 # x is a global variable
xcubed=cube(x) # xcubed is a global variable
print(x, “Cubed 15”, xcubed)

Short Questions (3 Marks)

Q1. Which line in the given code(s) will not work and why?
def interest(p,r,t=7):
I=(p*r*t)
print(interest(20000,.08,15)) #line 1
print(interest(t=10, 20000, 0.75)) #line 2
print(interest(50000, 0.7)) #line 3
print(interest(p=10000,r=.06,time=8)) #line 4
print(interest(80000, t=10)) #line 5

Answer: Line 2: positional argument must not be followed by keyword


argument, i.e.,positional argument must appear before a keyword
argument.
Line 4: There is no keyword argument with name ‘time’
Line 5: Missing value for positional arguments, R.

Q2. Write a python function showlarge() that accepts a string as


parameter and prints the words whose length is more than 4 characters.
Eg: if the given string is “My life is for serving my Country”
The output should be
serving
Country

Answer:
def showlarge(s):
l = s.split()
for x in l:
if len(x)>4:
print(x)
s=" My life is for serving my Country "
showlarge(s)

Q3. Write a function Interchange (num) in Python, which accepts a list


num of integers, and interchanges the adjacent elements of the list and
print the modified list as shown below:
(Number of elements in the list is assumed as even)
Original List: num = [5,7,9,11,13,15]
After Rearrangement num = [7,5,11,9,15,13]

Answer:
def Interchange(num):
for i in range(0,n,2):
num[i], num[i+1] = num[i+1], num[i]
print(num)
num=[5,7,9,11,13,15]
n=len(num)
if n%2==0:
Interchange(num)

Q4. Write a function INDEX_LIST(L), where L is the list of elements


passed as argument to the function. The function returns another list
named ‘indexList’ that stores the indices of all Non-Zero Elements of L.
For example:
If L contains [12, 4, 0, 11,0, 56]
The indexList will have - [0,1,3,5]
Answer:
L=[12,4,0,11,0,56]
def INDEX_LIST(L):
indexList=[]
for i in range(len(L)):
if L[i]!=0:
indexList.append(i)
print(indexList)
return indexList
INDEX_LIST(L)

You might also like