[go: up one dir, main page]

0% found this document useful (0 votes)
40 views45 pages

12CS em 01

The document discusses functions in programming languages. It covers topics like pure and impure functions, recursive functions, parameters and arguments. It provides examples and explanations of these concepts through questions and answers.
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)
40 views45 pages

12CS em 01

The document discusses functions in programming languages. It covers topics like pure and impure functions, recursive functions, parameters and arguments. It provides examples and explanations of these concepts through questions and answers.
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/ 45

Contents

Chapter Title Page


1 Functions 1
2 Data Abstraction 7
3 Scoping 11
4 Algorithmic Strategies 17
5 Python – Variables and Operators 24
6 Control Structures 31
7 Python Functions 37
8 Strings and String manipulations 47
9 List, Tuples, Set and Dictionary 52
10 Python Classes and objects 60
11 Database Concepts 66
12 Structured Query Language (SQL) 78
13 Python and CSV files 87
14 Importing C++ Programs in Python 95
15 Data Manipulation through SQL 101
16 Data Visualization using pyplot: Line chart, Pie chart 109
and Bar charts

Annexure-1 Additional Q & A 117


Annexure-2 Public Question Papers 224
Annexure-3 Practical Exercises 245
1 FUNCTIONS

I. Choose the best answer: (1 Mark)


1. The small sections of code that are used to perform a particular task is called
(A) Subroutines (B) Files (C) Pseudo code (D) Modules
2. Which of the following is a unit of code that is often defined within a greater code
structure?
(A) Subroutines (B) Function (C) Files (D) Modules
3. Which of the following is a distinct syntactic block?
(A) Subroutines (B) Function (C) Definition (D) Modules
4. The variables in a function definition are called as
(A) Subroutines (B) Function (C) Definition (D) Parameters
5. The values which are passed to a function definition are called
(A) Arguments (B) Subroutines (C) Function (D) Definition
6. Which of the following are mandatory to write the type annotations in the function
definition?
(A) Curly braces (B) Parentheses (C) Square brackets (D) indentations
7. Which of the following defines what an object can do?
(A) Operating System (B) Compiler (C) Interface (D) Interpreter
8. Which of the following carries out the instructions defined in the interface?
(A) Operating System (B) Compiler (C) Implementation (D) Interpreter
9. The functions which will give exact result when same arguments are passed are called
(A) Impure functions (B) Partial Functions
(C) Dynamic Functions (D) Pure functions
10. The functions which cause side effects to the arguments passed are called
(A) Impure function (B) Partial Functions
(C) Dynamic Functions (D) Pure functions
II. Answer the following questions: (2 Marks)
1. What is a subroutine?
Subroutines are small sections of code that are used to perform a particular task
that can be used repeatedly. In Programming languages these subroutines are called
as Functions.

..1..
12 – Computer Science

2. Define Function with respect to Programming language.


A function is a unit of code that is often defined within a greater code structure.
Specifically, a function contains a set of code that works on many kinds of inputs, like
variants, expressions and produces a concrete output.
3. Write the inference you get from X:=(78).
X:=(78) is a function definition. Here (78) is not an expression. Definitions bind
values to the name. Here, the value of 78 binds to the name X.
4. Differentiate interface and implementation.
Interface Implementation
Interface just defines what an object can Implementation carries out the
do, but won’t actually do it. instructions defined in the interface.
5. Which of the following is a normal function definition and which is recursive
function definition
i) let rec sum x y: return x + y
ii) let disp:
print ‘welcome’
iii) let rec sum num:
if (num!=0) then return num + sum (num-1)
else
return num
Answers:
(i) Recursive function
ii) Normal Function
iii) Recursive Function
III. Answer the following questions (3 Marks)
1. Mention the characteristics of Interface.
➢ The class template specifies the interfaces to enable an object to be created and
operated properly.
➢ An object's attributes and behaviour are controlled by sending functions to the
object.

..2..
12 – Computer Science

2. Why strlen is called pure function?


Each time you call the strlen() function with the same parameters, it always gives
the same correct answer. So, it is a pure function.
3. What is the side effect of impure function. Give example.
When a function depends on variables or functions outside of its definition block,
you can never be sure that the function will behave the same every time it’s called.
Example: random() function
4. Differentiate pure and impure function.
Pure Function Impure Function

The return value of the pure functions solely The return value of the impure functions
depends on its arguments passed. does not solely depend on its arguments
passed.
Hence, if you call the pure functions with the Hence, if you call the impure functions with
same set of arguments, you will always get the same set of arguments, you might get
the same return values. the different return values.
They do not have any side effects. They have side effects.

5. What happens if you modify a variable outside the function? Give an example.
One of the most popular groups of side effects is modifying the variable outside
of function.
For example
let y: = 0
(int) inc(int) x:
y: = y + x;
return (y)
In the above example the value of ‘y’ get changed inside the function definition
due to which the result will change each time. The side effect of the inc() function is
it is changing the data of the external visible variable ‘y’.

..3..
12 – Computer Science

IV. Answer the following questions (5 Marks)


1. What are called Parameters and write a note on
(i) Parameter without Type
(ii) Parameter with Type
Parameters are the variables in a function definition and arguments are the values
which are passed to a function definition through the function definition.
(i) Parameter without Type

let rec pow a b:=


if b=0 then 1
else a * pow a (b-1)

In the above function definition, the variables 'a' and 'b' are parameters and the
value which is passed to the variables 'a' and 'b' are arguments. We have also not
specified the datatype for 'a' and 'b'. This is an example of parameters without type.
(ii) Parameter with Type

let rec pow (a:int) (b:int) : int :=


if b=0 then 1
else a * pow a (b-1)

The parameters 'a' and 'b' are specified in the data type brackets () in the above
function definition. This is an example of parameters with type.
2. Identify in the following program
let rec gcd a b :=
if b <> 0 then gcd b (a mod b) else return a
i) Name of the function
ii) Identify the statement which tells it is a recursive function
iii) Name of the argument variable
iv) Statement which invoke the function recursively
v) Statement which terminates the recursion
Answers:
i) gcd
ii) let rec gcd a b
iii) a, b
..4..
12 – Computer Science

iv) if b <> 0 then gcd b (a mod b)


v) return a
3. Explain with example Pure and impure functions.
Pure function:
The return value of the pure functions solely depends on its arguments passed.
Hence, if you call the pure functions with the same set of arguments, you will always
get the same return values. They do not have any side effects.
Example:
strlen() function always gives the same correct answer every time you call with the
same parameters. So it is a pure function.
Impure function:
The return value of the impure functions does not solely depend on its arguments
passed. Hence, if you call the impure functions with the same set of arguments, you
might get the different return values. They have side effects.
For example, the mathematical function random() will give different outputs for the same
function call.
4. Explain with an example interface and implementation.
Interface:
An interface is a set of action that an object can do. Interface just defines what an object
can do, but won’t actually do it.
Implementation:
Implementation carries out the instructions defined in the interface.
For example, let's take the example of increasing a car’s speed.

ENGINE

getSpeed

No
Requi
red
Pull Fuel
Spe
Yes
Return

..5..
12 – Computer Science

➢ The person who drives the car doesn't care about the internal working.
➢ To increase the speed of the car he just presses the accelerator to get the desired
behaviour. Here the accelerator is the interface between the driver (the calling /
invoking object) and the engine (the called object).
➢ Internally, the engine of the car is doing all the things. It's where fuel, air, pressure,
and electricity come together to create the power to move the vehicle.
➢ All of these actions are separated from the driver, who just wants to go faster.
Thus, we separate interface from implementation.

..6..
2 DATA ABSTRACTION

I. Choose the best answer: (1 Mark)


1. Which of the following functions that build the abstract data type?
(A) Constructors (B) Destructors (C) recursive (D)Nested
2. Which of the following functions that retrieve information from the data type?
(A) Constructors (B) Selectors (C) recursive (D)Nested
3. The data structure which is a mutable ordered sequence of elements is called
(A) Built in (B) List (C) Tuple (D) Derived data
4. A sequence of immutable objects is called
(A) Built in (B) List (C) Tuple (D) Derived data
5. The data type whose representation is known are called
(A) Built in datatype (B) Derived datatype
(C) Concrete datatype (D) Abstract datatype
6. The data type whose representation is unknown are called
(A) Built in datatype (B) Derived datatype
(C) Concrete datatype (D) Abstract datatype
7. Which of the following is a compound structure?
(A) Pair (B) Triplet (C) single (D) quadrat
8. Bundling two values together into one can be considered as
(A) Pair (B) Triplet (C) single (D) quadrat
9. Which of the following allow to name the various parts of a multi-item object?
(A) Tuples (B) Lists (C) Classes (D) quadrats
10. Which of the following is constructed by placing expressions within square brackets?
(A) Tuples (B) Lists (C) Classes (D) quadrats
II. Answer the following questions: (2 Marks)
1. What is abstract data type?
Th e process of providing only the essentials and hiding the details is known as
abstraction. Abstract Data type (ADT) is a type (or class) for objects whose behavior
is defined by a set of value and a set of operations.
2. Differentiate constructors and selectors.
➢ Constructors are functions that build the abstract data type.
➢ Selectors are functions that retrieve information from the data type.

..7..
12 – Computer Science

3. What is a Pair? Give an example.


Any way of bundling two values together into one can be considered as a pair.
Some languages like Python provides a compound structure called Pair which is made
up of list or Tuple.
Example:
lst := [5, 10, 20]
4. What is a List? Give an example.
List is constructed by placing expressions within square brackets separated by
commas. Such an expression is called a list literal. The elements in the list can be of
any type, and it can be changed.
Example:
lst := [105, ”Aakash”, 14]
5. What is a Tuple? Give an example.
A tuple is a comma-separated sequence of values surrounded with parentheses.
The elements given in the tuple cannot be changed.
Example:
t := (10, 12)
III. Answer the following questions: (3 Marks)
1. Differentiate Concrete data type and abstract datatype.
Concrete data type Abstract datatype
In concrete data representation, a The definition of ADT only mentions
definition for each function is known. what operations are to be performed
but not how these operations will be
implemented.
2. Which strategy is used for program designing? Define that Strategy.
➢ The strategy followed in program design is Wishful Thinking.
➢ Wishful Thinking is the formation of beliefs and making decisions according to
what might be pleasing to imagine instead of by appealing to reality.
3. Identify Which of the following are constructors and selectors?
(a) N1=number( ) - Constructor
(b) accetnum(n1) - Selectors
(c) displaynum(n1) - Selectors

..8..
12 – Computer Science

(d) eval(a/b) - Selectors


(e) x,y= makeslope (m), makeslope(n) - Constructor
(f) display( ) - Selectors
4. What are the different ways to access the elements of a list. Give example.
The elements of the list can be accessed in two ways.
1] Multiple assignment:
In this method, which unpacks a list into its elements and binds each element to
a different name.
Example:
Ist := [10, 20]
x, y := lst
2] Element selection operator:
The value within the square brackets selects an element from the value of the
preceding expression.
Example:
lst = [10,20]
lst[0]
10
lst[1]
20
5. Identify Which of the following are List, Tuple and class ?
(a) arr [1, 2, 34] - List
(b) arr (1, 2, 34) - Tuple
(c) student [rno, name, mark] - Class
(d) day= (‘sun’, ‘mon’, ‘tue’, ‘wed’) - Tuple
(e) x= [2, 5, 6.5, [5, 6], 8.2] - List
(f) employee [eno, ename, esal, eaddress] - Class
IV. Answer the following questions: (5 Marks)
1. How will you facilitate data abstraction. Explain it with suitable example.
To facilitate data abstraction, you will need to create constructors and selectors.
➢ Constructors are functions that build the abstract data type.
➢ Selectors are functions that retrieve information from the data type.

..9..
12 – Computer Science

for example
Let's take an abstract datatype called city. This city object will hold the city's name,
and its latitude and longitude.
city = makecity (name, lat, lon)
✓ Here the function makecity (name, lat, lon) is the constructor. When it creates
an object city, the values name, lat and lon are sent as parameters.
✓ getname(city), getlat(city) and getlon(city) are selector functions that obtain
information from the object city.
2. What is a List? Why List can be called as Pairs. Explain with suitable example
✓ List is constructed by placing expressions within square brackets separated by
commas. Such an expression is called a list literal.
✓ The elements in the list can be of any type, and it can be changed.
Example:
lst := [10, 20]
10 and 20 can be accessed through Ist[0] and lst[1] respectively.
The above example mathematically we can represent.
✓ Any way of bundling two values together into one can be considered as a pair.
Lists are a common method to do so. Therefore, List can be called as Pairs.
Example:
lst[(0, 10), (1, 20)]
where 0 and 1 are index position and 10 and 20 are values. That is, the
elements of lst.
3. How will you access the multi-item. Explain with example.
You can use the structure construct in the OOP language to represent multi-part
objects where each part is named.
Consider the following pseudo code:
class Person:
creation( ) The new data type Person is the class
firstName := " " name, creation() is the function and
lastName := " " firstName, lastName, id, email are
id := " " variables.
email := " "

..10..
3 SCOPING

I. Choose the best answer: (1 Mark)


1. Which of the following refers to the visibility of variables in one part of a program to
another part of the same program.
(A) Scope (B) Memory
(C) Address (D) Accessibility
2. The process of binding a variable name with an object is called
(A) Scope (B) Mapping
(C) late binding (D) early binding
3. Which of the following is used in programming languages to map the variable and object?
(A) :: (B) := (C) = (D) ==
4. Containers for mapping names of variables to objects is called
(A) Scope (B) Mapping
(C) Binding (D) Namespaces
5. Which scope refers to variables defined in current function?
(A) Local Scope (B) Global scope
(C) Module scope (D) Function Scope
6. The process of subdividing a computer program into separate sub-programs is called
(A) Procedural Programming (B) Modular programming
(C) Event Driven Programming (D) Object oriented Programming
7. Which of the following security technique that regulates who can use resources in a
computing environment?
(A) Password (B) Authentication
(C) Access control (D) Certification
8. Which of the following members of a class can be handled only from within the
class?
(A) Public members (B) Protected members
(C) Secured members (D) Private members
9. Which members are accessible from outside the class?
(A) Public members (B) Protected members
(C) Secured members (D) Private members

..11..
12 – Computer Science

10. The members that are accessible from within the class and are also available to its
subclasses is called
(A) Public members (B) Protected members
(C) Secured members (D) Private members
II. Answer the following questions: (2 Marks)
1. What is a scope?
Scope refers to the visibility of variables, parameters and functions in one part of
a program to another part of the same program.
2. Why scope should be used for variable. State the reason.
➢ The definition is used to indicate which part of the program the variable can be
accessed or used.
➢ It is a good practice to limit a variable's scope to a single definition. This way,
changes inside the function can't affect the variable on the outside of the
function in unexpected ways.
3. What is Mapping?
The process of binding a variable name with an object is called mapping. = (equal
to sign) is used in programming languages to map the variable and object.
4. What do you mean by Namespaces?
Namespaces are containers for mapping names of variables to objects.
5. How Python represents the private and protected Access specifiers?
➢ Python prescribes a convention of prefixing the name of the variable or method
with single or double underscore to emulate the behaviour of protected and
private access specifiers.
➢ All members in a Python class are public by default.
III. Answer the following questions: (3 Marks)
1. Define Local scope with an example.
➢ Local scope refers to variables defined in current function.
➢ Always, a function will first look up for a variable name in its local scope. Only if it
does not find it there, the outer scopes are checked.
Example
Disp( ):
a := 7 → local scope
print a
..12..
12 – Computer Science

Disp( )
Output
7
2. Define Global scope with an example.
➢ A variable which is declared outside of all the functions in a program is known as
global variable.
➢ This means, global variable can be accessed inside or outside of all the functions
in a program.
Example
a := 10 → global scope
Disp( ):
a := 7 → local scope
print a
Disp()
print a
Output
7
10
3. Define Enclosed scope with an example.
➢ A function (method) with in another function is called nested function.
➢ A variable which is declared inside a function which contains another function
definition with in it, the inner function can also access the variable of the outer
function. This scope is called enclosed scope.
Example
Disp():
a := 10 → enclosed scope
Disp1()
print a
Disp1()
print a
Output
10
10
..13..
12 – Computer Science

4. Why access control is required?


Access control is a security technique that regulates who or what can view or use
resources in a computing environment. It is a fundamental concept in security that
minimizes risk to the object. In other words, access control is a selective restriction
of access to data.
5. Identify the scope of the variables in the following pseudo code and write its output.
color:= Red
mycolor():
b:=Blue
myfavcolor():
g:=Green
print color, b, g
myfavcolor()
print color, b
mycolor()
print color
Scope of variables:
color → global scope
b → enclosed scope
g → local scope
Output
Red Blue Green
Red Blue
Red
IV. Answer the following questions: (5 Marks)
1. Explain the types of scopes for variable or LEGB rule with example.
The LEGB rule is used to decide the order in which the scopes are to be searched
for scope resolution.

Local (L) Defined inside function/class.


Enclosed (E) Defined inside enclosing functions.
Global (G) Defined at the uppermost level.
Built-in (B) Reserved names in built-in functions (modules).

..14..
12 – Computer Science

BUILT-IN

GLOBAL

ENCLOSED
LOCAL

Local scope:
➢ Local scope refers to variables defined in current function.
➢ Always, a function will first look up for a variable name in its local scope. Only if it
does not find it there, the outer scopes are checked.
Enclosed scope:
➢ A function (method) with in another function is called nested function.
➢ A variable which is declared inside a function which contains another function
definition with in it, the inner function can also access the variable of the outer
function. This scope is called enclosed scope.
Global scope:
➢ A variable which is declared outside of all the functions in a program is known as
global variable.
➢ This means, global variable can be accessed inside or outside of all the functions
in a program.
Built-in scope:
➢ The built-in scope has all the names that are pre-loaded into the program scope
when we start the compiler or interpreter.
➢ Any variable or module which is defined in the library functions of a programming
language has Built-in or module scope.

..15..
12 – Computer Science

Example
Built-in/module scope → library files
a := 10 → global scope
Disp():
b := 7 → enclosed scope
Disp1()
c := 5 → local scope
print a, b, c
Disp1()
Disp()
Output
10
7
5
2. Write any Five Characteristics of Modules.
1. Modules contain instructions, processing logic, and data.
2. Modules can be separately compiled and stored in a library.
3. Modules can be included in a program.
4. Module segments can be used by invoking a name and some parameters.
5. Module segments can be used by other modules.
3. Write any five benefits in using modular programming.
❖ Less code to be written.
❖ Programs can be designed more easily because a small team deals with only a
small part of the entire code.
❖ Code is short, simple and easy to understand.
❖ Errors can easily be identified, as they are localized to a subroutine or function.
❖ The same code can be used in many applications.
❖ Modular programming allows many programmers to collaborate on the same
application.
❖ The scoping of variables can easily be controlled.

..16..
4 ALGORITHMIC STRATEGIES

I. Choose the best answer: (1 Mark)


1. The word comes from the name of a Persian mathematician Abu Ja’far Mohammed
ibn-i Musa al Khowarizmi is called?
(A) Flowchart (B) Flow (C) Algorithm (D) Syntax
2. From the following sorting algorithms which algorithm needs the minimum number
of swaps?
(A) Bubble sort (B) Quick sort
(C) Merge sort (D) Selection sort
3. Two main measures for the efficiency of an algorithm are
(A) Processor and memory (B) Complexity and capacity
(C) Time and space (D) Data and space
4. The complexity of linear search algorithm is
(A) O(n) (B) O(log n) (C) O(n2) (D) O(n log n)
5. From the following sorting algorithms which has the lowest worst-case complexity?
(A) Bubble sort (B) Quick sort
(C) Merge sort (D) Selection sort
6. Which of the following is not a stable sorting algorithm?
(A) Insertion sort (B) Selection sort (C) Bubble sort (D) Merge sort
7. Time complexity of bubble sort in best case is
(A) θ (n) (B) θ (nlogn) (C) θ (n2) (D) θ (n logn)
8. The Θ notation in asymptotic evaluation represents
(A) Base case (B) Average case
(C) Worst case (D) NULL case
9. If a problem can be broken into subproblems which are reused several times, the
problem possesses which property?
(A) Overlapping subproblems (B) Optimal substructure
(C) Memoization (D) Greedy
10. In dynamic programming, the technique of storing the previously calculated values is
called?
(A) Saving value property (B) Storing value property
(C) Memoization (D) Mapping

..17..
12 – Computer Science

II. Answer the following questions: (2 Marks)


1. What is an Algorithm?
An algorithm is a finite set of instructions to accomplish a particular task.
2. Define Pseudo code.
Pseudo code is a notation similar to programming languages. It is a mix of
programming language-like constructs and plain English.
3. Who is an Algorist?
An Algorist is someone who is skilled in algorithms designing, logic and problem
solving.
4. What is Sorting?
The process of arranging the list items in ascending or descending order is called
sorting.
Example
✓ Bubble Sorting
✓ Selection sorting
✓ Insertion Sorting
5. What is searching? Write its types.
Searching is the process of finding a particular value from the list.
The different types are
✓ Linear search
✓ Binary search
III. Answer the following questions: (3 Marks)
1. List the characteristics of an algorithm.
i) Input ii) Output iii) Finiteness iv) Definiteness
v) Effectiveness vi) Correctness vii) Simplicity viii) Unambiguous
ix) Feasibility x) Portable xi) Independent
2. Discuss about Algorithmic complexity and its types.
Computer resources are limited. Efficiency of an algorithm is defined by the
utilization of time and space complexity.
➢ Time Complexity:
The Time complexity of an algorithm is given by the number of steps taken by the
algorithm to complete the process.

..18..
12 – Computer Science

➢ Space Complexity:
Space complexity of an algorithm is the amount of memory required to run to its
completion.
3. What are the factors that influence time and space complexity.
The efficiency of an algorithm depends on how efficiently it uses time and memory
space. The time efficiency of an algorithm is measured by different factors.
✓ Speed of the machine
✓ Compiler and other system Software tools
✓ Operating System
✓ Programming language used
✓ Volume of data required
4. Write a note on Asymptotic notation.
Asymptotic Notations are languages that uses meaningful statements about time
and space complexity. The following three asymptotic notations are mostly used to
represent time complexity of algorithms:
(i) Big O → worst-case
(ii) Big Ω → best-case
(iii) Big  → average-case
5. What do you understand by Dynamic programming?
Dynamic programming is an algorithmic design method that can be used when the
solution to a problem can be viewed as the result of a sequence of decisions.
Steps to do Dynamic programming
➢ The given problem will be divided into smaller overlapping sub-problems.
➢ An optimum solution for the given problem can be achieved by using result of
smaller sub-problem.
➢ Dynamic algorithms use Memoization.
IV. Answer the following questions: (5 Marks)
1. Explain the characteristics of an algorithm.
❖ Input: Zero or more quantities to be supplied.
❖ Output: At least one quantity is produced.
❖ Finiteness: Algorithms must terminate after finite number of steps.

..19..
12 – Computer Science

❖ Definiteness: All operations should be well defined. For example, operations


involving division by zero or taking square root for negative number are
unacceptable.
❖ Effectiveness: Every instruction must be carried out effectively.
❖ Correctness: The algorithms should be error free.
❖ Simplicity: Easy to implement.
❖ Unambiguous: Algorithm should be clear and unambiguous. Each of its steps and
their inputs/outputs should be clear and must lead to only one meaning.
❖ Feasibility: Should be feasible with the available resources.
❖ Portable: An algorithm should be generic, independent of any programming
language or an operating system able to handle all range of inputs.
❖ Independent: An algorithm should have step-by-step directions, which should be
independent of any programming code.
2. Discuss about Linear search algorithm.
Linear search also called sequential search is a sequential method for finding a
particular value in a list. This method checks the search element with each element in
sequence until the desired element is found or the list is exhausted. In this searching
algorithm, list need not be ordered.
Pseudo code
1. Traverse the array using for loop
2. In every iteration, compare the target search key value with the current value
of the list.
✓ If the values match, display the current index and value of the array.
✓ If the values do not match, move on to the next array element.
3. If no match is found, display the search element not found.
For example
Consider the following array
a[] = {10, 12, 20, 25, 30} will be as follows,
a
Index 0 1 2 3 4
Values 10 12 20 25 30

..20..
12 – Computer Science

If you search for the number 25, the index will return to 3. If the searchable number
is not in the array, for example, if you search for the number 70, it will return -1.
3. What is Binary search? Discuss with example.
❖ Binary search also called half-interval search algorithm.
❖ It finds the position of a search element within a sorted array.
❖ The binary search algorithm can be done as divide-and-conquer search algorithm
and executes in logarithmic time.
Pseudo code for Binary search
1. Start with the middle element:
✓ If the search element is equal to the middle element of the array, then return
the index of the middle element.
✓ If not, then compare the middle element with the search value.
✓ If the search element is greater than the number in the middle index, then
select the elements to the right side of the middle index, and go to Step-1.
✓ If the search element is less than the number in the middle index, then select
the elements to the left side of the middle index, and start with Step-1.
2. When a match is found, display success message with the index of the element
matched.
3. If no match is found for all comparisons, then display unsuccessful message.
For example:
Using binary search, let's assume that we are searching for the location or index
of value 60.

❖ find index of middle element, use mid=low+(high-low)/2


low = 0, high = 9
mid = 0+(9-0)/2 = 4

❖ The mid value 50 is smaller than the target value 60. We have to change the value
of low to mid + 1 and find the new mid value again.
low = 5, high = 9
mid = 5 + ( 9 – 5 ) / 2 = 7

..21..
12 – Computer Science

❖ The mid value 80 is greater than the target value 60. We have to change the value
of high to mid - 1 and find the new mid value again.
low = 5, high = 6
mid = 5 + ( 6 – 5 ) / 2 = 5

❖ Now we compare the value stored at location 5 with our search element. We
found that it is a match.
❖ We can conclude that the search element 60 is found at lcoation or index 5.
4. Explain the Bubble sort algorithm with example.
➢ Bubble sort is a simple, it is too slow and less efficient when compared to insertion sort
and other sorting methods.
➢ The algorithm starts at the beginning of the list of values stored in an array. It compares
each pair of adjacent elements and swaps them if they are in the unsorted order.
➢ This comparison and passed to be continued until no swaps are needed.
Let's consider an array with values {15, 11, 16, 12, 14, 13} Below, we have a
pictorial representation of how bubble sort will sort the given array.

The above pictorial example is for iteration-1. Similarly, remaining iteration can be
done. At the end of all the iterations we will get the sorted values in an array as given
below:
11 12 13 14 15 16

..22..
TECH EASY 12 – Computer Science

5. Explain the concept of Dynamic programming with suitable example.


❖ Dynamic programming algorithm can be used when the solution to a problem can
be viewed as the result of a sequence of decisions.
❖ Dynamic programming approach is similar to divide and conquer. The given
problem is divided into smaller and yet smaller possible sub-problems.
❖ It is used whenever problems can be divided into similar sub-problems. so that
their results can be re-used to complete the process.
❖ For every inner sub problem, dynamic algorithm will try to check the results of the
previously solved sub-problems. The solutions of overlapped sub-problems are
combined in order to get the better solution.
Steps to do Dynamic programming
➢ The given problem will be divided into smaller overlapping sub-problems.
➢ An optimum solution for the given problem can be achieved by using result of smaller
sub-problem.
➢ Dynamic algorithms uses Memoization.
Fibonacci Series – An example
Fibonacci series generates the subsequent number by adding two previous
numbers.
Fibonacci Iterative Algorithm with Dynamic programming approach
Step - 1: Print the initial values of Fibonacci f0 and f1
Step - 2: Calculate fib = f0 + f1
Step - 3: Print the value of fib
Step - 4: Assign f0 = f1, f1 = fib
Step - 5: Goto Step - 2 and repeat until the specified number of terms generated.
If the number of terms is 10 then the output of the Fibonacci series is :
0 1 1 2 3 5 8 13 21 34 55

..23.. THAAI VIRUDHUNAGAR


5 PYTHON – VARIABLES AND OPERATORS

I. Choose the best answer: (1 Mark)


1. Who developed Python?
A) Ritche B) Guido Van Rossum
C) Bill Gates D) Sunder Pitchai
2. The Python prompt indicates that Interpreter is ready to accept instruction.
A) >>> B) <<< C) # D) <<
3. Which of the following shortcut is used to create new Python Program?
A) Ctrl + C B) Ctrl + F C) Ctrl + B D) Ctrl + N
4. Which of the following character is used to give comments in Python Program?
A) # B) & C) @ D) $
5. This symbol is used to print more than one item on a single line.
A) Semicolon(;) B) Dollor($) C) comma(,) D) Colon(:)
6. Which of the following is not a token?
A) Interpreter B) Identifiers C) Keyword D) Operators
7. Which of the following is not a Keyword in Python?
A) break B) while C) continue D) operators
8. Which operator is also called as Comparative operator?
A) Arithmetic B) Relational C) Logical D) Assignment
9. Which of the following is not Logical operator?
A) and B) or C) not D) Assignment
10. Which operator is also called as Conditional operator?
A) Ternary B) Relational C) Logical D) Assignment
II. Answer the following questions: (2 Marks)
1. What are the different modes that can be used to test Python Program ?
Interactive mode and Script mode are the two modes that can be used to test
python program.
2. Write short notes on Tokens.
Python breaks each logical line into a sequence of elementary lexical components
known as Tokens.

..24..
12 – Computer Science

The normal token types are


1) Identifiers
2) Keywords
3) Operators
4) Delimiters and
5) Literals
3. What are the different operators that can be used in Python ?
❖ Arithmetic operators
❖ Relational or Comparative operators
❖ Logical operators
❖ Assignment operators
❖ Conditional Operator
4. What is a literal? Explain the types of literals ?
Literal is a raw data given to a variable or constant. In Python, there are various
types of literals.
1) Numeric
2) String
3) Boolean
5. Write short notes on Exponent data?
An Exponent data contains decimal digit part, decimal point, exponent part
followed by one or more digits.
Example : 12.E04, 24.e04
III. Answer the following questions: (3 Marks)
1. Write short notes on Arithmetic operator with examples.
An arithmetic operator is a mathematical operator that takes two operands and
performs a calculation on them.
Arithmetic Operators:
+, -, *, /, % (modulus), ** (exponent) and // (integer division)
Example:
If the value is a=100 and b=10
(i) a + b = 110 (ii)a % 30 = 10
(iii) a // 30 = 3 (iv) a**2 = 10000

..25..
12 – Computer Science

2. What are the assignment operators that can be used in Python?


➢ In Python, = is a simple assignment operator to assign values to variable.
➢ There are various compound operators in Python like +=, -=, *=, /=, %=, **= and
//= are also available.
Assignment Operators:
=, +=, -=, *=, /=, %=,**= and //=
Example:
(i) x = 10 (ii) x += 20 → x = x + 20 (iii) x //= 3 → x = x // 3
3. Explain Ternary operator with examples.
➢ Ternary operator is also known as conditional operator that evaluate something
based on a condition being true or false.
➢ It simply allows testing a condition in a single line replacing the multiline if-else
making the code compact.
Syntax:
Variable_Name = [on_true] if [Test expression] else [on_false]
Example:
min = 50 if 49<50 else 70

4. Write short notes on Escape sequences with examples.


➢ In Python strings, the backslash "\" is a special character, also called the "escape"
character.
➢ It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a
newline, and "\r" is a carriage return.
Escape Description Example Output
sequence
character
\\ Backslash >>> print("\\test") \test
\’ Single-quote >>> print("Doesn\'t") Doesn't
\” Double-quote >>> print("\"Python\"") "Python"
\n New line >>>print("Python\nLanguage") Python
Language
\t Tab >>>print("Hi \t Hello") Hi Hello

..26..
12 – Computer Science

5. What are string literals? Explain.


➢ In Python a string literal is a sequence of characters surrounded by quotes.
➢ Python supports single, double and triple quotes for a string.
➢ A character literal is a single character surrounded by single or double quotes. The
value with triple-quote "' '" is used to give multi-line string literal.
Example:
s = ”Python”
c = “P”
m = ‘‘‘This is a multiline string with more than one lines’’’
IV. Answer the following questions: (5 Marks)
1. Describe in detail the procedure Script mode programming.
➢ Basically, a script is a text file containing the Python statements.
➢ Python Scripts are reusable code. Once the script is created, it can be executed
again and again without retyping.
➢ The Scripts are editable.
Creating and Saving Scripts in Python
1. Choose File → New File or press Ctrl + N in Python shell window that appears an
untitled blank script text editor.
2. Type the following code
a =100
b = 350
c = a+b print ("The Sum=", c)
3. Choose File → Save or Press Ctrl + S. Now, Save As dialog box appears on the
screen.
4. Type the file name in File Name box. Python files are by default saved with
extension .py.
Executing Python Script
1. Choose Run → Run Module or Press F5
2. If your code has any error, it will be shown in red color in the IDLE window, and
Python describes the type of error occurred.
3. To correct the errors, go back to Script editor, make corrections, save the file using
Ctrl + S or File → Save and execute it again.
4. For all error free code, the output will appear in the IDLE window of Python.
..27..
12 – Computer Science

2. Explain input() and print() functions with examples.


input( ) function:
In Python, input( ) function is used to accept data as input at run time.
The syntax is,
Variable = input (“prompt string”)
✓ Where, prompt string is a statement or message to the user, to know what input
can be given.
Example 1: input( ) with prompt string
>>> city=input (“Enter Your City: ”)
Enter Your City: Madurai
✓ If prompt string is not given in input( ) no message is displayed on the screen, thus,
the user will not know what is to be typed as input.
Example 2:input( ) without prompt string
>>> city=input()
Rajarajan
>>> print (“I am from”, city)
I am from Rajarajan
Note that in the above example, the user will not know what is to be typed
as input.
❖ input() accepts all data as string or characters but not as numbers. The int( )
function is used to convert string data as integer data explicitly.
print() function:
❖ In Python, the print() function is used to display result on the screen.
❖ It displays an entire statement which is specified within print ( ).
The syntax is,
print( “String’’ )
print( variable )
print( “string”, variable )
print( “string1”, varl, “string2”’, var2 )
Examples:
(1) >>>print(“Welcome’’)
Welcome

..28..
12 – Computer Science

(2) >>>x = 5
>>>print(x)
5
(3) >>>print( “The value of x = ”,x)
The value of x = 5
(4) >>>x = 2
>>>y = 3
>>>print( “ The sum of “,x,” and “,y,” is “, x+y )
The sum of 2 and 3 is 5
❖ The print ( ) evaluates the expression before printing it on the monitor.
❖ Comma ( , ) is used as a separator in print ( ) to print more than one item.
3. Discuss in detail about Tokens in Python.
Tokens:
Python breaks each logical line into a sequence of elementary lexical components
known as Tokens.
The normal token types are
1) Identifiers
2) Keywords
3) Operators
4) Delimiters and
5) Literals.
Whitespace separation is necessary between tokens
1) Identifiers:
An Identifier is a name used to identify a variable, function, class, module or
object.
➢ An identifier must start with an alphabet (A..Z or a..z) or underscore ( _ ).
➢ Identifiers may contain digits (0 .. 9)
➢ Python identifiers are case sensitive i.e. uppercase and lowercase letters
are distinct.
➢ Identifiers must not be a python keyword.
➢ Python does not allow punctuation character such as %,$, @ etc., within
identifiers.
Examples : Sum, total_marks, regno, num1
..29..
12 – Computer Science

2) Keywords:
➢ Keywords are special words used by Python interpreter to recognize the
structure of program.
➢ As these words have specific meaning for interpreter, they cannot be used for
any other purpose.
Few python’s keywords are for, while, lamba, del, if, and, or,…
3) Operators:
➢ In computer programming languages operators are special symbols which
represent computations, conditional matching etc.
➢ Operators are categorized as Arithmetic, Relational, Logical, Assignment etc.
➢ Value and variables when used with operator are known as operands.
4) Delimiters:
➢ Python uses the symbols and symbol combinations as delimiters in expressions,
lists, dictionaries and strings.
➢ The following are few delimiters:
( ) [ ] { }
, : . ; ; “
5) Literals:
➢ Literal is a raw data given to a variable or constant.
➢ In Python, there are various types of literals.
1) Numeric
2) String
3) Boolean

..30..
6 CONTROL STRUCTRES

I. Choose the best answer: (1 Mark)


1. How many important control structures are there in Python?
A) 3 B) 4 C) 5 D) 6
2. elif can be considered to be abbreviation of
A) nested if B) if..else C) else if D) if..elif
3. What plays a vital role in Python programming?
A) Statements B) Control C) Structure D) Indentation
4. Which statement is generally used as a placeholder?
A) continue B) break C) pass D) goto
5. The condition in the if statement should be in the form of
A) Arithmetic or Relational expression B) Arithmetic or Logical expression
C) Relational or Logical expression D) Arithmetic
6. Which is the most comfortable loop?
A) do..while B) while C) for D) if..elif
7. What is the output of the following snippet?
i=1
while True:
if i%3 ==0:
break
print(i,end='')
i +=1
A) 12 B) 123 C) 1234 D) 124
8. What is the output of the following snippet?
T=1
while T:
print(True)
break
A) False B) True C) 0 D) 1
9. Which amongst this is not a jump statement?
A) for B) pass
C) continue D) break

..31..
12 – Computer Science

10. Which punctuation should be used in the blank?


if <condition>_
statements-block 1
else:
statements-block 2
A) ; B) : C) :: D) !
II. Answer the following questions: (2 Marks)
1. List the control structures in Python.
1) Sequential
2) Alternative or Branching
3) Iterative or Looping
2. Write note on break statement.
➢ The break statement terminates the loop containing it.
➢ When the break statement is executed, the control flow of the program comes
out of the loop and starts executing the segment of code after the loop structure.
➢ If break statement is inside a nested loop, break will terminate the innermost loop.
Syntax:
break
3. Write is the syntax of if .. else statement.
Syntax:
if <condition>:
statements-block 1
else:
statements-block 2
4. Define control structure.
A program statement that causes a jump of control from one part of the program
to another is called control structure or control statement.
5. Write note on range () in loop.
range() generates a list of values starting from start till stop-1.
The syntax is
range (start, stop[,step])
Where,
start – refers to the initial value
..32..
12 – Computer Science

stop – refers to the final value


step – refers to increment value, this is optional part.
Example:
(i) range(1, 10) → start from 1 and end at 9
(ii) range(1, 10, 2) → returns 1 3 5 7 9
III. Answer the following questions: (3 Marks)
1. Write a program to display
A
AB
ABC
ABCD
ABCDE
Program :
for i in range(65, 70):
for j in range(65, i+1):
print(chr(j), end='\t')
print('\n')
2. Write note on if .. else structure.
The if .. else statement is used to choose between two alternatives based on a
condition.
Syntax:
if <condition>:
statements-block 1
else:
statements-block 2
Example:
a = int(input("Enter any number :"))
if a%2==0:
print (a, " is an even number")
else:
print (a, " is an odd number")
Output:
1) Enter any number :56 2) Enter any number :67
56 is an even number 67 is an odd number

..33..
TECH EASY

3. Using if .. else .. elif statement write a suitable program to display largest of 3


numbers.
Program :
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
c=int(input("Enter the third number:"))
if (a>b) and (a>c):
print(a, " is the largest number")
elif (b>c):
print(b, " is the largest number ")
else:
print(c, " is the largest number ")
4. Write the syntax of while loop.
Syntax:
while <condition>:
statements block 1
[else:
statements block2]
5. List the differences between break and continue statements.
➢ The break statement terminates the loop when it is executed.
➢ Continue statement is used to skip the remaining part of a loop and start with next
iteration.
IV. Answer the following questions: (5 Marks)
1. Write a detail note on for loop.
➢ for loop is the most comfortable loop. It is also an entry check loop.
➢ The condition is checked in the beginning of the loop and if it is True then the body
of the loop is executed, otherwise the loop is not executed.
Syntax:
for counter_variable in sequence:
statements-block 1
[else:
statements-block 2]
✓ The counter_variable mentioned in the syntax is similar to the control variable.
..34..
12 – Computer Science

✓ The sequence refers to the initial, final and increment value.


✓ Usually in Python, for loop uses the range() function in the sequence to specify
the initial, final and increment values.
The syntax of range() is
range (start, stop[,step])
where,
start – refers to the initial value
stop – refers to the final value
step – refers to increment value
Example :
for i in range(2, 10, 2):
print (i, end=' ')
Output:
2468
2. Write a detail note on if .. else .. elif statement with suitable example.
When we need to construct a chain of if statement(s) then ‘elif’ clause can be used
instead of ‘else’.
Syntax:
if <condition-1>:
statements-block 1
elif <condition-2>:
statements-block 2
else:
statements-block n
✓ condition-1 is tested if it is true then 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.
Example:
a=int(input("Enter the first number: "))
b=int(input("Enter the second number: "))
c=int(input("Enter the third number: "))

..35..
12 – Computer Science

if (a>b) and (a>c):


print(a, " is the largest number")
elif (b>c):
print(b, " is the largest number ")
else:
print(c, " is the largest number ")
Output:
Enter the first number: 7
Enter the second number: 22
Enter the third number: 15
22 is the largest number
3. Write a program to display all 3 digit odd numbers.
Program:
for i in range(101,1000,2):
print(i, end='\t')
4. Write a program to display multiplication table for a given number.
Program:
n = int(input("Enter a Number :"))
x = int(input("Enter number of terms :"))
for i in range(1, x+1):
print(i, " x ", n, " = ", i*n)

..36..
7 PYTHON FUNCTIONS

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
II. Answer the following questions: (2 Marks)
1. What is function?
Functions are named blocks of code that are designed to do specific job.

..37..
12 – Computer Science

2. Write the different types of function.


❖ User-defined Functions
❖ Built-in Functions
❖ Lambda Functions
❖ Recursion Functions
3. What are the main advantages of function?
➢ 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.
There are two types of scopes:
i) local scope and
ii) 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.
➢ 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))
..38..
12 – Computer Science

III. Answer the following questions: (3 Marks)


1. Write the 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 format arguments are also local to function.
2. Write the basic rules for global keyword in python.
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 try to modify global variable inside the function an “Unbound Local
Error” will occur.
❖ Without using the global keyword, we cannot modify the global variable inside the
function but we can only access the global variable.
4. Differentiate ceil() and floor() function?
floor():
It returns the largest integer less than or equal to x.
Syntax:
math.floor(x)
Example:
x = 26.7
print(math.floor(x))
Output:
26
ceil():
It returns the smallest integer greater than or equal to x.
Syntax:
math.ceil(x)
..39..
12 – Computer Science

Example:
x = 26.7
print(math.ceil(x))
Output:
27
5. Write a Python code to check whether a given year is leap year or not.
n=int(input("Enter a Year : "))
if n%4 == 0:
print(n," is a Leap Year")
else:
print(n," is not 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.
Example :
>>> n1 = eval (input ("Enter a number: "))
Enter an arithmetic expression: 234
>>> n1
234
In the above coding eval() function takes the returned value of string-based input
from input() function.
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.

..40..
12 – Computer Science

❖ The statement “return [expression]” exits a function, optionally passing back an


expression to the caller.
IV. Answer the following questions: (5 Marks)
1. Explain the different types of function with an example.
Basically, we can divide functions into the following types:
❖ User-defined Functions
❖ Built-in Functions
❖ Lambda Functions
❖ Recursion Functions
User-defined Functions:
We can define our own function. These are called used defined functions.
Functions must be defined, to create and use certain functionality.
Syntax:
def <function_name ([parameter1, parameter2…] )> :
<Block of Statements>
return <expression / None>
Example:
def hello():
print (“hello - Python”) function definition
return
hello() → function calling
Output:
hello – Python
Built-in Functions :
➢ The built-in functions are pre-defined by the python interpreter.
➢ These functions perform a specific task and can be used in any program,
depending on the requirement of the user.
Few functions are
(i) abs() - Returns an absolute value of a number
(ii) ord ( ) - Returns the ASCII value for the given Unicode character.
(iii) max() - Return the maximum value in the list.

..41..
12 – Computer Science

Lambda or 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
The above lambda function that adds argument arg1 with argument arg2 and
stores the result in the variable sum. The result is displayed using the print().
Recursion Functions:
➢ When a function calls itself is known as recursion.
➢ 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.
Example:
def fact(n):
if n == 0:
return 1
else:
return n * fact (n-1)
print (fact (0))
print (fact (5))
Output:
1
120

..42..
12 – Computer Science

2. Explain the scope of variables with an example.


Scope of variable refers to the part of the program, where it is accessible.
There are two types of scopes:
i) local scope and
ii) global scope.
Local Scope:
A variable declared inside the function's body or in the local scope is known as
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 format arguments are also local to function.
Example:
def loc():
y = 0 → local scope
print(y)
loc()
Output:
0
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.
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

..43..

You might also like