Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
[45]
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
of elementary lexical components known as (iii) Python supports the following Arithmetic
Tokens. The normal token types are operators.
Su
46
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
www.surabooks.com This material only for sample
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
47
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit II - Chapter 5
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
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
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
49
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit II - Chapter 5
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
(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
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) Statements (b) Control 8. What is the output of the following snippet?
(c) Structure (d) Indentation T=1
Su
[61]
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
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
62
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
www.surabooks.com
Sura’s
Where,
www.surabooks.com
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
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
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)
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
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
s = (s* 10)+d
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
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
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
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
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
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
Ans.
Working of break statement
False
9. Write the syntax of working of continue
Condition
statement in for and while loop.
ra
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
Sura’s
www.surabooks.com
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
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
12 123
123
12
1234
1
ra
12345
Ans. i=1 Ans. (i) for i in range (5, 0,-1):
Su
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
[75]
Sura’s
This material only for sample
Evaluation
www.surabooks.com
www.nammakalvi.org
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
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
76
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
www.surabooks.com This material only for sample
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
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
(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
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
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
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
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
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
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
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
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
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
print(str1[::–1])
[Ans. (b) [ ]]
(a) Tamilnadu (b) Tmlau
7. What is stride?
(c) udanlimaT (d) udaNlimaT
(a) index value of slide operation
ra
Sura’s
Part - II
Answer the following questions
This material only for sample
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
96
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
www.surabooks.com This material only for sample
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
(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
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
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
99
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
www.surabooks.com This material only for sample
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
105
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
Unit II - Chapter 8
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
Ans.
Ans. (i) 11
(i)
(ii) School
isalnum Returns True >>>str1=’Save Earth’
(iii) * * * * Welcome * * * *
() if the string >>>str1.isalnum()
ra
106
orders@surabooks.com Ph: 81242 01000 / 812430 1000 / 96001 75757
(iii)
www.surabooks.com This material only for sample www.surabooks.com
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
(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