Revision Tour
Revision Tour
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.
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
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 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
Answer: x is now 75
total=0
def add(a,b):
global total
total=a+b
print(total)
add(6,6)
print(total)
Answer: 12
12
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.
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
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)
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:
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)
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)