0% found this document useful (0 votes)
39 views13 pages

Xii CS Chapter 7 & 8 - Notes

The document is a study guide for a Computer Science course covering Python functions and string manipulation. It includes multiple-choice questions, short answer questions, and explanations of concepts such as function types, variable scope, and recursion. Additionally, it provides examples of Python code for various functions and operations.

Uploaded by

vhemavaradan7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views13 pages

Xii CS Chapter 7 & 8 - Notes

The document is a study guide for a Computer Science course covering Python functions and string manipulation. It includes multiple-choice questions, short answer questions, and explanations of concepts such as function types, variable scope, and recursion. Additionally, it provides examples of Python code for various functions and operations.

Uploaded by

vhemavaradan7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Hail Mary ! Praise the Lord !

AMALORPAVAM
HIGHER SECONDARY SCHOOL
PUDUCHERRY

XII – COMPUTER SCIENCE

7 • PYTHON FUNCTIONS

8 • STRINGS AND STRING


MANIPULATION
CHAPTER - 7
PYTHON FUNCTIONS
Part - I

Choose the best answer: (1 Mark)


1. A named blocks of code that are designed to do one specific job is called as
(a) Loop (b) Branching (c) Function (d) Block
2. A Function which calls itself is called as
(a) Built-in (b) Recursion (c) Lambda (d) return
3. Which function is called anonymous un-named function?
(a) Lambda (b) Recursion (c) Function (d) define
4. Which of the following keyword is used to begin the function block?
(a) define (b) for (c) finally (d) def
5. Which of the following keyword is used to exit a function block?
(a) define (b) return (c) finally (d) def
6. While defining a function which of the following symbol is used.
(a) ; (semicolon) (b) . (dot) (c) : (colon) (d) $ (dollar)
7. In which arguments the correct positional order is passed to a function?
(a) Required (b) Keyword (c) Default (d) Variable-length
8. Read the following statement and choose the correct statement(s).
I. In Python, you don’t have to mention the specific data types while defining function.
II. Python keywords can be used as function name.
(a) I is correct and II is wrong (b) Both are correct
(c) I is wrong and II is correct (d) Both are wrong
9. Pick the correct one to execute the given statement successfully.
if ____ : print(x, " is a leap year")
(a) x%2=0 (b) x%4==0 (c) x/4=0 (d) x%4=0
10. Which of the following keyword is used to define the function testpython(): ?
(a) define (b) pass (c) def (d) while
Part - II

Answer the following questions: (2 Marks)


1. What is function?
 Functions are named blocks of code that are designed to do specific job.
 Functions are nothing but a group of related statements that perform a specific task.
2. Write the different types of function.
Basically, we can divide functions into four types. They are:
 User-defined Functions
 Built-in Functions
 Lambda Functions
 Recursion Functions
3. What are the main advantages of function?
Main advantages of functions are
• It avoids repetition and makes high degree of code reusing.
• It provides better modularity for your application.
4. What is meant by scope of variable? Mention its types.
Scope of variable refers to the part of the program, where it is accessible, i.e., area where you
can refer (use) it.
There are two types of scopes - local scope and global scope.
5. Define global scope.
 A variable, with global scope can be used anywhere in the program.
 It can be created by defining a variable outside the scope of any function/block.
6. What is base condition in recursive function?
 The condition that is applied in any recursive function is known as base condition.
 A base condition is must in every recursive function otherwise it will continue to execute
like an infinite loop.
7. How to set the limit for recursive function? Give an example.
print(fact (2000)) will give Runtime Error after maximum recursion depth exceeded in
comparison. This happens because python stops calling recursive function after 1000 calls by
default. It also allows you to change the limit using sys.setrecursionlimit(limit_value).
Example:
import sys
sys.setrecursionlimit(3000)
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
print(fact (2000))
Part - III

Answer the following questions: (3 Marks)


1. Write the rules of local variable.

Rules of local variable:


 A variable with local scope can be accessed only within the function/block that it is created in.
 When a variable is created inside the function/block, the variable becomes local to it.
 A local variable only exists while the function is executing.
 The formal arguments are also local to function.
2. Write the basic rules for global keyword in python.
Rules of global Keyword:
 The basic rules for global keyword in Python are:
 When we define a variable outside a function, it’s global by default. You don’t have to use
global keyword.
 We use global keyword to read and write a global variable inside a function.
 Use of global keyword outside a function has no effect
3. What happens when we modify global variable inside the function?
When we modify the global variable from inside function, unbound local error will be displayed.
For eg:
c = 1 # global variable
def add():
c = c + 2 # increment c by 2
print(c)
add()
Output:
Unbound Local Error: local variable 'c' referenced before assignment
Without using the global keyword we cannot modify the global variable inside
the function but we can only access the global variable.
x = 0 # global variable
def add():
global x
x = x + 5 # increment by 2
print ("Inside add() function x value is :", x)
add()
print ("In main x value is :", x)
Output:
Inside add() function x value is : 5
In main x value is : 5
4. Differentiate ceil() and floor() function?
ceil() floor()
Returns the smallest integer greater than Returns the largest integer
or equal to x less than or equal to x

Syntax: Syntax:
math.ceil (x) math.floor (x)
import math import math
x= 26.7 x=26.7
y= -26.7 y=-26.7
z= -23.2 z=-23.2
print (math.ceil (x)) print (math.floor (x))
print (math.ceil (y)) print (math.floor (y))
print (math.ceil (z)) print (math.floor (z))
Output: Output:
27 26
-26 -27
-23 -24

5. Write a Python code to check whether a given year is leap year or not.
year = int(input("Enter a year: "))
if(year%4==0 and year%100!=0) or (year%400==0):
print("The year is a leap year")
else:
print("The year is not a leap year")

Output 1:
Enter a year: 1900
The year is not a leap year
>>>

Output 2:
Enter a year: 1996
The year is a leap year
>>>

Output 3:
Enter a year: 2000
The year is a leap year
6. What is composition in functions?
The value returned by a function may be used as an argument for another function in
a nested manner. This is called composition.
If we wish to take a numeric value or an expression as a input from the user, we take the input
string from the user using the function input() and apply eval() function to evaluate its value, for
example:
n2 = eval (input ("Enter an arithmetic expression: "))
Output:
Enter an arithmetic expression: 12.0+13.0 * 2
38.0
>>>
7. How recursive function works?
1. Recursive function is called by some external code.
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to continue recursion.
8. What are the points to be noted while defining a function?
 Function blocks begin with the keyword “def” followed by function name and parenthesis ().
 Any input parameters or arguments should be placed within these parentheses when you
define a function.
 The code block always comes after a colon (:) and is indented.
 The statement “return [expression]” exits a function, optionally passing back an expression
to the caller. A “return” with no arguments is the same as return None.
Part - IV
Answer the following questions: (5 Marks)
1. Explain the different types of function with an example.
Basically, we can divide functions into four types. They are:
 User-defined Functions
 Built-in Functions
 Lambda Functions
 Recursion Functions
1. User-defined Functions :
 Functions defined by the users themselves.
 Function blocks begin with the keyword “def” followed by function name and parenthesis ().
 The statement “return [expression]” exits a function,
Example:
def hello():
print (“hello - Python”)
return
2. Built-in functions:
 Functions that are inbuilt with in Python.
 There are many built-in functions that comes with the language python (for instance, the
print() function)
Example:
ord ( ) - Returns the ASCII value for the given Unicode character. This function is inverse of chr()
function.
chr ( )- Returns the Unicode character for the given ASCII value. This function is inverse of
ord()function.
3. Anonymous Functions:
 In Python, anonymous function is a function that is defined without a name.
 While normal functions are defined using the def keyword, in Python anonymous functions are
defined using the lambda keyword.
 Hence, anonymous functions are also called as lambda functions.
Syntax:
lambda [argument(s)] :expression
Example:
sum = lambda arg1, arg2: arg1 + arg2
print ('The Sum is :', sum(30,40))
print ('The Sum is :', sum(-30,40))
Output:
The Sum is : 70
The Sum is : 10
Recursive functions:
When a function calls itself is known as recursion.
Example :
def fact(n):
if n == 0:
return 1
else:
return n * fact (n-1)
print (fact (0))
print (fact (5))
Output:
1
120
2. Explain the scope of variables with an example.
Scope of variable refers to the part of the program, where it is accessible, i.e., area where you can
refer (use) it. We can say that scope holds the current set of variables and their values.
There are two types of scopes - local scope and global scope.
Local Scope:
A variable declared inside the function's body or in the local scope is known as localvariable.
Rules of local variable:
• A variable with local scope can be accessed only within the function/block that it is created in.
• When a variable is created inside the function/block, the variable becomes local to it.
• A local variable only exists while the function is executing.
• The formal arguments are also local to function.
Example : Create a Local Variable
def loc():
y=0 # local scope
print(y)
loc()
Output:
0

3. Explain the following built-in functions.


(a) id() (b) chr() (c) round() (d) type() (e) pow()
Function Description Syntax Example
id( ) id( ) Return id (object) x=15
the “identity” of an object. i.e. y='a'
the address of the object in print('address of x is :',id (x))
memory. print('address of y is :',id (y))
Note: the address of x and y Output:
may differ in your system. address of x is : 1357486752
address of y is : 13480736
chr( ) Returns the Unicode chr (i) c=65
character for the given ASCII d=43
value. This function is inverse print(chr (c))
of ord() function. printchr (d))
Output:
A
+
round( ) Returns the nearest integer to round x= 17.9
its input. (number y= 22.2
1. First argument [,ndigits]) z= -18.3
(number) is used to print('x value is rounded to', round(x))
specify the value to be print('y value is rounded to', round(y))
rounded. print('z value is rounded to', round(z))
2. Second argument Output:1
(ndigits) is used to x value is rounded to 18
specify the number y value is rounded to 22
of decimal digits z value is rounded to -18
desired after rounding. n1=17.89
print(round (n1,0))
print(round (n1,1))
print(round (n1,2))
Output:2
18.0
17.9
17.89
type ( ) Returns the type of object for type (object) x= 15.2
the given y= 'a'
single object. s= True
Note: This function print(type (x))
used with single object print(type (y))
parameter. print(type (s))
Output:
<class 'float'>
<class 'str'>
<class 'bool'>
pow ( ) Returns the computation of ab pow (a,b) a= 5
i.e.(a**b ) b= 2
a raised to the power of b. c= 3.0
print(pow(a,b))
print(pow(a,c))
print(pow(a+b,3))
Output:
25
125.0
343
4. Write a Python code to find the L.C.M. of two numbers.
#python code to find the L.C.M of two numbers
def lcm(x,y):
if x>y:
greater=x
else:
greater=y
while(True):
if (greater%x==0)and(greater%y==0):
lcm=greater
break
greater+=1
return lcm
num1=int(input("Type the first number:"))
num2=int(input("Type the second number:"))
print("The LCM of ", num1," and ",num2," is ",lcm(num1,num2))
Output:
Type the first number:4
Type the second number:7
The LCM of 4 and 7 is 28
5. Explain recursive function with an example.
Python recursive functions:
When a function calls itself is known as recursion. Recursion works like loop but sometimes it
makes more sense to use recursion than loop. recursive function calls itself. Imagine a process would
iterate indefinitely if not stopped by some condition! Such a process is known as infinite iteration.
The condition that is applied in any recursive function is known as base condition. A base condition is
must in every recursive function otherwise it will continue to execute like an infinite loop.
Overview of how recursive function works
1. Recursive function is called by some external code.
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to continue recursion.
Here is an example of recursive function used to calculate factorial.
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
print(fact (0))
print(fact (5))
Output:
1
120

CHAPTER - 8
STRINGS AND STRING
MANIPULATION
PART-I
Choose the best answer: (1 Mark)
1. Which of the following is the output of the following python code?
str1="TamilNadu"
print(str1[::-1])
(a) Tamilnadu (b) Tmlau (c) udanlimaT (d) udaNlimaT
2. What will be the output of the following code?
str1 = "Chennai Schools"
str1[7] = "-"
(a) Chennai-Schools (b) Chenna-School (c) Type error (d) Chennai
3. Which of the following operator is used for concatenation?
(a) + (b) & (c) * (d) =
4. Defining strings within triple quotes allows creating:
(a) Single line Strings (b) Multiline Strings
(c) Double line Strings (d) Multiple Strings
5. Strings in python:
(a) Changeable (b) Mutable (c) Immutable (d) flexible
6. Which of the following is the slicing operator?
(a) { } (b) [ ] (c) <> (d) ( )
7. What is stride?
(a) index value of slide operation (b) first argument of slice operation
(c) second argument of slice operation (d) third argument of slice operation
8. Which of the following formatting character is used to print exponential notation in upper case?
(a) %e (b) %E (c) %g (d) %n
9. Which of the following is used as placeholders or replacement fields which get replaced along with
format( ) function?
(a) { } (b) <> (c) ++ (d) ^^
10. The subscript of a string may be:
(a) Positive (b) Negative (c) Both (a) and (b) (d) Either (a) or (b)

Part -II
Answer the following questions (2 Marks)
1. What is String?
String is a sequence of Unicode characters that may be a combination of letters, numbers, or
special symbols enclosed within single, double or even triple quotes.
Example:
‘Welcome to learning Python’
“Welcome to learning Python”
‘‘‘Welcome to learning Python ’’’
2. Do you modify a string in Python?
No, Strings in python are immutable. That means, once you define a string modifications or
deletion is not allowed. If you want to modify the string, a new string value can be assign to the
existing string variable.
3. How will you delete a string in Python?
 Python will not allow deleting a particular character in a string.
 Whereas you can remove entire string variable using del command.
Example:
>>> str1="How about you"
>>> print (str1)
How about you
>>> del str1
>>> print (str1)
NameError: name 'str1' is not defined
4. What will be the output of the following python code?
str1 = “School”
print(str1*3)
Output:
SchoolSchoolSchool
5. What is slicing?
Slice is a substring of a main string. A substring can be taken from the original string by
using [ ] operator and index or subscript values. Thus, [ ] is also known as slicing operator.
Using slice operator, you have to slice one or more substrings from a main string.
General format of slice operation:
str[start:end]
Where start is the beginning index and end is the last index value of a character in the string.
Example:
>>> str1="THIRUKKURAL"
>>> print (str1[0:5])
THIRU
Part -III
Answer the following questions (3 Marks)
1. Write a Python program to display the given pattern
COMPUTER
COMPUTE
COMPUT
COMPU
COMP
COM
CO
C
Python Program:
str=”COMPUTER”
index = 0
for i in str:
print(str[:index+1])
index+=1
2. Write a short about the followings with suitable example:
(a) capitalize( ) (b) swapcase( )
(a)capitalize():
Syntax Description Example
capitalize( ) Used to capitalize the first character >>> city=”chennai”
of the string >>> print(city.capitalize())
Chennai
(b) swapcase( ) :
Syntax Description Example
swapcase( ) It will change case of >>> str1="tAmiL NaDu"
every character to its >>> print(str1.swapcase())
opposite case vice-versa. TaMIl nAdU

3. What will be the output of the given python program?


str1 = "welcome"
str2 = "to school"
str3=str1[:2]+str2[len(str2)-2:]
print(str3)
Output:
weol
4. What is the use of format( )? Give an example.
The format( ) function used with strings is very versatile and powerful function used for
formatting strings. The curly braces { } are used as placeholders or replacement fields which
get replaced along with format( ) function.
Example:
num1=int (input(“Number 1: “))
num2=int (input(“Number 2: “))
print (“The sum of { } and { } is { }”.format(num1, num2,(num1+num2)))
Out Put:
Number 1: 34
Number 2: 54
The sum of 34 and 54 is 88

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


Syntax Description Example
count(str, beg, end) Returns the number of >>> str1=”Raja Raja Chozhan”
substrings occurs within the >>> rint(str1.count('Raja'))
given range. Remember that 2
substring may be a single >>> print(str1.count('r'))
character. Range (beg and 0
end) arguments are optional. >>> print(str1.count('R'))
If it is not given, python 2
searched in whole string. >>> print(str1.count('a'))
Search is case sensitive. 5
>>> print(str1.count('a',0,5))
2
>>> print(str1.count('a',11))
1
Part -IV
Answer the following questions (5 Marks)
1. Explain about string operators in python with suitable example.
Python provides the following operators for string operations.
(i) Concatenation (+)
(ii) Append (+ =)
(iii) Repeating (*)
(iv) String slicing
(v) Stride when slicing string
These operators are useful to manipulate string.
(i) Concatenation (+)
Joining of two or more strings is called as Concatenation. The plus (+) operator is used to
concatenate strings in python.
Example
>>> "welcome" + "Python"
'welcomePython'
(ii) Append (+ =)
Adding more strings at the end of an existing string is known as append. The operator +=
is used to append a new string with an existing string.
Example
>>> str1="Welcome to "
>>> str1+="Learn Python"
>>> print (str1)
Welcome to Learn Python
(iii) Repeating (*)
The multiplication operator (*) is used to display a string in multiple number of times.
Example
>>> str1="Welcome "
>>> print (str1*4)
Welcome Welcome Welcome Welcome
(iv) String slicing
Slice is a substring of a main string. A substring can be taken from the original string by
using [ ] operator and index or subscript values. Thus, [ ] is also known as slicing operator.
Using slice operator, you have to slice one or more substrings from a main string.
General format of slice operation:
str[start:end]
Where start is the beginning index and end is the last index value of a character in the string.
Example 1: slice a substring from index 0 to 4
>>> print (str1[0:5])
THIRU
Example 2 :
>>> print (str1[:5])
THIRU
Example 3 :
>>> print (str1[6:])
KURAL
(v) Stride when slicing string:
When the slicing operation, you can specify a third argument as the stride, which refers to the
number of characters to move forward after the first character is retrieved from the string. The
default value of stride is 1.
Example:
>>> str1 = "Welcome to learn Python"
>>> print (str1[10:16:2])
er

You might also like