Sei sulla pagina 1di 33

www.surabooks.

com This material only for sample


Namma Kalvi www.surabooks.com

UNIT-II
 CORE PYTHON

www.nammakalvi.org

Chapter

5
PYTHON-VARIABLES AND OPERATORS
CHAPTER SNAPSHOT
5.1 Introduction 5.7 Tokens
5.2 Key features of Python 5.7.1. Identifiers
5.3 Programming in Python 5.7.2. Keywords

ns
5.3.1 Interactive mode Programming 5.7.3 Operators
5.3.2 Script mode Programming 5.7.4 Delimiters
5.7.5 Literals

io
5.4 Input and Output Functions
5.4.1 The print() function 5.8 Python Data types
5.8.1 Number Data type
5.4.2 input() function
at 5.8.2 Boolean Data type
5.5 Comments in Python
5.8.3 String Data type
ic
5.6 Indentation

Evaluation
bl
Pu

4. Which of the following character is used to give


Part - I comments in Python Program?
Choose the best answer  (1 mark) (a) # (b) & (c) @ (d) $
ra

1. Who developed Python?  [Ans. (a) #]


(a) Ritche 5. This symbol is used to print more than one item
Su

(b) Guido Van Rossum on a single line.


(c) Bill Gates (a) Semicolon (;) (b) Dollor ($)
(d) Sunder Pitchai (c) comma (,) (d) Colon (:)
 [Ans. (b) Guido Van Rossum]  [Ans. (c) comma (,)]
2. The Python prompt indicates that Interpreter 6. Which of the following is not a token?
is ready to accept instruction. (a) Interpreter (b) Identifiers
(a) >>> (b) <<< (c) # (d) << (c) Keyword (d) Operators
 [Ans. (a) >>>]  [Ans. (a) Interpreter]
3. Which of the following shortcut is used to 7. Which of the following is not a Keyword in
create new Python Program? Python?
(a) Ctrl + C (b) Ctrl + F (a) break (b) while
(c) Ctrl + B (d) Ctrl + N (c) continue (d) operators
 [Ans. (d) Ctrl + N]  [Ans. (d) operator]

[45]

orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757


Unit II - Chapter 5
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


8. Which operator is also called as Comparative
operator?
 
This material only for sample www.surabooks.com

www.nammakalvi.org
4. What is a literal? Explain the types of literals?
Ans. Literal is a raw data given in a variable or
(a) Arithmetic (b) Relational constant. In Python, there are various types of
(c) Logical (d) Assignment literals.
 [Ans. (b) Relational] (i) Numeric
9. Which of the following is not Logical operator? (ii) String
(a) and (b) or (iii) Boolean
(c) not (d) Assignment
 [Ans. (d) Assignment] 5. Write short notes on Exponent data?
10. Which operator is also called as Conditional Ans. An Exponent data contains decimal digit part,
operator? decimal point, exponent part followed by one or
(a) Ternary (b) Relational more digits.
Example: 12.E04, 24.e04.
(c) Logical (d) Assignment
 [Ans. (a) Ternary]
Part - III

ns
Answer the following questions
Part - II
Answer the following questions  (3 marks)

io
 (2 marks) 1. Write short notes on Arithmetic operator with
at examples.
1. What are the different modes that can be used
Ans. (i) An arithmetic operator is a mathematical
to test Python Program?
ic
operator that takes two operands and
Ans. The modes that can be used to test Python performs a calculation on them. They are
bl

program are used for simple arithmetic.


(i) Interactive mode (ii) Most computer languages contain a set
Pu

(ii) Script mode of such operators that can be used within


2. Write short notes on Tokens. equations to perform different types of
Ans. Python breaks each logical line into a sequence sequential calculations.
ra

of elementary lexical components known as (iii) Python supports the following Arithmetic
Tokens. The normal token types are operators.
Su

(i) Identifiers, Operator – Examples Result


(ii) Keywords, Operation
(iii) Operators, Assume a=100 and b=10. Evaluate the
(iv) Delimiters and following expressions
(v) Literals. + (Addition) >>> a + b 110
3. What are the different operators that can be – (Subtraction) >>> a – b 90
used in Python? * (Multiplication) >>> a * b 1000
Ans. The operators that can be used in Python / (Division) >>> a / b 10.0
(i) Arithmetic operators % (Modulus) >>> a % 30 10
(ii) Relational or Comparative operator ** (Exponent) >>> a ** 2 10000
(iii) Logical operators // (Floor Division) >>> a // 3
(iv) Assignment operators 30 (Integer
Division)
(v) Conditional operator

46
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

2. What are the assignment operators that can be


used in Python?
Sura’s
www.surabooks.com

➠ XII Std - Computer Science


(ii) A character literal is a single character
surrounded by single or double quotes. The

Python - Variables and Operators


Ans. (i) In Python, = is a simple assignment value with triple-quote "' '" is used to give
operator to assign values to variable. Let a multi-line string literal.
= 5 and b = 10 assigns the value 5 to a and To test String Literals :
10 to b these two assignment statement can # Demo Program to test String Literals
also be given as a,b=5,10 that assigns the strings = "This is Python"
value 5 and 10 on the right to the variables char = "C"
a and b respectively. multiline_str = "'This is a multiline string
(ii) There are various compound operators in with more than one line code."'
Python like +=, -=, *=, /=, %=, **= and //= print (strings)
are also available. print (char)
3. Explain Ternary operator with examples. print (multiline_str)
Ans. (i) Ternary operator is also known as # End of the Program
conditional operator that evaluate Output:

ns
something based on a condition being true This is Python
or false. C

io
(ii) It simply allows testing a condition in a This is a multiline string with more than
single line replacing the multiline if-else at one line code.
making the code compact.
Variable Name = [on_true] if [Test Part - IV
ic
 expression] else [on_false]
Answer the following questions
(iii) Example:
bl

min = 50 if 49 < 50 else 70 // min = 50  (5 marks)


min = 50 if 49 > 50 else 70 // min = 70
Pu

1. Describe in detail the procedure Script mode


4. Write short notes on Escape sequences with programming.
examples. Ans. A script is a text file containing the Python
Ans. (i) In Python strings, the backslash "\" is a
ra

statements. Python Scripts are reusable code.


special character, also called the "escape" Once the script is created, it can be executed
character. again and again without retyping. The Scripts
Su

(ii) It is used in representing certain whitespace are editable.


characters: "\t" is a tab, "\n" is a newline, Creating Scripts in Python :
and "\r" is a carriage return.
(i) Choose File → New File or press Ctrl + N in
(iii) For example to print the message "It's Python shell window.
raining", the Python command is A – A script is a text frame
>>> print ("It\'s raining") R – Text file contain Python script
It's raining (1) All text file does not Python scripts
5. What are string literals? Explain. (2) All text file must contain Python script
Ans. (i) In Python, a string literal is a sequence of (3) A is T B
characters surrounded by quotes. Python (ii) An untitled blank script text editor will be
supports single, double and triple quotes displayed on screen.
for a string. (iii) Type the code in Script editor

47
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit II - Chapter 5
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


Saving Python Script :
(i)  Choose File → Save or Press Ctrl + S
 
This material only for sample www.surabooks.com

www.nammakalvi.org
(ii) If code has any error, it will be shown in
red color in the IDLE window, and Python
describes the type of error occurred. To
correct the errors, go back to Script editor,
make corrections, save the file using Ctrl + S
or File → Save and execute it again.
(iii) 
For all error free code, the output will
appear in the IDLE window of Python.
2. Explain input () and print () functions with
examples.
Ans. Input and Output Functions : A program
needs to interact with the user to accomplish the
desired task; this can be achieved using Input-
(ii) Now, Save As dialog box appears on the Output functions. The input() function helps to
screen. enter data at run time by the user and the output

ns
File Location
function print() is used to display the result of
the program on the screen after execution.
The input() function :

io
at (i)  In Python, input( ) function is used to
accept data as input at run time. The syntax
for input() function is,
ic
Variable = input (“prompt string”)
(ii)  Where, prompt string in the syntax is a
bl

statement or message to the user, to know


what input can be given.
Pu

File Name (demo1) (ii) If a prompt string is used, it is displayed on


the monitor; the user can provide expected
data from the input device. The input( )
ra

Save As Dialog Box


takes whatever is typed from the keyboard
(iii) In the Save As dialog box, select the and stores the entered data in the given
location where you want to save your variable.
Su

Python code, and type the file name in File (iv) If prompt string is not given in input( ) no
Name box. Python files are by default saved message is displayed on the screen, thus,
with extension .py. Thus, while creating the user will not know what is to be typed
Python scripts using Python Script editor, as input.
no need to specify the file extension.
(v) Example 1 : input( ) with prompt string
(iv) Finally, click Save button to save your >>> city=input (“Enter Your City: ”)
Python script.
Enter Your City: Madurai
Executing Python Script :
>>> print (“I am from “, city)
(i) Choose Run → Run Module or Press F5 I am from Madurai
(vi) Example 2 : input( ) without prompt string
a=100
b=350 >>> city=input()
c=a+b
print ("The Sum=", c)
Madurai
>>> print (I am from", city)
To Execute Python Script I am from Madurai

48
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

(vii) Note that in example-2, the input( ) is not


having any prompt string, thus the user will
Sura’s
www.surabooks.com

➠ XII Std - Computer Science


(iii) Example :
>>> print (“Welcome to Python

Python - Variables and Operators


not know what is to be typed as input. If Programming”)
the user inputs irrelevant data as given in Welcome to Python Programming
the above example, then the output will
>>> x = 5
be unexpected. So, to make your program
more interactive, provide prompt string >>> y = 6
with input( ). >>> z = x + y
(viii) The input ( ) accepts all data as string >>> print (z)
or characters but not as numbers. If a 11
numerical value is entered, the input values
should be explicitly converted into numeric >>> print (“The sum = ”, z)
data type. The int( ) function is used to The sum = 11
convert string data as integer data explicitly. >>> print (“The sum of ”, x, “ and ”, y, “ is ”, z)
We will learn about more such functions in
The sum of 5 and 6 is 11
later chapters.

ns
(iv) The print ( ) evaluates the expression before
(ix) Example 3 :
x = int (input(“Enter Number 1: ”)) printing it on the monitor.

io
y = int (input(“Enter Number 2: ”)) (v) The print () displays an entire statement
print (“The sum = ”, x+y) at which is specified within print ( ). Comma
(x) Output : (,) is used as a separator in print ( ) to print
Enter Number 1: 34 more than one item.
ic
Enter Number 2: 56 3. Discuss in detail about Tokens in Python.
bl

The sum = 90
Ans. Python breaks each logical line into a sequence
(xi) Example 4 : Alternate method for the
of elementary lexical components known as
Pu

above program
Tokens. The normal token types are
x,y=int (input("Enter Number 1 :")),
 int(input("Enter Number 2:")) (i) Identifiers,
print ("X = ",x," Y = ",y) (ii) Keywords,
ra

(xii) Output : (iii) Operators,


Enter Number 1 :30
Su

(iv) Delimiters and


Enter Number 2:50 (v) Literals.
X = 30 Y = 50 Identifiers :
(i)
The print() function :
■ An Identifier is a name used to identify a
(i) In Python, the print() function is used to
variable, function, class, module or object.
display result on the screen. The syntax for
print() is as follows : ■ An identifier must start with an alphabet
(ii) Example : (A..Z or a..z) or underscore ( _ ).
print (“string to be displayed as output ” ) ■ Identifiers may contain digits (0 .. 9).
print (variable ) ■ Python identifiers are case sensitive i.e.
print (“String to be displayed as output ”, uppercase and lowercase letters are distinct.
variable) ■ Identifiers must not be a python keyword.
 print (“String1 ”, variable, “String 2”, ■ Python does not allow punctuation
 variable, “String 3” ……) character such as %,$, @ etc., within
identifiers.

49
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit II - Chapter 5
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


(ii) Keywords : Keywords are special words
used by Python interpreter to recognize
 
This material only for sample www.surabooks.com

www.nammakalvi.org
(iv) Delimiters : Python uses the symbols
and symbol combinations as delimiters in
the structure of program. As these words expressions, lists, dictionaries and strings.
have specific meaning for interpreter, they Following are the delimiters.
cannot be used for any other purpose. ( ) [ ] { }
(iii) Operators : In computer programming , : . ' = ;
languages operators are special symbols
which represent computations, conditional += -= *= /= //= %=
matching etc. The value of an operator &= |= ^= >>= <<= **=
used is called operands. Operators are (v) Literals : Literal is a raw data given in a
categorized as Arithmetic, Relational, variable or constant. In Python, there are
Logical, Assignment etc. Value and various types of literals.
variables when used with operator are ■ Numeric
known as operands. ■ String
■ Boolean.

ns
additional questions and Answers

io
Choose the Correct Answer 1 MARK 5. Which of the following mode cannot be
written Python program?
at (i) Interactive mode (ii) Script mode
1. Python language was released in
(iii) Calculator mode (iv) Executable mode
ic
(a) 1992 (b) 1991
(a) i (b) ii
bl

(c) 1994 (d) 2001 (c) i and iii (d) iii and iv
 [Ans. (b)1991]  [Ans. (d) iii and iv]
Pu

2. IDLE expansion is 6. Which of the following defines the Python


(a) Integrated Development Learning Environment interactive mode of programming?
(a) >>> (b) <<<
(b) Information Development Logical Environment
ra

(c) >> (d) <<


(c) Integrated Development Language Environment  [Ans. (a) >>>]
Su

(d) Interactive Development Learning Environment 7. Which of the following mode allows to write
codes in Python command prompt?
 [Ans. (a) Integrated Development Learning
Environment] (a) Script mode (b) Complier mode
(c) Interactive mode (d) Program mode
3. In Python, How many ways programs can be  [Ans. (c) Interactive mode]
written?
(a) 4 (b) 3 8. Which mode can also be used as a simple
(c) 2 (d) many calculator in Python?
 [Ans. (c) 2] (a) Information (b) Intelligent
(c) Script (d) Interactive
4. In Python, the script mode programs can be  [Ans. (d) Interactive]
stored with the extension.
9. Which mode displays the python code result
(a) .pyt (b) .pyh
immediately?
(c) .py (d) .pon
(a) Compiler (b) Interactive
 [Ans. (c) .py]
(c) Script (d) Program
 [Ans. (b) Interactive]

50
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample www.surabooks.com

 

6
Chapter
CONTROL STRUCTURES


CHAPTER SNAPSHOT
www.nammakalvi.org

6.01 Introduction 6.2.2 Alternative or Branching Statement


6.02 Control Structures 6.2.3. Iteration or Looping constructs
6.2.1 Sequential Statement 6.2.4 Jump Statements in Python

Evaluation
Part - I 6. Which is the most comfortable loop?

ns
(a) do..while (b) while
Choose the best answer  (1 mark) (c) for (d) if..elif

io
1. How many important control structures are  [Ans. (c) for]
there in Python?
7. What is the output of the following snippet?
(a) 3 (b) 4 (c) 5 (d) 6
at
i=1
 [Ans. (a) 3]
while True:
ic
2. elif can be considered to be abbreviation of if i%3 ==0:
bl

(a) nested if (b) if..else break


(c) else if (d) if..elif print(i,end='')
Pu

 [Ans. (c) else if] i +=1


3. What plays a vital role in Python (a) 12 (b) 123 (c) 1234 (d) 124
programming?  [Ans. (A) 12]
ra

(a) Statements (b) Control 8. What is the output of the following snippet?
(c) Structure (d) Indentation T=1
Su

 [Ans. (a) Statements] while T:


4. Which statement is generally used as a print(True)
placeholder? break
(a) continue (b) break (a) False (b) True
(c) pass (d) goto (c) 0 (d) no output
 [Ans. (c) pass]  [Ans. (b) True]
5. The condition in the if statement should be in 9. Which amongst this is not a jump statement ?
the form of (a) for
(a) Arithmetic or Relational expression (b) goto
(b) Arithmetic or Logical expression (c) continue
(c) Relational or Logical expression (d) break
(d) Arithmetic  [Ans. (a) for]
 [Ans. (c) Relational or Logical expression]

[61]

orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757


Unit II - Chapter 6
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


10. Which punctuation should be used in the
blank?
 
This material only for sample www.surabooks.com

www.nammakalvi.org
Part - III
Answer the following questions
if <condition>_
statements-block 1  (3 marks)
else:
statements-block 2
1. Write a program to display
(a) ; (b) : (c) :: (d) !
A
 [Ans. (b) :]
AB
Part - II ABC
Answer the following questions ABCD
 (2 marks) ABCDE
1. List the control structures in Python. Ans. For i in range (65, 70):
Ans. (i) Sequential
For j in range (65, i + 1):
(ii) Alternative or Branching print (chr(j), end = ' ')
(iii) Iterative or Looping print (end='\n')

ns
i+ = 1
2. Write note on break statement.
Ans. (i) The break statement terminates the loop 2. Write note on if..else structure.

io
containing it. Control of the program flows Ans. (i) When we need to construct a chain of if
to the statement immediately after the body statement(s) then 'elif' clause can be used
of the loop.
at instead of 'else'.
(ii) Syntax:
ic
(ii) When the break statement is executed, the
control flow of the program comes out of if <condition-1>:
bl

the loop and starts executing the segment statements-block 1


of code after the loop structure. elif <condition-2>:
Pu

(iii) If break statement is inside a nested loop statements-block 2


(loop inside another loop), break will else:
terminate the innermost loop. statements-block n
ra

3. Write the syntax of if..else statement (iii) In the syntax of if..elif..else mentioned
Ans. Syntax : above, condition-1 is tested if it is true then
Su

if <condition>: statements-block1 is executed, otherwise


statements-block 1 the control checks condition-2, if it is true
else: statements-block2 is executed and even if it
statements-block 2 fails statements-block n mentioned in else
part is executed.
4. Define control structure.
Ans. A program statement that causes a jump of 3. Using if..else..elif statement write a suitable
control from one part of the program to another program to display largest of 3 numbers.
is called control structure or control statement. Ans. a = int (input ("Enter number 1")
b = int (input (" Enter number 2")
5. Write note on range () in loop.
c = int (input (" Enter number 3")
Ans. range() generates a list of values starting from
start till stop-1. if a > b and a > c:
range (start,stop,[step]) put (" A is greatest")
Where, elif b > a and b > c:
start – refers to the initial value print ("B is greatest")
stop – refers to the final value
else:
step – refers to increment value, this is optional
print ("C is greatest")
part.

62
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com

4. Write the syntax of while loop.


Ans. Syntex:
This material only for sample

Sura’s
Where,

www.surabooks.com

➠ XII Std - Computer Science

start – refers to the initial value

Control Structures
while <condition>: stop – refers to the final value
statements block 1 step –  refers to increment value, this is
[else: optional part.
statements block2] Examples for range() :
5. List the differences between break and range (1,30,1) - will start the range of values
continue statements. from 1 and end at 29
Ans. The break statement terminates the loop range (2,30,2) - will start the range of values
containing it and control reaches after the body from 2 and end at 28
of the loop where as continue statement skips range (30,3,-3) - will start the range of values
the remaining part of a loop and start with next
from 30 and end at 6
iteration.
range (20) - will consider this value
Part - IV 20 as the end value(or

ns
upper limit) and starts the
Answer the following questions range count from 0 to 19
 (5 marks) (remember always range()

io
will work till stop -1 value
at only)
1. Write a detail note on for loop
Example :
Ans. (i) for loop is the most comfortable loop. It is #Program to illustrate the use of for loop - to
ic
also an entry check loop. The condition is print single digit even number
checked in the beginning and the body of for i in range (2,10,2):
bl

the loop(statements-block 1) is executed


print (i, end=' ')
if it is only True otherwise the loop is not
Pu

Output :
executed.
2468
(ii) Syntax:
for counter_variable in sequence: 2. Write a detail note on if..else..elif statement
with suitable example.
ra

statements-block 1
[else: # optional block Ans. (i) When we need to construct a chain of if
statement(s) then 'elif' clause can be used
Su

statements-block 2]
instead of 'else'.
(iii) The counter_variable mentioned in the
syntax is similar to the control variable (ii) Syntax :
that we used in the for loop of C++ and if <condition-1>:
the sequence refers to the initial, final statements-block 1
and increment value. Usually in Python, elif <condition-2>:
for loop uses the range() function in the statements-block 2
sequence to specify the initial, final and else:
increment values. range() generates a list of
statements-block n
values starting from start till stop-1.
(iii) In the syntax of if..elif..else mentioned
(iv) The syntax of range() is as follows:
above, condition-1 is tested if it is true then
range (start,stop,[step]) statements-block1 is executed, otherwise
the control checks condition-2, if it is true
statements-block2 is executed and even if it
fails statements-block n mentioned in else
part is executed.

63
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit II - Chapter 6
www.surabooks.com

Sura’s ➠ XII Std - Computer Science  


This material only for sample www.surabooks.com

www.nammakalvi.org
3. Write a program to display all 3 digit odd
numbers.
Test false
Expression
of if Ans. for i in range (101, 100, 2):
print (i, end = " ")
True Test false
4. Write a program to display multiplication
Expression
Body of if of elif table for a given number.
True Ans. n = int (input ("Enter the number")
for i in range (1, 13):
Body of elif
Body of else
print (n, 'x', i, " = ", n * i)

if..elif..else statement execution Hands on Experience


(iv) 'elif'
clause combines if..else-if..else
statements to one if..elif…else. 'elif' can 1. Write a program to check whether the given

ns
be considered to be abbreviation of 'else if'. character is a vowel or not.
In an 'if' statement there is no limit of 'elif ' Ans. Program :

io
clause that can be used, but an 'else' clause ch = input ("Enter a character")
if used should be placed at the end.
if ch in ('a', 'A', 'e', 'E', 'i', 'I','o','O','u', 'U'):
(v) Example : #Program to illustrate the use of
at
print (ch, 'is a vowel')
nested if statement
ic
Average Grade 2. Using if..else..elif statement check smallest of
>=80 and above A three numbers.
bl

>=70 and <80 B Ans. Program :


Pu

>=60 and <70 C a = in + (input ("Enter number 1")


>=50 and <60 D
b = in + (input("Enter number 2")
Otherwise E
m1=int (input("Enter mark in first subject : ")) c = in + (input ("Enter number 3")
ra

m2=int (input("Enter mark in second subject : ")) if a < b and a < c :


avg= (m1+m2)/2 print ("a is smallest")
Su

if avg>=80: elif b < a and b< c:


print ("Grade : A") print ("b is smallest")
elif avg>=70 and avg<80: else
print ("Grade : B") print ("c is smallest")
elif avg>=60 and avg<70:
3. Write a program to check if a number is
print ("Grade : C")
Positive, Negative or zero.
elif avg>=50 and avg<60:
Ans. Program :
print ("Grade : D")
x = in + (input("aEnter a number")
else:
if x>0:
print ("Grade : E")
print (x, "is a positive number")
Output 1:
elif x < 0:
Enter mark in first subject : 34
print (x, "is a negative number")
Enter mark in second subject : 78
else
Grade : D
print (x, "is zero")
Output 2 :
Enter mark in first subject : 67
64
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

4. Write a program to display Fibonacci series 0 1


1 2 3 4 5…… (upto n terms)
Sura’s

www.surabooks.com

➠ XII Std - Computer Science


n = n//10
if s = = x:

Control Structures
Ans. Program to display Fibonacci series : print ("The given number is palindrome"
a, b, c = 0, 1,0 else:
n = in + (input("Enter number of terms"))  print ("The given number is not
palindrome")
print (a, end = '')
print (b, end = '') 7. Write a program to print the following pattern
for I in range (3, n+1): *****
c = a+b ****
print (c, end = '') ***
a=b **
b=c *
Ans. Program :
5. Write a program to display sum of natural
numbers, upto n. for i in range (5, 0, -1):
Ans. Program to display sum of natural numbers for j in range (1, i + 1):

ns
upto n : print (' * ', end = '')
print (end = '\n')
s=0
i+=1

io
n = in + (input("Enter number of terms"))
for i in range (1, n + 1) 8. Write a program to check if the year is leap
s=s+i
print ("sum = '', s)
at year or not.
Ans. Program :
ic
6. Write a program to check if the given number y = int (input ("Enter the year"))
is a palindrome or not. If y % 400 = = 0 or y% 4 = = 0 or y% 100 = = 0:
bl

Ans. Program : print ("The given year is a leap year")


n = int (input("Enter the number")) else:
Pu

s, d, x = 0, 0, n print ("The given number is not a leap


while (n ! = 0): year")
d = n%10
ra

s = (s* 10)+d

additional questions and Answers


Su

Choose the Correct Answer 1 MARK


3. Which of the following is used to alter the
1. Which of the following are the executable control flow of the process depending on the
segments that yield the result? state of the process?
(a) Operator (b) Statements (a) control structure
(c) Keywords (d) Identifiers (b) control statement
 [Ans. (b) Statements] (c) program statement
(d) control structure or control statement
1. Find the odd man out.
 [Ans. (d) control structure or control
(a) keywords (b) Operator
statement]
(c) Identifiers (d) Programs
 [Ans. (d) Programs] 4. How many important control structures in
2. Find the odd man out. python?
(a) Statement (b) Operator (a) 2 (b) 3
(c) Identifier (d) Keyword (c) 4 (d) many
 [Ans. (a) Statements]  [Ans. (b) 3]
65
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

4. (i) if a loop is left by break, the else part is not


executed
Sura’s
www.surabooks.com

➠ XII Std - Computer Science


3. Write a program in python to check if the
accepted number even or odd.

Control Structures
(ii) Continue statement is used to skip the a = int(input("Enter any number :"))
remaining part of a loop and start with next if a%2==0:
iteration.
print (a, " is an even number")
(iii) In python, pass statement is a null statement. else:
(iv) In python, pass statement is not completely print (a, " is an odd number")
ignored by the complier.
Ans. Output 1:
(a) i and ii (b) iii only
Enter any number :56
(c) iii and iv (d) iv only
56 is an even number
 [Ans. (d) iv only]
Output 2:
Choose the true or false statement Enter any number :67
1. State whether the following statement is true/ 67 is an odd number
false. 4. Write the syntax of alternative method to write

ns
(i) While loop is an entry check loop complete if-else.
(ii) for loop is an entry check loop Ans. Syntax:
(iii) print() can have parameters

io
variable = variable1 if condition else variable 2
(iv) if-elif-else is similar to c++ nested if.
(a) i – true, ii – true, iii-true, iv-true 5. Write a program in python to check if the
at
(b) i-true, ii-false, iii-true, iv-true accepted number us even or odd (use alternate
(c) i-true, ii-true, iii-false, iv-true method of if-else).
ic
(d) i-true, ii-true, iii-true, iv-true Ans. a = int (input("Enter any number :"))
x="even" if a%2==0 else "odd"
bl

 [Ans. (a) i – true, ii – true, iii-true, iv-true]


print (a, " is ",x)
Very Short Answers 2 MARKS
Pu

Output 1:
1. What is meant by alternative or branching? Enter any number :3
Ans. There may be situations in our real life 3 is odd
programming where we need to skip a segment Output 2:
ra

or set of statements and execute another segment Enter any number :22
based on the test of a condition. This is called 22 is even
Su

alternative or branching.
6. What are the two types of looping constructs
2. Draw a flow chart that defines the execution of in python?
if-else statement.
Ans. Python provides two types of looping constructs:
Ans. Entry
(i) while loop
(ii) for loop
if condition is if condition is 7. Write a note on the parameters used in print
true condition false
() statement.
Statement Statement
Ans. (i) print can have end, sep as parameters. end
block -1 block -2 parameter can be used when we need to
give any escape sequences like '\t' for tab,
'\n' for new line and so on.
(ii) sep as parameter can be used to specify
Exit
any special characters like, (comma) ;
if..else statement execution
(semicolon) as separator between values

69
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit II - Chapter 6
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


8. Write the syntax of for loop.
Ans. Syntax:
 
This material only for sample www.surabooks.com

www.nammakalvi.org
for counter in range(1,n+1):
sum = sum + counter
for counter_variable in sequence: print("Sum of 1 until %d: %d" % (n,sum))
statements-block 1 Output:
[else: # optional block Sum of 1 until 100: 5050
statements-block 2] 13. Write a python program to find the sum of
9. Draw the flowchart that illustrate the working even numbers between 1 and 10.
of for loop. Ans. s = 0
Ans. For i in range (2, 11, 2)
for each item s=s+i
in sequence print (s)
14. Write a python program to find the sum of odd
Yes numbers between 10 and 20.
Last item
reached? Ans. s = 0

ns
for i in range (11, 21, 2)
s=s+i
print (s)

io
No
15. What are the values taken by range ()?
Body of for
Ans. It take values from string, list, dictionary.
Exit loop
at
16. What is meant by Nested loop structure?
ic
for loop execution Ans. A loop placed within another loop is called as
nested loop structure. A while within another
10. What will the output of the following program?
bl

while; for within another for; for within while


for i in range (1, 9, 2): and while within for to construc nested loops.
Pu

print (i, end = ' ')


else: 17. What is the use of Jump statements in python?
print (")n End of the loop") (or)
What are the statements are there to achieve
Ans. Output:
ra

jump statements in python?


1, 3, 5, 7
End of the loop Ans. The jump statement in Python, is used to
Su

unconditionally transfer the control from one


11. What is the expression or statement at ?1? and part of the program to another. There are three
?2? in the following program to get the output keywords to achieve jump statements in Python:
2468 break, continue, pass. The following flowchart
for ?1? in range (2, ?2?, 2): illustrates the use of break and continue.
print (i, end = ")
18. Write the syntax how break statement used in
Ans. ?1? – i for loop.
?2? – 10 Ans. for var in sequence:
12. Write a python program to calculate the sum if condition:
of numbers between 1 and 100. break
Ans. Program to calculate the sum of numbers 1 to #code inside for loop
100 #code outside for loop
Program :
19. Write the syntax how break statement used in
n = 100
while loop.
sum = 0
Ans. while test expression:
#code inside while loop

70
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757


www.surabooks.com

if condition:
break
This material only for sample

Sura’s
www.surabooks.com

➠ XII Std - Computer Science


Example :
# Program to print your name and address -

Control Structures
#code inside while loop example for sequential statement
#code outside while loop print ("Hello! This is Shyam")
print ("43, Second Lane, North Car Street, TN")
20. What is the use of continue statement in
Output :
python?
Hello! This is Shyam
Ans. Continue statement unlike the break statement
is used to skip the remaining part of a loop and 43, Second Lane, North Car Street, TN
start with next iteration. 2. List the types of alternative or branching
21. Draw the flowchart that illustrates the working statement in python.
of continue statement in python. Ans. Python provides the following types of alternative
Ans. or branching statements:
(i) Simple if statement
Enter loop
(ii) if..else statement

ns
Test false (iii) if..elif statement
Expression
of loop 3. Write a note on simple if statement with an

io
true example.
Ans. Simple if statement : Simple if is the simplest
at
yes
continue? of all decision making statements. Condition
should be in the form of relational or logical
ic
Exit loop
no
expression.
bl

Remaining body of loop


Syntax :
Working of continue statement
if <condition>:
Pu

22. What will the output the following statements-block1


for w in "school"? In the above syntax if the condition is true state-
If w = = '0': ments - block 1 will be executed.
ra

continue Example : Program to check the age and print


print (w) whether eligible for voting
Su

Ans. schl x=int (input("Enter your age :"))


23. Write a note an pass statement. if x>=18:
Ans. pass statement in Python programming is a null print ("You are eligible for voting")
statement. pass statement when executed by the Output 1:
interpreter it is completely ignored. Nothing
Enter your age :34
happens when pass is executed, it results in no
operation. You are eligible for voting
Short Answers 3 MARKS Output 2:
Enter your age :16
1. Write a note on sequential statement with an >>>
example.
Ans. A sequential statement is composed of a 4. Write a python program to print all numbers
sequence of statements which are executed one from 10 to 15 using while loop.
after another. A code to print your name, address Ans. Example : Program to illustrate the use of while
and phone number is an example of sequential loop - to print all numbers from 10 to 15
statement.

71
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit II - Chapter 6
www.surabooks.com

Sura’s

i=10  #
➠ XII Std - Computer Science
intializing part of the control
variable
This material only for sample

  www.surabooks.com

www.nammakalvi.org
# to check if the letter typed is not 'a' or 'b' or 'c'
if ch not in ('a', 'b', 'c'):
while (i<=15): # test condition print (ch,' the letter is not a/b/c')
print (i,end='\t') # statements - block 1 Output 1:
i=i+1 # Updation of the control variable Enter a character :e
Output: e is a vowel
10 11 12 13 14 15 Output 2:
5. Draw a flowchart that illustrates the working Enter a character :x
of while loop. x the letter is not a/b/c
Ans.
8. Draw the flowchart that illustrates the working
of break statement.
while Expression: Ans.
Statement (s)
Condition Enter loop

ns
if conditions is true false
Condition
if condition is
Conditional Code

io
false
true

while loop execution


at break?
yes
ic
6. Draw the flowchart that illustrates the use Exit loop
no
of break and continue statement in loop
bl

Remaining body of loop


structure.
Pu

Ans.
Working of break statement

False
9. Write the syntax of working of continue
Condition
statement in for and while loop.
ra

Ans. for var in sequence:


True else
# code inside for loop
Su

Statement 1
Statement 1 Statement 2 if condition:
... ...
break Statementn continue
... #code inside for loop
continue
...
Further #code outside for loop
Statements
Statementn of Program while test expression:
#code inside while loop
Use of break, continue statement in loop structure
if condition:
continue
7. Write a program in python that illustrate the
#code inside while loop
use of 'in' and 'not in' if statement
#code outside while loop
Ans. Program :
ch=input ("Enter a character :") 10. What is the output of the following Python
# to check if the letter is vowel program?
if ch in ('a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'): Ans. i=10 # intializing part of the control variable
print (ch,' is a vowel') while (i<=15): # test condition

72
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com

print (i,end='\t') # statements - block 1


i=i+1 # Updation of the control variable
This material only for sample

Sura’s
www.surabooks.com

➠ XII Std - Computer Science


Output:
Jump Stat

Control Structures
else: End of the program
print ("\nValue of i when the loop exit ",i)
Output: 1 14. Why we need to construct the pass statement?
10 11 12 13 14 15 Ans. pass statement is generally used as a placeholder.
Value of i when the loop exit 16 When we have a loop or function that is to be
implemented in the future and not now, we
11. What will be the range of values displayed by cannot develop such functions or loops with
the following? empty body segment because the interpreter
Ans. range (1,30,1) - will start the range of values would raise an error. So, to avoid this we can
from 1 and end at 29 use pass statement to construct a body that does
range (2,30,2) - will start the range of values nothing.
from 2 and end at 28
range (30,3,-3) - will start the range of values
from 30 and end at 6
Long Answers 5 MARKS

ns
range (20) - will consider this value 20 as the 1. Explain Jump statement in python.
end value(or upper limit) and
Ans. The jump statement in Python, is used to
starts the range count from 0 to

io
unconditionally transfer the control from one
19 (remember always range()
part of the program to another. There are three
will work till stop -1 value only)
at keywords to achieve jump statements in Python :
12. Draw a flowchart that illustrate how looping break, continue, pass. The following flowchart
ic
construct gets executed. illustrates the use of break and continue.
Ans.
bl

False
Pu

Condition
False
Condition
True else
Statement 1
True else Statement 2
Statement 1
Statement 1
ra

... ...
Statement 1 Statement 2 break Statementn
Statement 2 ... ...
Su

... Statementn continue Further


... Statements
Statementn Statementn of Program
Further
Statements Use of break, continue statement in loop structure
of Program
Diagram to illustrate how looping construct gets executed (i) break statement : The break statement
terminates the loop containing it. Control
13. What will be output of the following program? of the program flows to the statement
Ans. for word in "Jump Statement": immediately after the body of the loop.
if word = = "e": A while or for loop will iterate till the
break condition is tested false, but one can
print (word, end=") even transfer the control out of the loop
(terminate) with help of break statement.
else:
When the break statement is executed, the
print ("End of the loop") control flow of the program comes out of
print ("\n End of the program") the loop and starts executing the segment
of code after the loop structure.

73
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit II - Chapter 6
www.surabooks.com

Sura’s

➠ XII Std - Computer Science
If break statement is inside a nested loop
(loop inside another loop), break will
 
This material only for sample www.surabooks.com

www.nammakalvi.org
3. Write a program in python to display he
following output
terminate the innermost loop. 1
Syntax: 22
break 333
(ii) continue statement : Continue statement
4444
unlike the break statement is used to skip
the remaining part of a loop and start with 55555
next iteration. Ans. for i in range (1,6):
Syntax: for j in range (1, i + 1)
continue
print (i, end = ' ')
(iii) pass statement : pass statement is generally
used as a placeholder. When we have a loop print (end = '\n')
or function that is to be implemented in i+=1
the future and not now, we cannot develop

ns
such functions or loops with empty body 4. Write a program in python to display the
segment because the interpreter would following output.
raise an error. So, to avoid this we can use (i) 5 5 5 5 5

io
pass statement to construct a body that
does nothing. at 4444
Syntax: 333
pass 22
ic
2. Write a program in python to display the 1
bl

following output. (ii) 1 2 3 4 5


1 1234
Pu

12 123
123
12
1234
1
ra

12345
Ans. i=1 Ans. (i) for i in range (5, 0,-1):
Su

while (i<=6): for j in range (1, i + 1):


for j in range (1,i): print (i, end = ' ')
print (j,end='\t')
print (end = '\n')
print (end='\n')
i +=1 i+=1
Output: (ii) for i in range (5, 0, -1):
1 for j in range (1, i + 1):
12 print (j end = ' ')
123 print (i, end = '\n')
1234
i+=1
12345


74
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
PYTHON
www.surabooks.com This material only for sample www.surabooks.com

 

7
Chapter
FUNCTIONS
www.nammakalvi.org


CHAPTER SNAPSHOT
7.01 Introduction

ns
7.1.1 Types of Functions
7.02 Defining Functions
7.2.1 Syntax for User defined function

io
7.2.2 Advantages of User-defined Functions
7.03 Calling a Function
at
7.04 Passing Parameters in Functions
ic
7.05 Function Arguments
7.5.1 Required Arguments
bl

7.5.2 Keyword Arguments


7.5.3 Default Arguments
Pu

7.5.4 Variable-Length Arguments


7.06 Anonymous Functions
7.6.1 Syntax of Anonymous Functions
ra

7.07 The return Statement


7.7.1 Syntax of return
Su

7.08 Scope of Variables


7.8.1 Local Scope
7.8.2 Global Scope
7.8.3 Global and local variables
7.09 Functions using libraries
7.9.1 Built-in and Mathematical functions
7.9.2 Composition in functions
7.10 Python recursive functions

[75]

orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757


Unit II - Chapter 7
www.surabooks.com

Sura’s
This material only for sample

➠ XII Std - Computer Science

Evaluation
  www.surabooks.com

www.nammakalvi.org

(a) I is correct and II is wrong


Part - I (b) Both are correct
Choose the best answer  (1 mark) (c) I is wrong and II is correct
1. A named blocks of code that are designed to (d) Both are wrong
do one specific job is called as  [Ans. (a) I is correct and II is wrong]
(a) Loop (b) Branching 9. Pick the correct one to execute the given
(c) Function (d) Block statement successfully.
 [Ans. (c) Function ] if ____ : print(x, " is a leap year")
2. A Function which calls itself is called as (a) x%2=0 (b) x%4==0
(a) Built-in (b) Recursion (c) x/4=0 (d) x%4=0
(c) Lambda (d) return  [Ans. (b) x%4==0]
 [Ans. (b) Recursion] 10. Which of the following keyword is used to
3. Which function is called anonymous un-named define the function testpython(): ?

ns
function (a) define (b) pass
(a) Lambda (b) Recursion (c) def (d) while

io
(c) Function (d) define  [Ans. (c) def]
 [Ans. (a) Lambda] Part - II
at
4. Which of the following keyword is used to Answer the following questions
begin the function block?  (2 marks)
ic
(a) define (b) for
bl

(c) finally (d) def 1. What is function?


 [Ans. (d) def] Ans. Functions are nothing but a group of related
Pu

5. Which of the following keyword is used to exit statements that perform a specific task.
a function block?
2. Write the different types of function.
(a) define (b) return
Ans.
(c) finally (d) def
ra

 [Ans. (b) return] Functions Description


6. While defining a function which of the User - defined Functions defined by
Su

following symbol is used. functions the users themselves


(a) ; (semicolon) (b) . (dot) Built in functions Functions that are
(c) : (colon) (d) $ (dollar) inbuilt with in Python.
 [Ans. (c) : (colon)] Lambda functions Functions that are
7. In which arguments the correct positional anonymous un-named
order is passed to a function? function.
(a) Required (b) Keyword Recursion functions Functions that calls
(c) Default (d) Variable-length itself is known as
recursive.
 [Ans. (d) Variable-length]
8. Read the following statement and choose the 3. What are the main advantages of function?
correct statement(s). Ans. Main advantages of functions are
(I) In Python, you don’t have to mention the (i) It avoids repetition and makes high degree
specific data types while defining function. of code reusing.
(II) Python keywords can be used as function (ii) 
It provides better modularity for your
name. application.

76
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

4. What is meant by scope of variable? Mention


its types.
Sura’s
(ii) 
www.surabooks.com

➠ XII Std - Computer Science


When a variable is created inside the
function/block, the variable becomes local

Python Functions
Ans. Scope of variable refers to the part of the to it.
program, where it is accessible, i.e., area where (iii) 
A local variable only exists while the
the variables can refer (use). The scope holds the function is executing.
current set of variables and their values. The two
(iv) The formate arguments are also local to
types of scopes - local scope and global scope.
function.
5. Define global scope.
2. Write the basic rules for global keyword in
Ans. A variable, with global scope can be used
python.
anywhere in the program. It can be created by
defining a variable outside the scope of any Ans. Rules of global Keyword : The basic rules for
function/block. global keyword in Python are:
6. What is base condition in recursive function? (i) 
When we define a variable outside a
Ans. (i) A recursive function calls itself. Imagine function, it’s global by default. You don’t
a process would iterate indefinitely if not have to use global keyword.

ns
stopped by some condition. Such a process (ii) 
We use global keyword to read and write a
is known as infinite iteration.
global variable inside a function.

io
(ii) The condition that is applied in any
recursive function is known as base at (iii) 
Use of global keyword outside a function
condition. has no effect.
(iii) A base condition is must in every recursive 3. What happens when we modify global variable
ic
function otherwise it will continue to inside the function?
execute like an infinite loop. Ans. It shows an error, unbound local error.
bl

7. How to set the limit for recursive function? 4. Differentiate ceil() and floor() function.
Pu

Give an example. Ans.


Ans. To set the limit for recursive function using
sys. setrecursionlimit (limit _value). ceil () floor ()
Example: It returns the It returns the largest
ra

import sys smallest integer integer less than or


sys.setrecursionlimit(3000) greater that or equal equal to given value.
Su

to the given value.


def fact(n):
if n == 0:
return 1 5. Write a Python code to check whether a given
year is leap year or not.
else:
return n * fact(n-1) Ans. y = int(input ("Enter year")
print(fact (2000)) if y%4==0:
Part - III print ("The given year is a leap year")
else:
Answer the following questions
print ("The given year is not a leap year")
 (3 marks) 6. What is composition in functions?
1. Write the rules of local variable. Ans. (i) The value returned by a function may be
Ans. Rules of local variable : used as an argument for another function
in a nested manner.
(i) A variable with local scope can be accessed
only within the function/block that it is
created in.
77
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit II - Chapter 7
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


(ii) This is called composition. For example,
if we wish to take a numeric value or an
 
This material only for sample

Lambda functions
www.surabooks.com

www.nammakalvi.org
Functions that are
anonymous un-named
expression as a input from the user, we take function.
the input string from the user using the
Recursion functions Functions that calls itself is
function input() and apply eval() function
known as recursive.
to evaluate its value
Syntax for User defined function :
7. How recursive function works?
def<function_name ([parameter 1, parameter
Ans. (i)  Recursive function is called by some 2.....])>:
external code. <Block of Statement>
(ii) If the base condition is met then the return<expression / None> a
program gives meaningful output and exits. (i) Block : A block is one or more lines of code,
(iii) Otherwise, function does some required grouped together so that they are treated
processing and then calls itself to continue as one big sequence of statements while
recursion. execution. In Python, statements in a block
are written with indentation. Usually, a

ns
8. What are the points to be noted while defining block begins when a line is indented (by
a function? four spaces) and all the statements of the
Ans. When defining functions there are multiple block should be at same indent level.

io
things that need to be noted; (ii) Nested Block : A block within a block is
(i)  Function blocks begin with the keyword
"def" followed by function name and
at called nested block. When the first block
statement is indented by a single tab space,
parenthesis ().
ic
the second block of statement is indented
(ii) Any input parameters or arguments should by double tab spaces.
bl

be placed within these parentheses when Here is an example of defining a function;


you define a function. Do_Something():
Pu

(iii) 
The code block always comes after colon(;) value = 1 #Assignment Statement
and is indented. return value #Return Statement

(iv) The statement "return [expression]"
(iii) Lambda function is mostly used for creating
ra

exits a function, optionally passing back an


expression to the caller. A "return" with no small and one-time anonymous function.
arguments is the same as return None. (iv)  Lambda functions are mainly used in
Su

combination with the functions like filter(),


Part - IV map() and reduce().
Answer the following questions Syntax of Anonymous Functions :
The syntax for anonymous functions is as
 (5 marks) follows:
lambda [argument(s)] : expression
1. Explain the different types of function with an Example:
example.
sun = lambda arg1, arg2: arg1 + arg2
Ans. Type of functions :
print (The Sum is :', sum(30, 40)
Functions Description print (The Sum is :', sum(–30, 40)
User - defined Functions defined by the Output :
functions users themselves The Sum is : 70
Built in functions Functions that are inbuilt The Sum is : 10
with in Python. Built-in Functions : Functions which are using
Python libraries are called Built-in function.

78
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
x=20
y=-23.2

www.surabooks.com This material only for sample

Sura’s

(i) 
www.surabooks.com

➠ XII Std - Computer Science


Rules of local variable :
A variable with local scope can be accessed

Python Functions
print('x = ', abs(x)) only within the function/block that it is
print('y = ', abs(y)) created in.
Output: (ii)  When a variable is created inside the
x = 20 function/block, the variable becomes local
y = 23.2 to it.
Recursive function : A recursive function (iiii) A local variable only exists while the
calls itself. Imagine a process would iterate function is executing.
indefinitely if not stopped by some condition! (iv)  The formate arguments are also local to
Such a process is known as infinite iteration. function.
The condition that is applied in any recursive (v) Example: Create a Local Variable
function is known as base condition. A base def loc():
condition is must in every recursive function y=0 # local scope
otherwise it will continue to execute like an
print(y)
infinite loop.

ns
loc()
Overview of how recursive function works :
Output:
(i)  Recursive function is called by some

io
external code. 0
(ii) If the base condition is met then the at (vi) Example : Accessing local variable outside
program gives meaningful output and exits. the scope
(iii) 
Otherwise, function does some required def loc():
ic
processing and then calls itself to continue y = "local"
recursion.
bl

loc()
Here is an example of recursive function
used to calculate factorial. print(y)
Pu

Example : (vii) When we run the above code, the output


def fact(n): shows the following error:
if n == 0: The above error occurs because we are
ra

return 1 trying to access a local variable ‘y’ in a


else: global scope.
Su

return n * fact (n-1) NameError: name 'y' is not defined


print (fact (0)) Global Scope : A variable, with global scope
print (fact (5)) can be used anywhere in the program. It can be
Output: created by defining a variable outside the scope
of any function/block.
1
120 Rules of global Keyword :
2. Explain the scope of variables with an example. The basic rules for global keyword in Python are:
Ans. Scope of variable refers to the part of the (i) 
When we define a variable outside a
program, where it is accessible, i.e., area where function, it’s global by default. You don’t
the variables refer (use). The scope holds the have to use global keyword.
current set of variables and their values. The two (ii) 
We use global keyword to read and write a
types of scopes - local scope and global scope. global variable inside a function.
Local Scope : A variable declared inside the (iii) 
Use of global keyword outside a function
function's body or in the local scope is known as has no effect.
local variable.

79
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit II - Chapter 7


www.surabooks.com

Sura’s
Use of global Keyword :
This material only for sample

➠ XII Std - Computer Science

(i) Example : Accessing global Variable From


  www.surabooks.com

www.nammakalvi.org
3. Explain the following built-in functions.
(a) id() (b) chr()
Inside a Function (c) round() (d) type()
c = 1 # global variable (e) pow()
def add(): Ans.
print(c) (a)
add() id () id( ) Return id x=15
Output: the “identity” (object) y='a'
1 of an object. print ('address of x
(ii) Example : Accessing global Variable From i.e. the address is :',id (x))
Inside a Function of the object in
c = 1 # global variable memory. print ('address of y
def add(): is :',id (y))
Note:
print(c)
The address of Output:

ns
add()
Output: x and y may address of x is :
1 differ in your 1357486752

io
(iii) Example : Modifying Global Variable system. address of y is :
From Inside the Function at 13480736
c = 1 # global variable (b)
def add():
ic
c=c+2 # increment c by 2 chr ( ) Returns the chr c=65
Unicode (i) d=43
bl

print(c)
add() character for print (chr (c))
Pu

Output: the given ASCII prin t(chr (d))


 Unbound Local Error: local variable 'c' value. Output:
referenced before assignment This function is A
(iv) Example : Changing Global Variable From inverse of ord() +
ra

Inside a Function using global keyword function.


x = 0 # global variable (c)
Su

def add(): round Returns round x= 17.9


global x () the nearest (number y= 22.2
x=x+5 # increment by 2 integer to its [,ndigits])
input. z= -18.3
print ("Inside add() function x value
 is :", x) 1. First print ('x value
add() argument is rounded to',
print ("In main x value is :", x) (number) round (x))
is used to
Output: print ('y value
specify the
Inside add() function x value is : 5 value to be is rounded to',
In main x value is : 5 rounded. round (y))
(v)  In the above program, x is defined as a
global variable. Inside the add() function, print ('z value
global keyword is used for x and we is rounded to',
increment the variable x by 5. Now We round (z))
can see the change on the global variable x
outside the function i.e the value of x is 5.

80
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
(d)

www.surabooks.com This material only for sample

Sura’s
break

www.surabooks.com

➠ XII Std - Computer Science

greater + = 1

Python Functions
type Returns the type x= 15.2
() type of object (object) y= 'a' return lcm
for the given s= True a = int (input ("Enter number 1"))
single object. b = int (input ("Enter number 2"))
print (type (x))
Note: print ("The LCM of ", a, "and", b, "is", LCM(a,b))
print (type (y))
This function
print (type (s)) 5. Explain recursive function with an example.
used with
single object Output: Ans. (i) A recursive function calls itself. Imagine
parameter. a process would iterate indefinitely if not
<class 'float'>
stopped by some condition.
<class 'str'>
(ii) Such a process is known as infinite
<class 'bool'> iteration. The condition that is applied in
(e) any recursive function is known as base
condition.
pow Returns the pow a= 5
(iii) A base condition is must in every recursive

ns
() computation (a,b) b= 2
of ab i.e. function otherwise it will continue to
c= 3.0
(a**b) a execute like an infinite loop.
print (pow (a,b))

io
raised to the Overview of how recursive function works :
power of b. print (pow (a,c)) at (i) Recursive function is called by some
print (pow (a+b,3)) external code.
Output: (ii)  If the base condition is met then the
ic
25 program gives meaningful output and exits.
(iii)  Otherwise, function does some required
bl

125.0
processing and then calls itself to continue
343
recursion.
Pu

4. Write a Python code to find the L.C.M. of two Here is an example of recursive function
numbers. used to calculate factorial.
Ans. Program : Example :
ra

def lcm(x, y): def fact(n):


if x>y: if n == 0:
Su

greater = x return 1
else: else:
greater = y return n * fact (n-1)
while (True): print (fact (0))
if ((greater % x == 0) and (greater % y == print (fact (5))
0)): Output:
lcm = greater 1
120

81
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit II - Chapter 7
www.surabooks.com

Sura’s ➠ XII Std - Computer Science

additional questions and Answers


 
This material only for sample www.surabooks.com

www.nammakalvi.org

Choose the Correct Answer 1 MARK 9. In Python, statement in a block are written
with
1. Which of the following is used, if you don’t (a) Function (b) Identification
need to type all the python code for the same (c) Recursion (d) Parameters
task again and again:  [Ans. (b) Identification]
(a) Statement 10. Which of the following are treated as one big
(b) Function sequence of statement while exection?
(c) Scope (a) Structure (b) Statement
(d) Control structures [Ans. (b) Function] (c) Block (d) Code
2. Which of the following avoids repetition and  [Ans. (c) Block]
makes high degree of code reusing? 11. What will be the output if the return has no
(a) Loop (b) Branching argument?
(a) No (b) Return

ns
(c) Functions (d) Dictionaries
 [Ans. (c) Functions] (c) None (d) End
 [Ans. (c) None]

io
3. Which of the following provides better
modularity for your python application 12. Which of the following are the values pass to
at
(a) function (b) tuples the function parameters?
(c) dictionaries (d) control structures (a) Variables
ic
 [Ans. (a) function] (b) Arguments
(c) Definitions
bl

4. How many types of functions are there in


(d) Identifiers
python?
 [Ans. (b) Arguments]
Pu

(a) 3 (b) 4 (c) 2 (d) 5


 [Ans. (b) 4] 13. How many types of arguments are used to call
5. Functions that calls itself are known as a function ?
(a) 3 (b) 4 (c) 5 (d) 2
ra

(a) User defined (b) Recursive


(c) Built- in (d) Lambda [Ans. (b) 4]
[Ans. (b) Recursive] 14. Which of the following is not a type of
Su


6. Find the odd man out arguments used to call a function?
(a) User defined (b) Built in (a) Required (b) Keywords
(c) Recursion (d) Parameters (c) Default (d) Module
 [Ans. (d) Parameters]  [Ans. (d) Module]
7. Which of the following is not a type of function 15. In which of the following the number of
in python? arguments in the function call should match
(a) Control (b) Lambda exactly with the function definition?
(c) Recursion (d) Built in (a) Required arguments
 [Ans. (a) Control] (b) Keyword arguments
8. Which of the following statement exits a (c) Default arguments
function? (d) Variable-length arguments
(a) Exit (b) Def  [Ans. (a) Required arguments]
(c) Return (d) None of these
 [Ans. (c) Return]

82
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample www.surabooks.com

 
STRINGS AND

8
Chapter
STRING MANIPULATION


www.nammakalvi.org
CHAPTER SNAPSHOT
8.1 Introduction 8.6 String Formatting Operators
8.2 Creating Strings 8.7 Formatting characters
8.3 Accessing characters in a String 8.8 The format( ) function
8.4 Modifying and Deleting Strings 8.9 Built-in String functions
8.5 String Operators 8.10 Membership Operators

ns
Evaluation
io
5. Strings in python:
Part - I
at (a) Changeable (b) Mutable
Choose the best answer  (1 mark) (c) Immutable (d) flexible
ic
1. Which of the following is the output of the  [Ans. (c) Immutable]
bl

following python code?


6. Which of the following is the slicing operator?
str1="TamilNadu"
(a) { } (b) [ ] (c) < > (d) ( )
Pu

print(str1[::–1])
 [Ans. (b) [ ]]
(a) Tamilnadu (b) Tmlau
7. What is stride?
(c) udanlimaT (d) udaNlimaT
(a) index value of slide operation
ra

 [Ans. (d) udaNlimaT]


(b) first argument of slice operation
2. What will be the output of the following code?
Su

(c) second argument of slice operation


str1 = "Chennai Schools"
(d) third argument of slice operation
str1[7] = "-"
 [Ans. (d) third argument of slice operation]
(a) Chennai-Schools (b) Chenna-School
8. Which of the following formatting character is
(c) Type error (D) Chennai used to print exponential notation in upper case?
 [Ans. (a) Chennai-Schools] (a) %e (b) %E (c) %g (d) %n
3. Which of the following operator is used for  [Ans. (a) %e]
concatenation? 9. Which of the following is used as placeholders or
(a) + (b) & (c) * (d) = replacement fields which get replaced along with
format( ) function?
 [Ans. (a) +] (a) { } (b) < > (c) ++ (d) ^^
4. Defining strings within triple quotes allows  [Ans. (a) { }]
creating: 10. The subscript of a string may be:
(a) Single line Strings (b) Multiline Strings (a) Positive (b) Negative
(c) Double line Strings (d) Multiple Strings (c) Both (a) and (d) Either (a) or (b)
 [Ans. (d) Either (a) or (b)]
 [Ans. (b) Multiline Strings]
[95]

orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757


Unit II - Chapter 8
www.surabooks.com

Sura’s
Part - II
Answer the following questions
This material only for sample

➠ XII Std - Computer Science   www.surabooks.com

www.nammakalvi.org
>>> print (str1)
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
 (2 marks) print (str1)
1. What is String? NameError: name 'str1' is not defined
Ans. (i) String is a data type in python, which is
4. What will be the output of the following
used to handle array of characters.
python code?
(ii) String is a sequence of Unicode characters
str1 = "School"
that may be a combination of letters,
numbers, or special symbols enclosed print(str1*3)
within single, double or even triple quotes. Ans. Output : School School School
(iii) Example : 5. What is slicing?
'Welcome to learning Python' Ans. (i) Slice is a substring of a main string. A
"Welcome to learning Python" substring can be taken from the original
" "Welcome to learning Python" " string by using [] operator and index or

ns
subscript values.
2. Do you modify a string in Python?
(ii) Thus, [] is also known as slicing operator.

io
Ans. (i) Usually python does not support any Using slice operator, you have to slice one
modification in its strings. But, it provides a at or more substrings from a main string.
function replace() to change all occurrences Part - III
of a particular character in a string.
Answer the following questions
ic
(ii) General formate of replace function:
 (3 marks)
bl

replace("char1", "char2")
The replace function replaces all 1. Write a Python program to display the given
Pu

occurrences of char1 with char2. pattern.


(iii) Example : COMPUTER
COMPUTE
>>> str1="How are you" COMPUT
ra

>>> print (str1) COMPU


How are you COMP
Su

>>> print (str1.replace("o", "e")) COM


Hew are yeu CO
C
3. How will you delete a string in Python? Ans. str1 = input("Enter string")
Ans. Python will not allow deleting a particular str2 = ' '
character in a string. Whereas you can remove
index = len(str1)
entire string variable using del command.
for i in str1:
>>> str1="How about you"
str2 = str1[0 : index]
>>> print (str1)
index – = 1
How about you
print(str2)
>>> del str1

96
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

2. Write a short about the followings with


Sura’s
www.surabooks.com

➠ XII Std - Computer Science


5. Write a note about count( ) function in python.

Strings and String Manipulation


suitable example:
Ans.
(a) capitalize( ) (b) swapcase( )
Ans. Syntax Description Example
count Returns the >>> str1="Raja Raja
Descrip
Syntax Example (str, beg, number of Chozhan"
tion
end) substrings >>> print(str1.
(a) capitalize( ) Used to >>> city="chennai"
capitalize occurs count('Raja'))
>>> print(city.
the first within the 2
capitalize())
character given range. >>> print(str1.
Chennai
of the Remember count('r'))
string that substring 0
(b) swapcase( ) It will >>> str1="tAmiL may be a single >>> print(str1.
change NaDu" character. count('R'))
case of >>> print(str1. 2
Range (beg

ns
every
swapcase()) and end) >>> print(str1.
character
to its TaMIl nAdU arguments count('a'))

io
opposite are optional. 5
case vice- at If it is not >>> print(str1.
versa. given, python count('a',0,5))
3. What will be the output of the given python searched in 2
ic
program? whole string. >>> print(str1.
bl

str1 = "welcome" Search is case count('a',11))


sensitive. 1
str2 = "to school"
Pu

str3 = str1[:2]+str2[len(str2)-2:] Part - IV


print(str3)
Answer the following questions
Ans. weol
ra

 (5 marks)
4. What is the use of format( )? Give an example.
1. Explain about string operators in python with
Su

Ans. (i) The format( ) function used with strings is suitable example.
very versatile and powerful function used Ans. String Operators : Python provides the
for formatting strings. following operators for string operations. These
(ii) The curly braces { } are used as placeholders operators are useful to manipulate string.
or replacement fields which get replaced (i) Concatenation (+) : Joining of two or more
along with format( ) function. strings is called as Concatenation. The plus
(iii) num1=int (input("Number 1: ")) (+) operator is used to concatenate strings
num2=int (input("Number 2: ")) in python.
print ("The sum of {} and {} is {}". Example :
format(num1,num2,(num1+num2))) >>> "welcome" + "Python"
Output : 'welcomePython'
Number 1: 34 (ii) Append (+ =) : Adding more strings at
Number 2: 54 the end of an existing string is known as
append. The operator += is used to append
The sum of 34 and 54 is 88 a new string with an existing string.

97
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit II - Chapter 8
www.surabooks.com

Sura’s


➠ XII Std - Computer Science
Example :
>>> str1="Welcome to "
 
This material only for sample www.surabooks.com

www.nammakalvi.org
5. Write a program to create a mirror of the given
string. For example, "wel" = "lew".
>>> str1+="Learn Python" Ans. str1= input (“Enter a string”)
>>> print (str1) str2 = ‘ ‘
Welcome to Learn Python index = -1
(iii) Repeating (*) : The multiplication operator for i in str1:
(*) is used to display a string in multiple str2 = str1[index]
index - = 1
number of times.
print (“The mirror image of the string is”, str2)
Example :
>>> str1="Welcome " 6. Write a program to removes all the occurrences
of a give character in a string.
>>> print (str1*4)
Ans. str1 = input (“Enter string”)
Welcome Welcome Welcome Welcome
Ch = input (“Enter a character to be removed”)
Hands on Experience print (str1. Replace (ch, “ “ )
7. Write a program to append a string to another

ns
1. Write a python program to find the length of string without using += operator.
a string.
Ans. str1 = input (“Enter first string”)
Ans. str = input ("Enter a string")

io
str2 = input (“Enter second string”)
print (len(str)) at print(str1 + str2)
2. Write a program to count the occurrences of 8. Write a program to swap two strings.
each word in a given string. Ans. str1 = input (“Enter string 1”)
ic
Ans. Word = 1 Str2 = input (“Enter string 2”)
str = input ("Enter a string") temp = str1
bl

For i in str: str1 = str2


str2 = temp
Pu

If (i = = ‘ ‘):
Word = word + 1 print(“After swapping”)
print("Number of words", Word) print(str1. Str2)
9. Write a program to replace a string with
ra

3. Write a program to add a prefix text to all the


lines in a string. another string without using replace().
Ans. str1 = input (“Enter string”)
Su

Ans. import textwrap


str1 = input ("enter string") print (str1)
str1 = input (“Enter string to the replaced”)
t = textwrap. dedent (str1) print (str1)
w = textwrap. fill (t, width = 50)
f = textwrap. indent (w, 1*1) 10. Write a program to count the number of
characters, words and lines in a given string.
print ( )
Ans. str1 = input (“Enter string”)
print (f)
c=0
print ( )
w=1
4. Write a program to print integers with ‘*’ on for i in str1:
the right of specified width. if i ! = ‘ ‘ :
Ans. x = 4 c=c+1
y = 345 else:
w=w+1
print ("width 2 "+" (*<3d)". format (x))
x = str1. count (‘\n’) + 1
print ("width 6 "+" (*<7d)". format (y))
print (“Number of characters”, c - x + 1)
print (“Number of words”, w + x - 1)
print (“Number of lines”, x )
98
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

additional questions and Answers


Sura’s
www.surabooks.com

➠ XII Std - Computer Science

Strings and String Manipulation


Choose the Correct Answer 1 MARK 9. What is the output for the following
>>> s1 = "how"
1. Which of the following is used to handle array >>>s1[0] = ‘A’
of characters in python? (a) How (b) A
(a) Functions (b) Composition (c) Aow (d) Error
(c) String (d) Arguments  [Ans. (d) Error]
 [Ans. (c) String] 10. Which of the following operators are useful to
2. String are enclosed with do string manipulation?
(a) " (b) " " (a) +, - (b)*, / (c) + * (d)’, "
(c) '''''' '''''' (d) ''' '''  [Ans. (c) + *]
(e) all of these [Ans. (e) all of these] 11. Adding more strings at the end of an existing
string is known as
3. Which of the following allows creation of
(a) Con cat (b) Con catenation

ns
multiline strings
(c) Join (d) Append
(a) ' ' (b) '' ''
 [Ans. (d) Append]
(c) '''''' '''''' (d) none of these

io
(e) None of these  [Ans. (c) '''''' ''''''] 12. A substring can be taken from the original
string by using
4. Find the output for the following
at
(a) { } (b) ( ) (c) [ ] (d) < >
print (‘Greater Chennai cooperation’s  student’)  [Ans. (c) [ ]]
ic
(a) Greater Chennai Corporation’s student
(b) Greater Chennai Corporation 13. What is the output from the following
bl

statement?
(c) S Student
str1 = "welcome"
Pu

(d) Error : Invalid Syntax


print (str1[: : 3]
 [Ans. (d) Error : Invalid Syntax]
(a) come (b) ome
5. String index values are also called as (c) wce (d) wel
ra

(a) class (b) function  [Ans. (c) wce]


(c) subscript (d) arguments 14. What is the output from the following
Su

 [Ans. (c) subscript] statement?


6. Which of the following is used to access and str1 = "python"
manipulate the strings? print (str1 [: : - 2])
(a) Index value (b) Subscript (a) nhy (b) Pyt (c) hy (d) on
(c) Argument (d) Parameters  [Ans. (a) nhy]
(e) a or b [Ans. (e) a or b] 15. Which of the following operator is used to
7. The positive subscript always starts with construct strings?
(a) 0 (b) 1 (c) –1 (d) 0.1 (a) : (b) % (c) : : (d) #
 [Ans. (a) 0]  [Ans. (b) %]

8. The negative subscript is always begins with


16. Which of the following formatting operator is
(a) 0 (b) 1
used to represent signed decimal integer?
(c) –1 (d) –1.0
(a) % d or % i (b) %s or % c
 [Ans. (c) –1]
(c) %g or % x (d) %s or % e
 [Ans. (a) % d or % i]

99
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

www.surabooks.com This material only for sample

18. What is the use of title () function? Give


Sura’s
www.surabooks.com

➠ XII Std - Computer Science


3. Write the syntax and example of using string

Strings and String Manipulation


example. characters.
Ans. Ans. Syntax:
("String to be display with %val1 and %val2"
title( ) Returns a string >>> str1='education
 %(val1, val2))
in title case department'
Example :
>>> print(str1.title())
Education name = "Rajarajan"
Department mark = 98
print ("Name: %s and Marks: %d" 
Short Answers 3 MARKS
%(name,mark))
1. How the positive and negative subscript values Output :
are assigned? Give example.
Name: Rajarajan and Marks: 98
Ans. The positive subscript 0 is assigned to the first
character and n-1 to the last character, where 4. Write the usage of the following format string

ns
n is the number of characters in the string. The characters.
negative index assigned from the last character
(i) % c
to the first character in reverse order begins

io
with -1. at (ii) % d (or) % i
Example : (iii) % s
String S C H O O L Ans. (i) character
ic
Positive 0 1 2 3 4 5 (ii) Signed decimal integer
subscript (iii) String
bl

Built in –6 –5 –4 –3 –2 –1
5. Fill in the blanks
Pu

functions
Format Usage
2. Write a program to accept a string and print it character
in reverse order. ________
i) Unsigned decimal integer
Ans. str1 = input ("Enter a string: ")
ra

ii) % 0 ________
index=-1
while index >= -(len(str1)): iii) ________ Hexadecimal integer
Su

print ("Subscript[",index,"] : " + str1[index]) iv) % i ________


index += -1 Ans. (i) %u
Output : (ii) octal integer
Enter a string: welcome (iii) % c or %x
Subscript [ -1 ] : e (iv) signed decimal integer.
Subscript [ -2 ] : m
Subscript [ -3 ] : o
Subscript [ -4 ] : c
Subscript [ -5 ] : l
Subscript [ -6 ] : e
Subscript [ -7 ] : w

105
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit II - Chapter 8
www.surabooks.com

Sura’s ➠ XII Std - Computer Science


6. Write the formats string characters for the
following
 
This material only for sample www.surabooks.com

www.nammakalvi.org
10. Write the output of the following statements.
(i) ‘Python 2. 3’ . isalpha ()
(i) Exponential notation
(ii) ‘Python Program’ . is alnum ()
(ii) Floating point numbers
(iii) ‘Python’ . isupper ()
(iii) Short numbers in exponential notation
Ans. (i) False
Ans. (i) % e or % E
(ii) False
(ii) % f
(iii) False
(iii) % g or % G
11. Write the output for the following statement.
7. Write the description for the following escape (i) print ("PYTHON" . lower ())
sequence. (ii) print ("PYTHON" . islower ())
(i) \r (iii) print ("PYTHON" . isupper ())
(ii) \000 (iv) print ("PYTHON" . upper ())

ns
(iii) \v Ans. (i) python
Ans. (i) carriage return (ii) false

io
(ii) character with octal value (iii) false
(iii) vertical tab (iv) PYTHON
at
8. Write the output of the following statements. 12. Write a note on
ic
(i) print (len ("Corporation")) (i) isalnum ()
(ii) print ("school", Capitalize ()) (ii) isalpha ()
bl

(iii) print ("Welcome" center (15, ‘*’)) (iii) isdigit ()


Pu

Ans.
Ans. (i) 11
(i)
(ii) School
isalnum Returns True >>>str1=’Save Earth’
(iii) * * * * Welcome * * * *
() if the string >>>str1.isalnum()
ra

9. Write the output of the following statements. contains False


only letters The function returns
strl = ‘mammals’
Su

and digit. It False as space is an


(i) strl. find (‘ma’) returns False. alphanumeric character.
(ii) strl. find (‘ma’, 2) If the string >>>’Save1Earth’.
contains isalnum()
(iii) strl. find (‘ma’, 2, 4)
any special True
(iv) strl. find (‘ma’, 2, 5) character like
Ans. (i) 0 _, @, #, *, etc.
(ii) 3 (ii)
(iii) - 1 isalpha( ) Returns True >>>’Click123’.
if the string isalpha()
(iv) 3
contains False
only letters. >>>’python’.isalpha( )
Otherwise
True
return False.

106
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
(iii)

www.surabooks.com This material only for sample www.surabooks.com

Sura’s ➠ XII Std - Computer Science


Long Answers 5 MARKS

Strings and String Manipulation


isdigit( ) Returns True >>> str1=’Save Earth’
if the string 1. Write a python program to check whether the
>>>print(str1.isdigit( ))
contains only given string is palindrome or not.
False
numbers. Ans. str1 = input ("Enter a string: ")
Otherwise it str2 = ' '
returns False. index=-1
13. Write the out put for the following statement. for i in str1:
strl = "Raja Raja Chozhan" str2 += str1[index]
(i) print (strl . count (‘Raja’)) index -= 1
(ii) print (strl . count (‘R’)) print ("The given string = { } \n The Reversed
(iii) print (strl . count (‘A’))  string = { }".format(str1, str2))
(iv) print (strl . count (‘a’)) if (str1==str2):
(v) print (strl . count (‘a’, 0, 5)) print ("Hence, the given string is 
Palindrome")

ns
(vi) print (strl . count (‘a’, 11))
Ans. (i) 2 else:
(ii) 2 print ("Hence, the given is not a

io
(iii) 0 palindrome")
(iv) 5
at
2. Write a python program to print the following
(v) 2 pattern
ic
(vi) 1 *
14. Why ‘in’ and ‘not in’ operators are called **
bl

***
membership operator? Explain with example.
****
Ans. Membership Operators :
Pu

*****
(i) The ‘in’ and ‘not in’ operators can be used Ans. str1=' * '
with strings to determine whether a string i=1
is present in another string. Therefore, while i<=5:
ra

these operators are called as Membership print (str1*i)


Operators.
i+=1
Su

(ii) Example :
str1=input ("Enter a string: ") 3. Write a python program to display the number
str2="chennai" of vowels and consonants in the given string.
if str2 in str1: Ans. str1=input ("Enter a string: ")
print ("Found") str2="aAeEiIoOuU"
else: v,c=0,0
for i in str1:
print ("Not Found")
if i in str2:
(iii) Output : 1 v+=1
Enter a string: Chennai GHSS, Saidapet else:
Found c+=1
(iv) Output : 2 print ("The given string contains { } vowels and
Enter a string: Govt GHSS, Ashok Nagar  { } consonants".format(v,c))
Not Found

www.nammakalvi.org

107
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757

Potrebbero piacerti anche