Python Problem Solving Fundamentals
Python Problem Solving Fundamentals
Chapter 1 : Introduction-Fundamentals
[Link] Is Computer Science?
Computer science is fundamentally about is computational problem solving —that is, solving
problems by the use of computation
The Essence of Computational Problem Solving
In order to solve a problem computationally, two things are needed:
A representation that captures all the relevant aspects of the problem.
An algorithm that solves the problem by use of the representation.
1
PROBLEM SOLVING USING PYTHON UNIT-I
BASE-2 REPRESENTATION :
128 64 32 16 8 4 2 1
2^7 2^6 2^5 2^4 2^3 2^2 2^1 2^0
0 1 1 0 0 0 1 1 = 99
1.4 Computer Software
Computer software is a set of program instructions, including related data and documentation,
that can be executed by computer.
Syntax, Semantics, and Program Translation :
The syntax of a language is a set of characters and the acceptable sequences of those
characters.
The semantics of a language is the meaning associated with each syntactically correct
sequence of characters.
A compiler is a translator program that translates programs directly into machine code
to be executed by the CPU.
An interpreter executes program instructions in place of (“running on top of”) the CPU.
Syntax errors are caused by invalid syntax. Semantic (logic) errors are caused by errors in
program logic.
Procedural vs. Object-Oriented Programming
Python supports both procedural and object-oriented programming.
Procedural programming and object-oriented programming are two major
programming paradigms in use today.
2
PROBLEM SOLVING USING PYTHON UNIT-I
Installing of python
Python is well supported and freely available at [Link]
Latest version : 3.8.5
3
PROBLEM SOLVING USING PYTHON UNIT-I
Python IDLE
An Integrated Development Environment (IDLE) is a bundled set of software tools for
program development.
An editor for creating and modifying programs
A translator for executing programs
A program debugger provides a means of taking control of the execution of a program
to aid in finding program errors
The Python Standard Library is a collection of modules, each providing specific functionality
beyond what is included in the core part of Python.
Python character set
Letters: Upper case and lower case letters
Digits: 0,1,2,3,4,5,6,7,8,9
Special Symbols: Underscore (_), (,), [,], {,}, +, -, *, &, ^, %, $, #, !, Single quote(‘),
Double quotes(“), Back slash(\), Colon(:), and Semi Colon (;)
White Spaces: (‘\t\n\x0b\x0c\r’), Space, Tab.
Token
A program in Python contains a sequence of instructions.
Python breaks each statement into a sequence of lexical components known as tokens.
Variables
A variable is “a name that is assigned to a value.”
The assignment operator, = , is used to assign values to variables.
An immutable value is a value that cannot be changed.
Eg: >>>num=10
>>> k=num
>>> print(k)
O/P : 10
In Python the same variable can be associated with values of different type during
program execution.
Eg : var = 12 integer
var = 12.45 float
var = 'Hello' string
4
PROBLEM SOLVING USING PYTHON UNIT-I
5
PROBLEM SOLVING USING PYTHON UNIT-I
>>> inf
Arithmetic underflow problem :
This problem occurs in division.
If denominator is larger than numerator, then it will result in zero.
Eg: 1/10000=0.00001
Loss of precision problem :
This problem occurs in division.
If numerator divided by denominator, then if the result is never ending.
Eg : 10/3 = 3.33333
6
PROBLEM SOLVING USING PYTHON UNIT-I
EXAMPLE :
>>>print('Hello\nJennifer Smith')
O/P:
Hello
Jennifer Smith
>>> print ('what\'s your name?')
O/P : what's your name?
>>> print ('what's your name?')
O/P : SyntaxError: invalid syntax
Implicit Line Joining
Matching parentheses, square brackets, and curly braces can be used to span a logical
program line on more than one physical line.
Explicit Line Joining
Program lines may be explicitly joined by use of the backslash (\).
Identifier
• An identifier is a sequence of one or more characters used to name a given program
element.
7
PROBLEM SOLVING USING PYTHON UNIT-I
The keyword module in python provides two helpful members for dealing with keywords.
8
PROBLEM SOLVING USING PYTHON UNIT-I
kwlist provides a list of all the python keywords for the version which
you are running.
iskeyword() provides a way to determine if a string is also a keyword.
Eg :
NUMBERS
Number data type stores Numerical Values.
This data type is immutable [i.e. values/items cannot be changed].
Pythn supports integers, floating point numbers and complex numbers.
9
PROBLEM SOLVING USING PYTHON UNIT-I
Sequence
A sequence is an ordered collection of items, indexed by positive integers.
It is a combination of mutable (value can be changed) and immutable (values cannot
be changed) datatypes.
There are three types of sequence data type available in Python, they are
1. Strings, 2. Lists, 3. Tuples
Strings
A String in Python consists of a series or sequence of characters.
Single quotes(' ') E.g., 'This a string in single quotes' ,
Double quotes(" ") E.g., "'This a string in double quotes'" ,
Triple quotes(""" """)E.g., """This is a paragraph. It is made up of multiple lines
and sentences."""
Individual character in a string is accessed using a subscript(index).
Strings are Immutable i.e the contents of the string cannot be changed after it is created.
Lists
List is an ordered sequence of items. Values in the list are called elements /items.
It can be written as a list of comma-separated items (values) between square brackets[].
Items in the lists can be of different datatypes.
Eg : lt = [ 10, -20, 15.5, ‘ABC’, “XYZ” ]
Tuples
In tuple the set of elements is enclosed in parentheses ( ).
A tuple is an immutable list.
Once a tuple has been created, you can't add elements to a tuple or remove elements
from the tuple.
Benefit of Tuple:
Tuples are faster than lists.
If the user wants to protect the data from accidental changes, tuple can be used.
Tuples can be used as keys in dictionaries, while lists can't.
Altering the tuple data type leads to error.
Eg : tpl = ( 10, -20, 15.5, ‘ABC’, “XYZ” )
Dictionaries
A dictionary maps keys to values.
10
PROBLEM SOLVING USING PYTHON UNIT-I
Lists are ordered sets of objects, whereas dictionaries are unordered sets.
Dictionary is created by using curly brackets. i,e.{ }
Dictionaries are accessed via keys and not via their position.
The values of a dictionary can be any Python data type. So dictionaries are unordered
key-value pairs(The association of a key and a value is called a key- value pair)
Eg : Creating a dictionary:
>>> food = {"ham":"yes", "egg" : "yes", "rate":450 }
Set :
Python also provides two set types, set and frozenset.
The set type is mutable, while frozenset is immutable.
They are unordered collections of immutable objects.
Boolean :
The boolean data type is either True or False.
In Python, boolean variables are defined by the True and False keywords.
The keywords True and False must have an Upper Case first letter.
OPERATORS IN PYTHON
An operator is a symbol that represents an operation that may be performed on one or
more operands.
Operators that take one operand are called unary operators.
Operators that take two operands are called binary operators.
20 - 5 ➝ 15 ( - as binary operator)
- 10 * 2 ➝ -20 ( - as unary operator)
Types of operators
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operator
Bitwise Operator
Identity Operator
Membership Operator
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc.
11
PROBLEM SOLVING USING PYTHON UNIT-I
x**y (x to the
** Exponent - left operand raised to the power of right
power y)
Relational Operators
• Relational operators are used to compare values. It returns either True or False
according to the condition.
Logical operators
• Logical operators are the and, or, not operators.
12
PROBLEM SOLVING USING PYTHON UNIT-I
Eg:
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
Assignment Operator
• Assignment operators are used to assign the values to variables.
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
BITWISE OPERATORS
• Bitwise operators are working with individual bits of data.
13
PROBLEM SOLVING USING PYTHON UNIT-I
Example :
Membership operators
Membership operators : in and not in for determining the presence of items in a sequence such
as strings, lists and tuples.
in and not in are the membership operators in Python.
They are used to test whether a value or variable is found in a sequence(string, list,
tuple, set and dictionary)
In dictionary, we can only test for the presence of key not the value.
Example :
What Is an Expression?
An expression is a combination of symbols or single symbol that evaluates to a value.
A subexpression is any expression that is part of a larger expression.
Expressions, most commonly, consist of a combination of operators and operands,
Eg : 4 + (3 * k)
Operator precedence
Precedence : Defines the priority of an operator.
Associativity :
When an expression contains operators with equal precedence then the associativity
property decides which operation is to be performed first.
Associativity implies the direction of execution and is of two types,left to right and right
to left.
15
PROBLEM SOLVING USING PYTHON
UNIT 3
2 MARKS
1
1. What Is a Function Routine?
➢ Computer program as a single series of instructions.
➢ A routine is a named group of instructions performing some task.
➢ A routine can be invoked (called) as many times as needed in a given program.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
2. Define: Function.
➢ A function is a block of statements under a name that can execute independently.
➢ The functions are used to perform a specific task.
➢ Functions allow us to divide a larger problem into smaller subparts to solve efficiently.
= = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = =
3. How to create/ define a function?
➢ The Python programming language provides the keyword def to create functions.
➢ The general syntax to create functions is as follows.
Syntax:
def function_name(list_of_parameters):
statement_1
statement_2
statement_3
...
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
4. What is calling a function in Python?
➢ In Python, we use the name of the function to make a function call.
➢ If the function requires any parameters, we need to pass them while calling it.
Syntax:
function_name(parameter_1, parameter_2,...)
Example:
def sample_function():
2
print('This is a user-defined function')
sample_function()
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
➢ Function avg takes three arguments (n1, n2, and n3) and returns the average of the three.
➢ The function call avg(10, 25, 16), therefore, is an expression that evaluates to the
returned function value.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
6. What is Non-Value-Returning Functions in Python?
➢ A non-value-returning function is called not for a returned value, but for its side
effects.
➢ A side effect is an action other than returning a function value, such as displaying
output on the screen.
Example:
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
7. What is Actual arguments and Formal arguments in Python?
➢ Actual arguments, or simply “arguments,” are the values passed to functions (or
method) when the calling function to be operated on.
3
➢ Formal parameters, or simply “parameters,” are the “placeholder” names
(variables/identifiers) specified in the (header of) function definition.
def addition(x, y): →Formal parameters
addition = x+y
print(f”{addition}”)
addition(2, 3) →Actual Parameters
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
8. What is Local Variable?
➢ A local variable is a variable that is only accessible from within a given function.
➢ In Python, the variable that created inside a function is said to be under the local scope.
Example:
In this example Variable ‘a’ is used within the function named my_function() only.
def my_function():
a = 10
print('Inside my_function a value is: ', a)
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
9. What is Global Variable?
➢ A global variable is a variable defi ned outside of any function definition. Such
variables are said to have global scope.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
4
10. What is Variable scope in Python?
➢ The scope refers to the accessibility of a variable or object in the program.
➢ The scope of a variable determines the part of the program in which it can be accessed
or used.
➢ In Python programming, there are two different levels of scope and they are as follows.
1. Local Scope
2. Global Scope
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
11. What is built-in functions in Python?
➢ Built-in functions are defined as the functions whose functionality is pre-defined in
Python.
➢ There are several built-in functions in Python which are listed below:
1. abs()
2. all()
[Link]()
4. bin()
5. bool()
6. sum() and so on.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
5
PROBLEM SOLVING USING PYTHON
UNIT 3
5 & 10 MARKS
6
1. Explain about function in Python?
➢ Computer program as a single series of instructions.
➢ A routine is a named group of instructions performing some task.
➢ A routine can be invoked (called) as many times as needed in a given program.
➢ When a routine terminates, execution automatically returns to the point from which it
was called.
➢ A function is Python’s version of a program routine. Some functions are designed to
return a value, while others are designed for other purposes.
➢ Functions allow us to divide a larger problem into smaller subparts to solve efficiently.
Create/ Define a function:
➢ The Python programming language provides the keyword def to create functions.
➢ The general syntax to create functions is as follows.
Syntax:
def function_name(list_of_parameters):
statement_1
statement_2
statement_3
...
Calling a function:
➢ In Python, we use the name of the function to make a function call.
➢ If the function requires any parameters, we need to pass them while calling it.
Syntax:
function_name(parameter_1, parameter_2,...)
Example:
def sample_function():
print('This is a user-defined function')
sample_function()
7
Value-Returning Functions :
➢ A value-returning function in Python is a program routine called for its return value,
and is therefore similar to a mathematical function.
➢ Function avg takes three arguments (n1, n2, and n3) and returns the average of the three.
➢ The function call avg(10, 25, 16), therefore, is an expression that evaluates to the
returned function value.
Non-Value-Returning Functions:
➢ A non-value-returning function is called not for a returned value, but for its side effects.
➢ A side effect is an action other than returning a function value, such as displaying
output on the screen.
Example:
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
2. Discuss about: Parameter passing in Python.
➢ Information can be passed into functions as arguments.
➢ Arguments are specified after the function name, inside the parentheses.
➢ You can add as many arguments as you want, just separate them with a comma.
➢ In Python, all the parameters are passed using pass by reference only.
Example1:
def fn1(name):
print(f'Hello! {name}')
name = 'Raja'
8
name = 'Rama'
fn1 (name)
print(f'name outside the function is {name}')
Output:
Hello! Rama
name outside the function is Rama
➢ In the above example program, the changes made in the called function does not affect
the name value outside the function.
➢ Because here the name variable has redefined, so it becomes a local variable for the
function.
➢ So, when we change the 'name' value in the function, it creates a new reference to it,
but it does not change the name outside the function.
Example2:
def myFun(x):
x[0] = 20
Example 3:
def myFun(x):
x = [20, 30, 40]
9
def addition(x, y): →Formal parameters
addition = x+y
print(f”{addition}”)
addition(2, 3) →Actual Parameters
Mutable vs. Immutable Arguments
➢ When a function is called, the current values of the arguments passed become the
initial values of their corresponding formal parameters.
Example:
➢ In this case, literal values are passed as the arguments to function avg.
➢ When variables are passed as actual arguments. Here we can change the value.
➢ It is considered as Mutable.
➢ In this case, function avg doesn’t assign values to its formal parameters, so there is no
possibility of the actual arguments being changed. It is considered as Immutable.
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
4. Explain Python function arguments?
In Python, there are different ways to pass arguments to a function. They are as follows.
10
1. Positional Arguments (or) Required Arguments
➢ The positional arguments are the arguments passed to a function in the same positional
order as they defined in the function definition.
➢ Here, the number of arguments and order of arguments in the function call should
exactly match with the respective function definition.
➢ If any mismatch leads to error.
➢ The positional arguments are also known as required arguments.
Example:
def addition(num1, num2, num3):
return num1 + num2 + num3
2. Default Arguments
➢ The default argument is an argument which is set with a default value in the function
definition.
➢ If the function is called with value then, the function executed with provided value,
otherwise, it executed with the default value given in the function definition.
Example:
def addition(num1, num2, num3=300):
return num1 + num2 + num3
Output:
Sum = 60
Sum = 330
3. Keyword Arguments
➢ The keyword argument is an argument passed as a value along with the parameter name
(parameter_name = value).
➢ When keyword arguments are used, we may ignore the order of arguments.
➢ We may pass the arguments in any order because the Python interpreter uses the
keyword provided to match with the respective parameter.
11
Example:
def student_info(rollNo, name, dept, year):
print(f'Roll Number : {rollNo}')
print(f'Student Name : {name}')
print(f'Department : {dept}')
print(f'Year of Study : {year}')
Output:
Roll Number : 111
Student Name : Rama
Department : CSE
Year of Study : 4
4. Variable-length Arguments
➢ The Python provides variable-length of arguments which enable us to pass an arbitrary
number of arguments.
➢ Here, all the arguments are stored as a tuple of parameters in the function definition.
And they are accessed using the index values (similar to a tuple).
Example:
def largest(*numbers):
return max(numbers)
print(largest(20, 35))
print(largest(2, 5, 3))
print(largest(10, 40, 80, 50))
print(largest(16, 3, 9, 12, 44, 40))
Output:
35
5
80
44
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
5. Explain about Variable scope in Python.
➢ The scope refers to the accessibility of a variable or object in the program.
➢ The scope of a variable determines the part of the program in which it can be accessed
or used.
1. Local Variable and Local Scope
12
➢ A local variable is a variable that is only accessible within a given function itself.
Such variables are said to have local scope.
Example:
def my_function():
a = 10
print('Inside my_function a value is: ', a)
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
6. Discuss about Built-in function in Python.
➢ The Python built-in functions are defined as the functions whose functionality is pre-
defined. These functions are known as Built-in Functions.
➢ There are several built-in functions in Python which are listed below:
abs()Function:
➢ The python abs() function is used to return the absolute value of a number.
➢ It takes only one argument, a number whose absolute value is to be returned.
➢ The argument can be an integer and floating-point number.
➢ If the argument is a complex number, then, abs() returns its magnitude.
Examples:
1) x = abs(-7.25)
print(x)
Output:
7.25
2) x = abs(3+5j)
13
print(x)
Output:
5.830951894845301
all() Function:
➢ The all() function returns True if all items in an iterable are true, otherwise it returns
False.
➢ If the iterable object is empty, the all() function also returns True.
➢ Ex:
mylist = [0, 1, 1] mylist = [True, True, True]
x = all(mylist) x = all(mylist)
print(x) print(x)
Output:
False True
Any() Function:
➢ The any() function returns True if any item in an iterable are true, otherwise it returns
False.
➢ If the iterable object is empty, the any() function will return False.
Ex 1:
mylist = [False, True, False]
x = any(mylist)
Output:
True
Ex 2:
mytuple = (0, 1, False)
x = any(mytuple)
Output:
True
Ex 3:
myset = {0, 1, 0}
x = any(myset)
Output:
True
complex() Function:
14
➢ The complex() function returns a complex number by specifying a real number and an
imaginary number.
Syntax:
complex(real, imaginary)
Ex:
x = complex(3, 5) x = complex('3+5j’)
print(x) print(x)
Output: (3+5j) Output: (3+5j)
dict() Function:
➢ The dict() function creates a dictionary.
➢ A dictionary is a collection which is unordered, changeable and indexed.
Ex:
x = dict(name = "John", age = 36, country = "Norway")
print(x)
Output:
{'name': 'John', 'age': 36, 'country': 'Norway'}
eval() Function:
➢ The eval() function evaluates the specified expression.
Example:
x=5
print(eval('x + 1’))
Output:
6
exec() Function:
➢ The exec() function executes the specified Python code.
➢ The exec() function accepts large blocks of code, unlike the eval() function which
only accepts a single expression
Ex:
x = 'name = "John
print(name)'
exec(x)
Output: John
len() Function:
➢ The len() function returns the number of items in an object.
15
➢ When the object is a string, the len() function returns the number of characters in the
string.
Ex:
mylist = ["apple", "orange", "cherry"]
x = len(mylist)
print(x)
Output:
3
id() function
➢ The id() function returns a unique id for the specified object.
➢ All objects in Python has its own unique id.
➢ The id is the object's memory address, and will be different for each time you run the
program. (except for some object that has a constant unique id, like integers from -5 to
256)
Example
x = ('apple', 'banana', 'cherry')
y = id(x)
print(y)
# This value is the memory address of the object and will be different every time you
run the program
Output:
88991544
list() function
➢ The list() function creates a list object.
➢ A list object is a collection which is ordered and changeable.
Example:
print(x)
Output:
16
map() function
➢ The map() function executes a specified function for each item in an iterable.
➢ The item is sent to the function as a parameter.
Example:
def myfunc(a):
return len(a)
x = map(myfunc, ('apple', 'banana', 'cherry'))
print(x)
#convert the map into a list, for readability:
print(list(x))
Output:
<map object at 0x056D44F0>
['5', '6', '6']
max() function
➢ The max() function returns the item with the highest value, or the item with the highest
value in an iterable.
➢ If the values are strings, an alphabetically comparison is done.
Example:
x = max(5, 10)
print(x)
Output:
10
min() function
➢ The min() function returns the item with the lowest value, or the item with the lowest
value in an iterable.
➢ If the values are strings, an alphabetically comparison is done.
Example:
x = min(5, 10)
print(x)
Output:
5
range() function
17
➢ The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and stops before a specified number.
Example:
x = range(6)
for n in x:
print(n)
Output:
0
1
2
3
4
5
= = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == =
18
PROBLEM SOLVING USING PYTHON
UNIT 4
2 MARKS
1
1. What is an Object?
➢ All objects have certain attributes and behavior.
➢ An object contains a set of attributes, stored in a set of instance variables, and a set of
functions called methods that provide its behavior.
➢ The attributes of a car, for example, include its color, number of miles driven, current
location, and so on.
➢ Its behaviors include driving the car (changing the number of miles driven attribute)
and painting the car (changing its color attribute).
➢ The sort rmethod would be part of the object containing the list.
Ex:
names_list.sort().
➢ The period is referred to as the dot operator , used to select a member of a given object
in this case, the sort method.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
2. What is Object References?
➢ In Python, objects are represented as a reference to an object in memory.
➢ A reference is a value that references, or “points to,” the location of another entity.
➢ Thus, when a new object in Python is created, two entities are stored—the object, and
a variable holding a reference to the object.
➢ All access to the object is through the reference value.
➢ The value that a reference points to is called the dereferenced value. This is the value
that the variable represents, as shown in the following Figure.
2
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
3. What is built-in function id?
➢ The id is the object's memory address, and will be different for each time you run the
program. (except for some object that has a constant unique id, like integers from -5 to
256).
Example
x = ('apple', 'banana', 'cherry')
y = id(x)
print(y)
# This value is the memory address of the object and will be different every time you
run the program
Output:
88991544
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
4. What is assignment of references?
when variable n is assigned to variable k, depicted in the following Figure.
When variable n is assigned to k, it is the reference value of k that is assigned, not the
dereferenced value 20.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
5. What is Garbage Collection?
Garbage collection is a method of determining which locations in memory are no longer in use,
and deallocating them.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
6. What is Turtle Graphics?
➢ Turtle graphics refers to a means of controlling a graphical entity (a “turtle”) in a
graphics window with x,y coordinates.
3
➢ Python provides the capability of turtle graphics in the turtle Python standard library
module.
➢ There may be more than one turtle on the screen at once. Each turtle is represented by
a distinct object.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
7. How can you create Turtle in Python?
➢ The first step in the use of turtle graphics is to create a turtle graphics window of a
specific size with an appropriate title.
➢ The following shows how to create a turtle screen of a certain size with an appropriate
title bar.
4
Absolute Positioning:
➢ A turtle’s position can be changed using absolute positioning by use of method
setposition.
Relative Positioning
➢ A turtle’s position can be changed using relative positioning by use of methods
setheading, left, right, and forward.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
11. What is pen attributes of turtle?
➢ The pen attributes that can be controlled includes:
1. pen is down or up (using methods penup and pendown)
2. pen size (using method pensize)
3. pen color (using method pencolor).
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
12. What are additional attributes of turtle?
1. Turtle Visibility - Methods showturtle() and hideturtle() control a
turtle’s visibility.
2. Turtle Size- The size of a given turtle shape can be controlled with methods
resizemode and turtlesize.
3. Turtle Shape- A turtle’s shape may be set to one of the provided shapes, a described
polygon (or collection of polygons), or an image.
4. Turtle Speed- The speed of a turtle can be controlled by use of the speed method.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
13. What is module?
➢ The term “module” refers to the design and/or implementation of specific functionality
to be incorporated into a program.
➢ Modules generally consist of a collection of functions (or other entities).
➢ The Python turtle module is an example of a software module.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
14. What are advantages of modular programming?
1. Software Design
2. Software Development
3. Software Testing
4. Software Modification and Maintenance
=== == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
5
15. What is module specification?
➢ Every module needs to provide a specification of how it is to be used.
➢ This is referred to as the module’s interface.
➢ Any program code making use of a particular module is referred to as a client of the
➢ module.
➢ A module’s specification should be sufficiently clear and complete so that its clients
can effectively utilize it.
➢ The function’s specification is provided by the line immediately following the function
header, called a docstring in Python.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
16. What is docstring?
➢ The function’s specification is provided by the line immediately following the function
header, called a docstring in Python.
➢ A docstring is a string literal denoted by triple quotes used in Python for providing the
specification of certain program elements.
Ex:
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
17. What is Top-Design?
➢ Top-down design is an approach for deriving a modular design in which the overall
design of a system is developed first, deferring the specification of more detailed
aspects of the design until later steps.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
18. What Is a Python Module?
➢ A Python module is a file containing Python definitions and statements.
➢ The Python Standard Library contains a set of predefined standard (built-in) modules.
➢ When a Python file is directly executed, it is considered the main module of a
program.
➢ Main modules are given the special name __main__.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
19. What is namespace?
➢ A namespace provides a context for a set of identifiers.
6
➢ Every module in Python has its own namespace.
➢ A name clash is when two otherwise distinct entities with the same identifier become
part of the same scope.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
20. What is “import module name” Form of Import?
➢ With the import modulename form of import in Python, the namespace of the
imported module becomes available to, but does not become part of, the namespace of
the importing module.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
21. What is “from-import” Form of Import?
➢ Python also provides an alternate import statement of the form
from modulename import something
where something can be a list of identifiers, a single renamed identifier, or an asterisk, as
shown below,
(a) from modulename import func1, func2
(b) from modulename import func1 as new_func1
(c) from modulename import *
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
22. What is module private variable?
In Python, all the variables in a module are “public,” with the convention that variables
beginning with two underscores (__) are intended to be private.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
23. What is Built-in Function dir()?
➢ Built-in function dir() is very useful for monitoring the items in the namespace of
the main module for programs executing in the Python shell.
➢ For example, the following gives the namespace of a newly started shell,
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
The following shows the namespace after importing and defining variables,
>>> import random
>>> n 5 10
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'n',
'random']
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
7
24. What are the 3 possible namespaces?
There are three possible namespaces referenced (“active”):
1. built-in namespace
2. global namespace
3. local namespace.
Built-in namespace:
➢ The built-in namespace contains the names of all the built-in functions, constants, and
so on, in Python.
Global namespace:
➢ The global namespace contains the identifiers of the currently executing module.
Local Namespace
➢ The local namespace is the namespace of the currently executing function (if any).
When Python looks for an identifier, it first searches the local namespace (if defi ned), then the
global namespace, and finally the built-in namespace.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
25. What is text file?
➢ A text file is a file containing characters, structured as individual lines of text.
➢ In addition to printable characters, text files also contain the nonprinting newline
character, \n, to denote the end of each text line.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
26. What is Binary File?
➢ Binary files can contain various types of data, such as numerical values, and are
therefore not structured as lines of text.
➢ Such files can only be read and written via a computer program.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
27. What are the operations of File?
Fundamental operations of all types of files include opening a file, reading from a file, writing
to a file, and closing a file.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
28. What is Opening Text File?
➢ All files must first be opened before they can be used.
➢ In Python, when a file is opened, a file object is created that provides methods for
accessing the file.
8
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
29. What is Reading Text File?
➢ The readline method returns the next line of a text file, including the end-of-line
character.
➢ If at the end of the file, an empty string is returned.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
30. What is Writing a text File?
➢ Use the write()method to output text to a file.
➢ To ensure that all data has been written, call the close() method to close the file
after all information has been written.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
31. What is String Processing?
String processing refers to the operations performed on strings that allow them to be accessed,
analyzed, and updated.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
32. What is String Traversal?
The characters in a string can be easily traversed, without the use of an explicit index variable,
using the for chr in string form of the for statement.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
33. What is an Exception?
➢ The exception is an abnormal situation during the execution.
➢ An exception is a value (object) that is raised (“thrown”) signalling that an unexpected,
or “exceptional,” situation has occurred.
➢ Python contains a predefined set of exceptions referred to as standard exceptions.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
34. List some standard exceptions.
ImportError Raised when an import(from..import) statement fails
IndexError Raised when a sequence index is out of range
NameError Raised when a local or global name is not found
TypeError Raised when an operation or function is applied to an object of
inappropriate type
ValueError Raised when a built-in operation or function is applied to an
appropriate value
9
IOError Raised when an input/output operation fails (e.g., ‘file not found’)
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
35. What is propagation of exception?
➢ An exception is either handled by the client code, or automatically propagated back to
the client’s calling code, and so on, until handled.
➢ If an exception is thrown all the way back to the main module (and not handled), the
program terminates displaying the details of the exception.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
36. What is IOError exceptions?
IOError exceptions raised as a result of a fi le open error can be caught and handled.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
10
PROBLEM SOLVING USING PYTHON
UNIT 4
5 & 10 MARKS
11
1. Explain the fundamental concept of software object?
➢ Objects are the fundamental component of object-oriented programming.
➢ All objects have certain attributes and behavior.
➢ An object contains a set of attributes, stored in a set of instance variables, and a set of
functions called methods that provide its behavior.
➢ The attributes of a car, for example, include its color, number of miles driven, current
location, and so on.
➢ Its behaviors include driving the car (changing the number of miles driven attribute)
and painting the car (changing its color attribute).
➢ The sort rmethod would be part of the object containing the list (names_list.
Ex:
names_list.sort().
➢ The period is referred to as the dot operator, used to select a member of a given object
in this case, the sort method.
Object References:
➢ In Python, objects are represented as a reference to an object in memory.
➢ A reference is a value that references, or “points to,” the location of another entity.
➢ Thus, when a new object in Python is created, two entities are stored—the object, and
a variable holding a reference to the object.
➢ All access to the object is through the reference value.
➢ The value that a reference points to is called the dereferenced value. This is the value
that the variable represents, as shown in the following Figure.
12
➢ We can get the reference value of a variable (that is, the location in which the
corresponding object is stored) by use of built-in function id.
➢ The id is the object's memory address, and will be different for each time you run the
program. (except for some object that has a constant unique id, like integers from -5 to
256).
Example
x = ('apple', 'banana', 'cherry')
y = id(x)
print(y)
# This value is the memory address of the object and will be different every time you
run the program
Output:
Assignment of reference:
when variable n is assigned to variable k, depicted in the following Figure.
➢ When variable n is assigned to k, it is the reference value of k that is assigned, not the
dereferenced value 20.
➢ This can be determined by use of the built-in id function, as demonstrated below.
>>> id(k) >>> id(k) == id(n)
505498136 True
>>> id(n) >>> n is k
505498136 True
➢ Thus, to verify that two variables refer to the same object instance, we can either
compare the two id values by use of the comparison operator, or make use of the
provided is operator (which performs id(k) = = id(n)).
➢ when the value of one of the two variables n or k is changed, as depicted in the
following Figure.
13
Reassignment of Reference Value
➢ Here, variable k is assigned a reference value to a new memory location holding the
value 30.
➢ The previous memory location that variable k referenced is retained since variable n is
still referencing it.
➢ As a result, n and k point to different values, and therefore are no longer equal.
Memory Deallocation and Garbage Collection
➢ when variable k being reassigned, variable n is reassigned as well. The result is
depicted in the following Figure.
➢ After n is assigned to 40, the memory location storing integer value 20 is no longer
referenced—thus, it can be deallocated.
➢ To deallocate a memory location means to change its status from “currently in use” to
“available for reuse.”
➢ In Python, memory deallocation is automatically performed by a process called garbage
collection.
➢ Garbage collection is a method of automatically determining which locations in
memory are no longer in use and deallocating them.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
2. Explain about List assignment and Copying?
List Assignment:
➢ when a variable is assigned to another variable referencing a list, each variable ends
up referring to the same instance of the list in memory, depicted in the following
figure.
14
List Assignment
➢ Thus, any changes to the elements of list1 results in changes to list2,
>>>list1[0] = 5
>>>list2[0]
5
List Copying
➢ A copy of a list can be made as follows, Copy using = operator.
➢ It only creates a new variable that shares the reference of the original object.
>>> list2 = list(list1)
➢ list() is referred to as a list constructor .
➢ The result of the copying is depicted in the following figure.
15
➢ The list constructor list() makes a copy of the top level of a list, in which the sublist
(lower-level) structures are shared is referred to as a shallow copy.
Top-Level Reassignment of Shallow Copies
➢ Copies were made of the top-level list structures, the elements within each list
were not copied. This is referred to as a shallow copy.
➢ Thus, if a top-level element of one list is reassigned, for example list1[0] = [70, 80],
the other list would remain unchanged, as shown in the following figure.
➢ A shallow copy creates a new object which stores the reference of the original elements.
➢ So, a shallow copy doesn't create a copy of nested objects, instead it just copies the
reference of nested objects.
Sublevel Reassignment of Shallow Copies:
➢ A change to one of the sublists is made, for example, list1[0][0] = 70, the corresponding
change would be made in the other list.
➢ That is, list2[0][0] would be equal to 70 also, as depicted in the following Figure.
Deep Copy:
➢ A deep copy operation of a list (structure) makes a copy of the complete structure,
including sublists.
16
➢ Since immutable types cannot be altered, immutable parts of the structure may not be
copied. Such an operation can be performed with the deepcopy method of the
copy module,
>>>import copy
>>>list2 = [Link](list1)
➢ The result of this form of copying is given in the following Figure.
17
5 This is similar to the concept of passing This is similar to the concept of passing
by reference in programming languages by value in languages like C++, Java, and
like C++, C#, and Java. C#.
6 This is implemented by using copy() This is implemented using “deepcopy()”
function. function.
7 import copy import copy
result_A = [[90, 85, 82], [72, 88, 90]] result_A = [[90, 85, 82], [72, 88, 90]] #
result_B = [Link](result_A) Student A grades
result_B = [Link](result_A) #
print(result_A) Student B grades (copied from A)
print(result_B)
print(result_A)
print(result_B)
Output: Output:
[[90, 85, 82], [72, 88, 90]] [[90, 85, 82], [72, 88, 90]]
[[90, 85, 82], [72, 88, 90]] [[90, 85, 82], [72, 88, 90]]
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
4. How will you create turtle graphics window in Python?
➢ The Python turtle library contains all the methods and functions that you’ll need to
create your images.
➢ To access a Python library, you need to import it into your Python environment, like
this:
>>> import turtle
➢ Turtle graphics refers to a means of controlling a graphical entity (a “turtle”) in a
graphics window with x,y coordinates.
➢ Each of the turtle graphics methods must be called in the form
[Link] .
➢ The first method called, setup, creates a graphics window of the specified size (in
pixels).
➢ The first step in the use of turtle graphics is to create a turtle graphics window of a
specific size with an appropriate title.
18
Creating a Turtle Graphics Window
➢ In this case, a window of size 800 pixels wide by 600 pixels high is created.
➢ The center point of the window is at coordinate (0,0).
➢ Thus, x-coordinate values to the right of the center point are positive values, and those
to the left are negative values.
Similarly, y-coordinate values above the center point are positive values, and those
below are negative values.
The top-left, top-right, bottom-left, and bottom-left coordinates for a window of size
(800, 600) are as shown in the following Figure.
19
➢ The screen is divided into four quadrants.
➢ The point where the turtle is initially positioned at the beginning of your program is
(0,0). This is called Home.
➢ To move the turtle to any other area on the screen, you use .goto() and enter the
coordinates like this:
>>> [Link](100,100)
➢ To bring the turtle back to its home position, you type the following:
>>> [Link]()
➢ This is like a shortcut command that sends the turtle back to the point (0,0).
➢ It’s quicker than typing [Link](0,0).
➢ A turtle graphics window in Python is also an object.
➢ Therefore, to set the title of this window, we need the reference to this object.
➢ This is done by call to method Screen.
➢ The background color of the turtle window can be changed from the default white
background color.
➢ This is done using method bgcolor.
➢ Example:
window = [Link]()
[Link]('blue')
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
5. Discuss about “Default Turtle”.
➢ A “turtle” is an entity in a turtle graphics window that can be controlled in various ways.
➢ Like the graphics window, turtles are objects.
20
➢ A “default” turtle is created when the setup method is called.
➢ The reference to this turtle object can be obtained by,
the_turtle = [Link]()
➢ A call to getturtle returns the reference to the default turtle and causes it to appear
on the screen.
➢ The initial position of all turtles is the center of the screen at coordinate (0,0), as shown
in the following Figure.
>>> t = [Link]()
>>> [Link](90)
>>> [Link](100)
>>> [Link](90)
>>> [Link](100)
21
➢ When you run these commands, the turtle will turn right by ninety degrees, go forward
by a hundred units, turn left by ninety degrees, and move backward by a hundred units.
➢ We can use the shortened versions of these commands as well:
• [Link]() instead of [Link]()
• [Link]() instead of [Link]()
• [Link]() instead of [Link]()
• [Link]() instead of [Link]()
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
7. Explain about fundamental Turtle attributes and its behaviour?
➢ Turtle objects have three fundamental attributes:
1. Position
2. Heading (orientation)
3. Pen attributes.
1. Position:
There are two types of positioning. They are:
a) Absolute Position
b) Relative Position
a) Absolute Positioning
➢ Method position returns a turtle’s current position.
➢ For newly created turtles, this returns the tuple (0, 0).
➢ A turtle’s position can be changed using absolute positioning by moving the turtle
to a specific x,y coordinate location by use of method setposition.
Example:
22
➢ Since newly created turtles are positioned at coordinates (0, 0), the square will be
displayed near the middle of the turtle window.
2 & b) Turtle Heading and Relative Positioning
➢ A turtle’s position can also be changed through relative positioning.
➢ In this case, the location that a turtle moves to is determined by its second
fundamental attribute, its heading.
➢ A newly created turtle’s heading is to the right, at 0 degrees.
➢ A turtle with heading 90 degrees moves up; with a heading 180 degrees moves left;
and with a heading 270 degrees moves down.
➢ A turtle’s heading can be changed by turning the turtle a given number of degrees left,
left(90), or right, right(90).
➢ The forward method moves a turtle in the direction that it is currently heading.
Example:
➢ In the above example, since turtles are initially positioned at coordinates (0, 0) with
an initial heading of 0 degrees, the first step is to move the turtle forward 100 pixels.
➢ That draws the bottom line of the square.
➢ The turtle is then turned left 90 degrees and again moved forward 100 pixels.
➢ This draws the line of the right side of the square.
➢ These steps continue until the turtle arrives back at the original coordinates (0, 0),
completing the square.
➢ Methods left and right change a turtle’s heading relative to its current heading.
➢ A turtle’s heading can also be set to a specific heading by use of method
setheading: the_turtle.setheading(90).
➢ In addition, method heading can be used to determine a turtle’s current heading.
23
➢ A turtle’s position can be changed using relative positioning by use of methods
setheading, left, right, and forward.
3. Pen attributes
➢ The pen attribute of a turtle object is related to its drawing capabilities.
➢ The most fundamental of these attributes is whether the pen is currently “up” or
“down,” controlled by methods penup() and pendown().
➢ When the pen attribute value is “up,” the turtle can be moved to another location without
lines being drawn.
➢ This is especially needed when drawing graphical images with disconnected segments.
Example:
➢ In this example, the turtle is hidden so that only the needed lines appear.
➢ Since the initial location of the turtle is at coordinate (0, 0), the pen is set to “up” so
that the position of the turtle can be set to (2100, 0) without a line being drawn as it
moves.
➢ This puts the turtle at the bottom of the left side of the letter.
➢ The pen is then set to “down” and the turtle is moved to coordinate (0, 250), drawing
as it moves.
➢ Therefore, draws a line from the bottom of the left side to the top of the “A.”
➢ The turtle is then moved (with its pen still down) to the location of the bottom of the
right side of the letter, coordinate (100, 0).
➢ To cross the “A,” the pen is again set to “up” and the turtle is moved to the location of
the left end of the crossing line, coordinate (264, 90).
➢ The pen is then set to “down” and moved to the end of the crossing line, at coordinate
(64, 90), to finish the letter.
24
Pen Size:
➢ The pen size of a turtle determines the width of the lines drawn when the pen attribute
is “down.”
➢ The pensize method is used to control this: the_turtle.pensize(5).
➢ The width is given in pixels, and is limited only by the size of the turtle screen.
Example:
Pen Color:
➢ The pen color can also be selected by use of the pencolor method:
the_turtle.pencolor('blue').
➢ The name of any common color can be used, for example 'white','red',
'blue', 'green', 'yellow', 'gray', and 'black'.
➢ Colors can also be specified in RGB (red/green/blue) component values.
➢ These values can be specifi ed in the range 0–255 if the color mode attribute of the
turtle window is set as given below,
[Link](255)
the_turtle.pencolor(238, 130, 238) # violet
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
8. Explain about additional attributes of turtle?
The additional attributes include:
1. Turtle Visibility
2. Turtle Size
3. Turtle Shape
4. Fill color of the turtle,
5. Turtle Speed,
6. Turtle Tilt
25
Turtle Visibility
➢ A turtle’s visibility can be controlled by use of methods hideturtle()and
showturtle().
Turtle Size
➢ The size of a turtle shape can be controlled with methods resizemode and
turtlesize as shown in the following figure.
➢ The shape and fill colors are set by use of the shape and fillcolor methods,
the_turtle.shape('circle')
the_turtle.fillcolor('white')
➢ New shapes may be created and registered with (added to) the turtle screen’s shape
dictionary.
26
Example:
➢ One way of creating a new is shape by providing a set of coordinates denoting a
polygon is shown in the following figure.
➢ In the figure, method register_shape is used to register the new turtle shape with
the name mypolygon.
➢ Once the new shape is defined, a turtle can be set to that shape by calling the shape
method with the desired shape’s name.
➢ The fillcolor method is then called to make the fill color of the polygon white
(with the edges remaining black).
➢ It is also possible to create turtle shapes composed of various individual polygons called
compound shapes.
Turtle Speed
➢ We may control the speed at which a turtle moves. The speed of a turtle can be
controlled by use of the speed method.
➢ A turtle’s speed can be set to a range of speed values from 0 to 10, with a “normal”
speed being around 6.
➢ To set the speed of the turtle, the speed method is used, the_turtle.speed(6).
➢ The following speed values can be set using a descriptive rather than a numeric value,
➢ 10: 'fast' 6: 'normal' 3: 'slow' 1: 'slowest' 0:
'fastest'
➢ Thus, a normal speed can also be set by the_turtle.speed('normal').
Turtle Tilt
➢ Turtle tilt is used to rotate the turtle shape by the angle from its current tilt-angle, but
do NOT change the turtle’s heading (direction of movement).
➢ Tilt is used by the method of [Link](angle)
27
Example:
# tilt turtleshape by 45
[Link](45)
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
9. How will you create multiple turtle?
➢ Any number of turtle objects can be created by use of method Turtle().
turtle1 = [Link]()
turtle2 = [Link]()
etc.
➢ By storing turtle objects in a list, any number of turtles may be maintained,
turtles = []
[Link]([Link]())
[Link]([Link]())
etc.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
10. Write about advantages of Modular Programming?
1. Software Design:
➢ Provides a means for the development of wee-designed programs.
2. Software Development:
➢ Provides a natural means of dividing up programming tasks
➢ Provides a means for the reuse of program code
3. Software Testing:
➢ Provides a means of separately testing parts of a program
➢ Provides a means of integrating parts of a program during testing
4. Software Modification and Maintenance:
➢ Facilitates the modification of specific program functionalities.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
11. Discuss briefly about fundamentals concepts of modules.
➢ Software is that programs that are designed as a collection of modules.
➢ The term “module,” refers to the design and/or implementation of specific functionality
of a program.
➢ Modules generally consists of a collection of functions or entities.
➢ Modular design allows large programs to be broken down into parts, in which each part
(module) provides a specified capability.
28
➢ It allows modules to be individually developed and tested, and eventually integrated as
a part of a complete system.
Module specification:
➢ Every module needs to provide a specification of how it is to be used.
➢ This is referred to as the module’s interface.
➢ Any program code making use of a particular module is referred to as a client of the
➢ module.
➢ A module’s specification should be sufficiently clear and complete so that its clients
can effectively utilize it.
➢ The function’s specification is provided by the line immediately following the function
header, called a docstring in Python.
➢ A docstring is a string literal denoted by triple quotes used in Python for providing the
specification of certain program elements.
Ex:
➢ The docstring of a particular program element can be displayed by use of the __doc__
extension,
>>> print(numPrimes.__doc__)
Returns the number of primes between start and end.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
12. Explain about Python Modules.
➢ A Python module is a file containing Python definitions and statements.
➢ The Python Standard Library contains a set of predefined standard (built-in) modules.
➢ When a Python file is directly executed, it is considered the main module of a
program.
➢ Main modules are given the special name __main__.
➢ As with the main module, imported modules may contain a set of statements.
➢ The statements of imported modules are executed only once, the first time that the
module is imported.
29
➢ By convention, modules are named using all lower case letters and optional underscore
characters.
Modules and Namespaces
➢ A namespace is a container that provides a set of identifiers
➢ Every module in Python has its own namespace.
➢ A name clash is when two distinct entities with the same identifier become
part of the same scope.
➢ Name clashes can occur, for example, if two or more Python modules contain identifiers
with the same name and are imported into the same program, as shown in the following
figure.
➢ In above example, module1 and module2 are imported into the same program.
➢ Each module contains an identifier named double, which return very different results.
➢ When the function call double(num_list) is executed in main, there is a name
clash.
➢ Thus, it cannot be determined which of these two functions should be called.
➢ Namespaces provide a means for resolving such problems.
➢ Two instances of identifier double, each defined in their own module, are distinguished
by being fully qualified with the name of the module in which each is defined:
[Link] and [Link]
30
Example Use of Fully Qualified Function Names
Importing Modules:
➢ With the import modulename form of import in Python, the namespace of the
imported module becomes available to, but does not become part of, the namespace of
the importing module.
➢ Python also provides an alternate import statement of the form
from modulename import something
where something can be a list of identifiers, a single renamed identifier, or an asterisk, as
shown below,
(a) from modulename import func1, func2
(b) from modulename import func1 as new_func1
(c) from modulename import *
➢ In example (a), only identifiers func1 and func2 are imported.
➢ In example (b), only identifier func1 is imported, renamed as new_func1 in the
importing module.
➢ Finally, in example (c), all of the identifiers are imported, except for those that begin
with two underscore characters, which are meant to be private in the module.
➢ In Python, all the variables in a module are “public,” with the convention that variables
beginning with two underscores (__) are intended to be private.
Built-in function dir():
➢ Built-in function dir() is very useful for monitoring the items in the namespace of
the main module for programs executing in the Python shell.
➢ For example, the following gives the namespace of a newly started shell,
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
The following shows the namespace after importing and defining variables,
>>> import random
>>> n 5 10
>>> dir()
31
['__builtins__', '__doc__', '__name__', '__package__', 'n',
'random']
Local, Global, and Built-in Namespaces in Python
There are three possible namespaces referenced (“active”):
1. Built-in namespace
2. Global namespace
3. Local namespace.
Built-in namespace:
➢ The built-in namespace contains the names of all the built-in functions, constants, and
so on, in Python.
Global namespace:
➢ The global namespace contains the identifiers of the currently executing module.
Local Namespace
➢ The local namespace is the namespace of the currently executing function (if any).
When Python looks for an identifier, it first searches the local namespace (if defined), then the
global namespace, and finally the built-in namespace.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
13. Explain the fundamental operations of file in python?
➢ Fundamental operations of all types of files include:
1. Opening a file
2. Reading from a file
3. Writing to a file
4. Closing a file
Opening Text Files
➢ All files must first be opened before they can be read from or written to.
32
➢ In Python, when a file is opened, a file object is created that provides methods for
accessing the file.
Opening for Reading
➢ To open a file for reading, the built-in open function is used.
input_file = open('[Link]','r')
➢ The first argument is the file name to be opened, '[Link]'.
➢ The second argument, 'r', indicates that the file is to be opened for reading.
➢ If the file is successfully opened, a file object is created and assigned to the provided
identifier, in this case identifier input_file.
Opening for Writing
➢ To open a file for writing, the open function is used as shown below,
output_file = open('[Link]','w')
➢ The first argument is the file name to be opened, '[Link]'.
➢ The second argument, 'w' is used to indicate that the file is to be opened for writing.
If the file already exists, it will be overwritten (starting with the first line of the file).
➢ When using a second argument of 'a', the output will be appended to an existing file
instead.
➢ It is important to close a file that is written to, otherwise the tail end of the file may not
be written to the file.
output_file.close()
Reading Text Files
➢ The readline method returns as a string the next line of a text file, including the
end-of-line character, \n.
➢ When the end-of-file is reached, it returns an empty string.
Example: Using WHILE Statement
33
input_fi le = \
open('[Link]','r')
for line in input_file:
➢ Using a FOR statement, all lines of the file will be read one by one.
➢ Using a WHILE loop, however, lines can be read until a given value is found.
Writing Text Files
➢ The write method is used to write strings to a file, is shown in the following figure.
➢ This code copies the contents of the input file, '[Link]', line by line to the
output file, 'myfile_copy.txt'.
➢ In contrast to print when writing to the screen, the write method does not add a
newline character to the output string.
➢ Thus, a newline character will be output only if it is part of the string being written.
➢ In this case, each line read contains a newline character.
➢ Finally, when writing to a file, data is first placed in an area of memory called a buffer.
Only when the buffer becomes full is the data actually written to the file.
➢ The close () method flushes the buffer to force the buffer to be written to the file.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
14. What is String Processing. Explain string Traversal.
String processing refers to the operations performed on strings that allow them to be accessed,
analyzed, and updated.
String Traversal:
➢ The characters in a string can be easily traversed, without the use of an explicit index
variable, using the for chr in string form of the FOR statement.
➢ This is usually done by the use of a FOR loop.
➢ For example, if we want to read a line of a text file and determine the number of blank
characters it contains, we could do the following,
space =' '
34
num_spaces = 0
line = input_fi [Link]()
for k in range(0,len(line)):
if line[k] == space:
num_spaces = num_spaces + 1
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
15. Discuss about String-Applicable Sequence Operations.
➢ Because strings (unlike lists) are immutable, sequence-modifying operations are not
applicable to strings.
➢ For example, one cannot add, delete, or replace characters of a string.
➢ Therefore, all string operations that “modify” a string return a new string that is a
modified version of the original string.
a) Length of String
b) Select Operation
c) Slice
d) Count
e) Index
f) Membership
g) Concatenation
h) Minimum Value
i) Maximum Value
j) Comparison
a) Length of String
The len() function is used to find the length of the string.
Example:
s = 'Hello Goodbye!'
print(len(s))
Output:
14
b) Select Operation
➢ It returns the substring of String (if found).
➢ If the substring is not found, it raises an exception.
➢ By using s[index value]method we can select particular string.
Example:
s = 'Hello Goodbye!'
35
s[6]
Output: 'G'
c) Slice:
➢ It can return a range of characters by using the slice syntax.
➢ Specify the start index and the end index, separated by a colon, to return a part of the
string. s[start:end]
Example:
s = 'Hello Goodbye!'
s[6:10]
Output: 'Good'
Slice from the Start
➢ By leaving out the start index, the range will start at the first character:
Example:
s = 'Hello Goodbye!'
print(s[:5])
Output: 'Hello'
Get the characters from the start to position 5 (not included) and starting index value is 0.
Slice To the End
➢ By leaving out the end index, the range will go to the end:
Example:
s = 'Hello Goodbye!'
print(s[2:])
Output: llo Goodbye!
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example:
s = 'Hello Goodbye!'
print(s[-5:-2])
Output:
dby
Get the characters:
36
From: "d" in " Goodbye!" (position -5)
To, but not included: "e" in " Goodbye!" (position -2):
d) Count
The string count () method returns the number of occurrences of a substring in the given
string.
[Link](substring)
Example:
s = 'Hello Goodbye!'
[Link]('o')
Output: 3
e) index
➢ The index() method finds the first occurrence of the specified value.
➢ The index() method raises an exception if the value is not found.
➢ The index() method is almost the same as the find() method, the only difference
is that the find() method returns -1 if the value is not found.
➢ [Link](value, start, end); start & end is optional.
Example:
s = 'Hello Goodbye!'
[Link]('b')
Output: 10
f) membership
Membership operators are used to test if a sequence is presented in an object.
1) in operator : The ‘in’ operator is used to check if a value exists in a sequence or not.
Evaluates to true if it finds a variable in the specified sequence and false otherwise.
2) ‘not in’ operator- Evaluates to true if it does not find a variable in the specified sequence
and false otherwise.
Example:
>>>s = 'Hello Goodbye!'
>>>'a' in s
Output: False
>>>'a' not in s
Output: True
37
g) Concatenation
➢ String concatenation means add strings together.
➢ Use the + character to add a variable to another variable:
Example:
>>>s = 'Hello Goodbye!'
>>> s + '!!'
Output:
'Hello Goodbye!!!'
h) Minimum Value
➢ The min() function returns the item with the lowest value.
➢ If the values are strings, an alphabetically comparison is done.
➢ min(n1, n2, n3, ...) OR min(iterable)
Example:
>>>s = 'Hello Goodbye!'
>>>min(s)
Output: ' '
i) Maximum Value
➢ The max() function returns the item with the lowest value.
➢ If the values are strings, an alphabetically comparison is done.
➢ max(n1, n2, n3, ...) OR max(iterable)
Example:
>>>s = 'Hello Goodbye!'
>>>max(s)
Output: 'y'
j) comparison
➢ Comparison operators are used to compare two values.
Operator Meaning Example
== Is equal to x==y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
38
16. Explain the concept of Strings in python?
➢ A string is a sequence of characters which is enclosed in quotes.
➢ In Python, a string value can be enclosed either in single quotes or double quotes or
triple quotes.
➢ The Python treats both single quote and double quote as same.
➢ For example, the strings ‘Welcome Python' and " Welcome Python " both are same.
➢ We can display a string literal with the print() function.
Example:
Print("Hi Python")
print('Hi Python')
Output:
Hi Python
Hi Python
Assign String to a Variable
➢ Assigning a string to a variable is done with the variable name followed by an equal
sign and the string.
Example
a = "Hi python"
print(a)
Output:
Hi Python
Multiline Strings
➢ We can assign a multiline string to a variable by using three quotes.
Example:
a=””” More things are wrought by prayer than this world dreams
off. An honest man is the noblest work of God. Get place and
wealth, if possible, with grace; if not, by any means get
wealth and place.”””
Print(a)
Output:
More things are wrought by prayer than this world dreams off.
An honest man is the noblest work of God. Get place and wealth,
if possible, with grace; if not, by any means get wealth and
place.
39
Accessing String Values
➢ In Python, a string data value has assigned to a variable and it is organized as an array
of characters.
➢ The Python provides a variety of ways to access the string values.
Example:
0 1 2 3 4 5
P Y T H O N
-6 -5 -4 -3 -2 -1
Accessing whole string
➢ To access the entire string which is stored in a variable, we use the variable name
directly.
Example:
a = "Hi python"
print(a)
Output:
Hi Python
Accessing a character from a String Values [Strings are Arrays]
To access a single character from a string variable, we can use the index value in square
brackets of the respective character.
Example:
a=’PYTHON’
print(a[1])
Output:
Y
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
Loop through the letters in the word "python":
for x in "PYTHON":
print(x)
Output:
P
Y
T
40
H
O
N
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
17. Discuss about string methods in python.
➢ Python has a set of built-in methods that you can use on strings.
➢ All string methods returns new values.
➢ They do not change the original string.
1. Checking the Contents of a String with in and not in operator.
isalpha() Method, isdigit() Method, islower() Method, isupper() Method, lower()
Method, upper() Method.
2. Searching the contents of a string
find() Method
3. Replacing the contents of a string
replace() Method
4. Removing the contents of a string
strip() Method
5. Splitting a string
split() Method
Checking the Contents of a String
➢ To check if a certain phrase or character is present in a string, we can use the keyword
in.
Example 1: Check if "world" is present in the following text.
txt = "Welcome to python world!"
print("world" in txt)
Output:
True
Example 2: Using IF statement
txt = "Welcome to python world!"
if "world" in txt:
print("Yes, 'World' is present.")
Output:
Yes, 'World' is present.
41
Check if NOT
➢ To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.
Example: Check if "universal" is present in the following text.
txt = "Welcome to python world!"
if "world" not in txt:
print("Yes, 'World' is present.")
Output:
True
isalpha() Method
➢ Check if all the characters in the text are letters.
➢ It returns true, if string contains only letters.
➢ Example of characters that are not alphabet letters: (space)!#%&? etc.
➢ Syntax is: [Link]()
Example 1:
S=’hello’
X=[Link]()
Print(X)
Output:
True
Example 2:
S=’hello!!’
X=[Link]()
Print(X)
Output:
False
isdigit() Method
➢ Check if all the characters in the text are digits.
➢ It returns True if all the characters are digits, otherwise False.
➢ Exponents, like ², are also considered as a digit.
Syntax is: [Link]()
Example 1:
S=’123’
42
X=[Link]()
Print(X)
Output:
True
Example 2:
S=’123aa’
X=[Link]()
Print(X)
Output:
False
islower() Method
➢ Check if all the characters in the text are in lower case.
➢ The islower() method returns True if all the characters are in lower case,
otherwise False.
➢ Numbers, symbols and spaces are not checked, only alphabet characters.
➢ Syntax is: [Link]()
Example:
a = "Welcome Python World!"
print([Link]())
Output:
welcome python world!
isupper() Method
➢ Check if all the characters in the text are in upper case.
➢ The isupper() method returns True if all the characters are in upper case,
otherwise False.
➢ Numbers, symbols and spaces are not checked, only alphabet characters.
➢ Syntax is: [Link]()
Example:
a = "Welcome Python World!"
print([Link]())
Output:
WELCOME PYTHON WORLD!
lower() Method
➢ The lower() method returns a string where all characters are lower case.
43
➢ Symbols and Numbers are ignored.
➢ Syntax is: [Link]()
Example:
a = "Welcome Python World!"
print([Link]())
Output:
welcome python world!
upper() Method
➢ Check if all the characters in the text are in upper case.
➢ The upper() method returns True if all the characters are in upper case, otherwise
False.
➢ Numbers, symbols and spaces are not checked, only alphabet characters.
➢ Syntax is: [Link]()
Example:
a = "Welcome Python World!"
print([Link]())
Output:
WELCOME PYTHON WORLD!
Searching the contents of a string
find() Method
➢ The find() method finds the first occurrence of the specified character and returns
its index value.
➢ If the character is not found, it returns the -1.
Example 1:
a = "Welcome Python World!"
print([Link]("e"))
Output:
1
Example 2:
a = "Welcome Python World!"
print([Link](“y”))
Output:
-1
Replacing the contents of a string
44
replace() Method
➢ Returns a string where a specified value is replaced with a specified value.
Example:
a = "Welcome Python World!"
print([Link]("Welcome", "hi"))
Output:
hi Python World!
Removing the contents of a string
strip() Method
➢ The strip() method removes any leading (spaces at the beginning) and trailing
(spaces at the end) characters.
➢ Space is also considered as default leading character to remove.
Example:
S = ' Hello!'
[Link](' !')
print(S)
Output:
Hello!
Splitting a string
split() Method
Splits the string at the specified separator, and returns a list. The default separator is any
whitespace.
Example:
txt = "welcome to the python world"
x = [Link]()
print(x)
Output:
['welcome', 'to', 'the', 'python', 'world']
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
18. Explain about Exception handling in python?
➢ Various error messages can occur when executing Python programs. Such errors are
called exceptions.
➢ An exception can be defined as an unusual condition of a program resulting in the
interruption in the flow of the program.
45
➢ Whenever an exception occurs, it stops the execution of current program, and it cannot
proceed further to execute. An exception is a Python object that represents an error.
➢ An exception is a value (object) that is raised (“thrown”) signalling that an unexpected,
or “exceptional,” situation has occurred.
➢ Python contains a predefined set of exceptions referred to as standard exceptions.
➢ Some standard exceptions are given below:
ImportError Raised when an import(from..import) statement fails
IndexError Raised when a sequence index is out of range
NameError Raised when a local or global name is not found
TypeError Raised when an operation or function is applied to an object of
inappropriate type
ValueError Raised when a built-in operation or function is applied to an
appropriate value
IOError Raised when an input/output operation fails (e.g., ‘file not found’)
Example 1:
lst = [1, 2, 3]
lsst[0]
Traceback (most recent call last):
File "<ipython-input-2-f6df29656ae2>", line 2, in
<module> lsst[0]
NameError: name 'lsst' is not defined
Example 2:
lst = [1, 2, 3]
lst[3]
Traceback (most recent call last):
File "<ipython-input-4-ecca8424f755>", line 2,in<module>
lst[3]
IndexError: list index out of range
Example 3:
2 + '3'
Traceback (most recent call last):
File "<ipython-input-5-8fd9dcfa4f42>", line 1, in <module>
2 + '3'
46
TypeError: unsupported operand type(s) for +: 'int' and
'str'
Example 4:
int('12.04')
Traceback (most recent call last):
File "<ipython-input-7-6210505837df>", line 1, in <module>
int('12.04')
ValueError: invalid literal for int() with base 10: '12.04'
➢
The Propagation of Raised Exceptions
➢ When an exception is raised and not handled by the client code, it is automatically
propagated back to the client’s calling code (and its calling code, etc.) until handled.
Try
{this code}
Except
{Run this code if exception occurs}
Else
{Run this code if no exception occurs}
➢ Exceptions are caught and handled in Python by use of a try block and exception
handler.
Exception Handling and User Input
➢ Exceptions raised by built-in functions, programmer-defined functions may raise
exceptions as well.
➢ Suppose we prompted the user to enter the current month as a number,
month = input('Enter current month (1–12): ')
➢ The input function will return whatever is entered as a string. We can do integer type
conversion on this value to make it an integer type,
month =int(input('Enter current month (1–12): '))
➢ If the input string contained non-digit characters (except for 1 and 2), the int function
would raise a ValueError exception.
➢ IOError exceptions raised as a result of a file open error can be caught and handled.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
47
PROBLEM SOLVING USING PYTHON
UNIT 5
2 MARKS
1
1. What is associative data structure?
➢ The elements of an associative data structure are unordered, instead accessed by an
associated key value.
➢ In Python, an associative data structure is provided by the dictionary type.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
2. What is Dictionary?
➢ A dictionary is a mutable, associative data structure of variable length.
➢ In Python, a dictionary is a collection of elements/ items where each element is a pair
of key and value.
➢ The syntax for declaring dictionaries in Python is given below.
Example:
student_dictionary ={'rollNo':1,'name':'Rani','dept':’CS'}
print(type(student_dictionary))
Output:
<class 'dict'>
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
3. What is Indexed data structure?
➢ Elements of indexed linear data structures, such as lists, are ordered—the first element
(at index 0), second element (at index 1), and so forth.
➢ Index means position or location of data.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
4. What is Set data type in python?
➢ A set is a mutable data type with nonduplicate, unordered values, providing the usual
mathematical set operations.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
2
5. What is frozen set?
➢ Frozen set is an immutable set type.
➢ Elements of the frozen set remain the same after creation.
➢ Syntax: frozenset([iterable])
Where, Iterable can be set, dictionary, tuple, etc.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
6. List out the Set Operators.
Set Operator Set A={1,2,3} Set B={3,4,5,6}
Membership 1 in A True True if 1 is a member of set
Add [Link](4) {1,2,3,4} Add new member to set
Remove [Link](2) {1,3} Remove member from set
Union A|B {1,2,3,4,5,6} Set of elements in either set
A or set B
Intersection A&B {3} Set of elements in both set A
and set B
Difference A-B {1,2} Set of elements in set A, but
not set B
Symmetric difference A^B {1,2,4,5,6} Set of elements in set A or
set B, but not both.
Size len(a) 3 Number of elements in set
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
7. What is Object Oriented programming?
➢ Object oriented programming (OOP) is a structure of program with properties and
methods of individual objects.
➢ An object is a data of a program.
➢ Every object has its properties and methods.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
8. What is a class?
➢ A class specifies the set of instance variables and methods that are “bundled together”
for defining a type of object.
➢ A class is a "blueprint” to define an object.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
9. What are the three fundamental features of Object-Oriented Programming?
The three fundamental features of object-oriented programming:
1. Encapsulation
3
2. Inheritance
3. Polymorphism
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
10. What is Encapsulation?
Encapsulation is a means of bundling together instance variables and methods to form a given
type, as well as a way of restricting access to certain class members.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
11. What is Inheritance?
➢ The inheritance is the process of acquiring (inherit) the properties of one class to
another class.
➢ The inheriting class is called a subclass (also “derived class” or “child class”), and the
class inherited from is called the superclass (also “base class” or “parent class”).
Parent Class
Child Class
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
12. What is subtype?
A subtype is something that can be substituted for and behave as its parent type (and its parent
type, etc.).
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
13. What is Polymorphism?
In object-oriented programming, polymorphism allows objects of different types, each with
their own specific behaviors, to be treated as the same general type.
Example:
Shape
Circle Square
Triangle
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
4
14. What is Recursive function?
➢ A recursive function is a function that calls itself.
➢ Example for recursive function is finding factorial of a given number.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
15. Write about three important characteristics of recursive function.
1. There must be at least one base case (a problem instances whose solution is known
without further recursive breakdown).
2. Problems that are not a base case are broken down into subproblems that are a similar
kind of problem as the original problem and work towards a base case.
3. There is a way to derive the solution of the original problem from the solutions of the
recursively solved subproblems.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
16. List out the difference between Set and Frozen set.
Set Frozen Set
A Set can be defined as an unordered list of Frozen set is an immutable (unchangeable)
data types that are iterable, changeable set type.
(mutable), and doesn’t have copy items.
In Python sets, you can change the items Items of the frozen set remain the same once
when you required, created. Because of this, frozen sets are used
as a key in Dictionary.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
5
PROBLEM SOLVING USING PYTHON
A control statement is a statement that determines the control flow of a set of instructions. A
control structure is a set of instructions and the control statements controlling their execution.
Three fundamental forms of control in programming are sequential, selection, and iterative
control.
• Sequential control is an implicit form of control in which instructions are executed in
the order that they are written.
• Selection control is provided by a control statement that selectively executes
instructions.
• iterative control is provided by an iterative control statement that repeatedly executes
instructions.
Indentation in Python
• A header in Python is a specific keyword followed by a colon.
• The set of statements following a header in Python is called a suite(commonly called
a block).
• A header and its associated suite are together referred to as a clause.
Selection Control or Decision Making statement
A selection control statement is a control statement providing selective execution of
instructions.
• if statements
• if-else statements
• Nested if statements
• Multi-way if-elif-else statements
if statement:
• An if statement is a selection control statement based on the value of a given Boolean
expression.
• The if statement executes a statement if a condition is true.
1
PROBLEM SOLVING USING PYTHON
Example :
2
PROBLEM SOLVING USING PYTHON
if-else statements
• The if-else statement takes care of a true as well a false condition.
Example :
Nested if statements
• One if statement inside another if statement then it is called a nested if statement.
Syntax :
if Boolean-expression1:
if Boolean-expression2:
statement1
else:
statement2
else:
statement3
3
PROBLEM SOLVING USING PYTHON
Flow chart
Example :
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
Flow Chart:
4
PROBLEM SOLVING USING PYTHON
Example:
Syntax :
Expression1 if condition else Expression2
Example :
num1=8; num2=9
print(num1) if num1<num2 else print(num2)
Example:
To check whether the given year is leap year or not
The Boolean data type contains two Boolean values, denoted as True and False in Python.
A Boolean expression is an expression that evaluates to a Boolean value.
Iteration statements
• While Loop
• For Loop
5
PROBLEM SOLVING USING PYTHON
while Statement
A while statement is an iterative control statement that repeatedly executes a set of statements
based on a provided Boolean expression ( condition ).
Syntax :
while condition:
suite (or) statements
•
The reserved keyword while begins with the while statement.
•
The test condition is a Boolean expression.
•
The colon (:) must follow the test condition, i.e. the while statement be terminated
with a colon (:).
• The statement(s) within the while loop will be executed till the condition is true, i.e.
the condition is evaluated and if the condition is true then the body of the loop is
executed.
• When the condition is false, the execution will be completed out of the loop or in
other words, the control goes out of the loop.
FLOW CHART
Example :
x=1
while x < 3:
print(x)
x=x+1
OUTPUT :
6
PROBLEM SOLVING USING PYTHON
Execution
• An infinite loop is an iterative control structure that never terminates (or eventually
terminates with a system error).
Example :
while True:
num = int(input("Enter an integer: "))
print("The double of",num,"is",2 * num)
Definite vs. Indefinite Loops
• A definite loop is a program loop in which the number of times the loop will iterate
can be determined before the loop is executed.
• A indefinite loop is a program loop in which the number of times the loop will iterate
is not known before the loop is executed.
Input Error Checking
Example :
a=5;b=3
ch=int(input("Enter the choice"))
while ch!=1 and ch!=2:
ch=int(input("Enter either 1 or 2"))
if ch==1:
print(a+b)
else:
print(a-b)
7
PROBLEM SOLVING USING PYTHON
range() function
range(5) [0,1,2,3,4]
range(1,5) [1,2,3,4]
range(1,10,2) [1,3,5,7,9]
range(5,0,-1) [5, 4, 3, 2, 1]
range(0,1) [0]
range(1,1) Empty
range(0) Empty
for loop
• A for statement is an iterative control statement that iterates once for each element in
a specified sequence of elements.
• Used to construct definite loops.
8
PROBLEM SOLVING USING PYTHON
Syntax :
for var in sequence:
statement(s)
………………………………
……………………………
………………………………
• for and in are essential keywords to iterate the sequence of values.
• var takes on each consecutive value in the sequence
• statements in the body of the loop are executed once for each value
Flow chart
•The for loop repeats a group of statements for a specified number of times.
for var in range(m,n):
print var
• function range(m, n) returns the sequence of integers starting from m, m+1, m+2,
m+3…………… n-1.
Example :
for i in range(1,6):
print(i)
Lists
A list is a linear data structure, thus its elements have a linear ordering.
Example :
• lst = [1,2,3,4,5]
• lst = [‘a,’b’,’c’,’d’]
• lst= [1,’ABC’,98.5,’HELLO’]
➢ Operations commonly performed on lists include retrieve, update, insert, remove, and
append.
➢ A list traversal is a means of accessing, one-by-one, the elements of a list.
9
PROBLEM SOLVING USING PYTHON
A list in Python is a mutable, linear data structure of variable length, allowing mixed-type
elements. Mutable means that the contents of the list may be altered. Lists in Python use
zerobased indexing.
All lists have index values 0 ... n-1, where n is the number of elements in the list. Lists are
denoted by a comma-separated list of elements within square brackets
lst = [10,20,30,40,50]
lst[0]=10
lst[1]=20
lst[2]=30
lst[3]=40
lst[4]=50
lst[-1]=50
lst[-2]=40
lst[-3]=30
lst[-4]=20
lst[-5]=10
Syntax : [Link](element)
Eg : [Link](60)
Eg : lst[2]=25
Eg : del lst[3]
10
PROBLEM SOLVING USING PYTHON
lst[1:3]=[20,30]
lst[1:4]=[20,30,40]
lst[:4]=[10,20,30,40]
lst[2:]=[30,40,50]
Built-in-function
[Link](element)
[Link](element)
[Link](element,start)
[Link](element)
[Link](list)
[Link](index)
[Link](index,element)
[Link](element)
[Link]()
[Link]()
>>> lst1=[1,2,3,4]
>>> lst2=lst1
>>> print(lst2)
[1, 2, 3, 4]
List Comprehension
List comprehensions in Python provide a concise means of generating a more varied set of
sequences than those that can be generated by the range function.
11
PROBLEM SOLVING USING PYTHON
Syntax :
Eg:
print(lst)
Example:
lst1=[1,2,3,4]
lst2=[2,5,6,7]
print(pair)
Looping in List
lst = [10,20,30,40,50]
for i in lst:
print(i)
O/P :
10
20
30
40
50
12
PROBLEM SOLVING USING PYTHON
Nested Lists
Tuples
tup=()
tup1=(“apple”,”banana”,1997,2020)
tup2=(1,2,3,4,5)
Basic Operations
a=(10,20,20,40,50,60,10,80) b=(1,2,3,4,5,6)
Length : len(a) : 8
Concatentation : a+b : (10, 20, 20, 40, 50, 60, 10, 80, 1, 2, 3, 4, 5, 6)
13
PROBLEM SOLVING USING PYTHON
Repetition : a*2 : (10, 20, 20, 40, 50, 60, 10, 80, 10, 20, 20, 40, 50, 60, 10, 80)
Membership : 20 in a : True
Index : [Link](40) : 3
Count : [Link](20) : 2
Conversion to Tuple
lst=[]
for i in range(5):
#ele=int(input())
[Link](i)
print(lst)
tup=tuple(lst)
print(tup)
Sample program for tuple : Counting [Link] ODD & EVEN numbers in tuple
input_tuple=()
final_tuple=()
oddc=0
evenc=0
for i in range(1,11):
input_tuple=(i)
final_tuple=final_tuple+(input_tuple,)
print(final_tuple)
for x in final_tuple:
temp=int(x)
if temp%2==0:
evenc=evenc+1
14
PROBLEM SOLVING USING PYTHON
else:
oddc=oddc+1
15
UNIT-V ( 5Marks )
1. Discuss the concept of a class.
A class specifies the set of instance variables and methods that are “bundled
together” for defining a type of object. Class is a blueprint or template to define an
object. Attributes are the names given to the variables that make up a class.
A class instance with a defined set of properties is called an object. As a result, the
same class can be used to construct as many objects as needed.
class Book:
def __init__(self, title, quantity, author, price):
[Link] = title
[Link] = quantity
[Link] = author
[Link] = price
The __init__ special method, also known as a Constructor, is used to initialize the
Book class with attributes such as title, quantity, author, and price.
In Python, built-in classes are named in lower case, but user-defined classes are
named in Camel or Snake case, with the first letter capitalized.
This class can be instantiated to any number of objects. Three books are instantiated
in the following example code:
book1, book2 and book3 are distinct objects of the class Book. The term self in the
attributes refers to the corresponding instances (objects).
print(book1)
print(book2)
print(book3)
Output:
The class and memory location of the objects are printed when they are printed. We
can't expect them to provide specific information on the qualities, such as the title,
author name, and so on. But we can use a specific method called __repr__ to do
this.
In Python, a special method is a defined function that starts and ends with two
underscores and is invoked automatically when certain conditions are met.
class Book:
def __init__(self, title, quantity, author, price):
[Link] = title
[Link] = quantity
[Link] = author
[Link] = price
def __repr__(self):
return f"Book: {[Link]}, Quantity: {[Link]}, Author: {[Link]}, Price:
{[Link]}"
print(book1)
print(book2)
print(book3)
Output:
Class A is the superclass of all the classes in the figure. Thus, subclasses B
and E each inherit variable var1 and method method1 from Class A. In addition,
Class B defines variable var2 and method method2, and Class E defines method5.
Since Class C is a subclass of Class B, it inherits everything in Class A and Class B,
adding var3 and method3 in its own definition. And since Class D is also a subclass
of Class B, it inherits everything in Class A and Class B, also defining method4.
>>> fruit
True
Sets do not maintain a logical ordering. Therefore, it is invalid and makes no sense
to access an element of a set by index value.
The add and remove methods allow sets to be dynamically altered during program
execution, for example,
In the above example, to create an empty an empty set1, the notation set () is
used, since empty braces is used to create an empty dictionary. Because sets do not
have duplicate elements, adding an already existing item to a set results in no
change to the set.
x= set ()
print (x)
print (n)
Output:
set()
{0, 1, 2, 3, 4}
>>>
Set Types
1. set type-
The set type is mutable---the contents can be changed using methods like
add() and remove(). Since it is mutable, it has no hash value and cannot be used as
either a dictionary key or as an element of another set.
2. frozenset type: The frozenset type is immutable and hashable ---its contents
cannot be altered after it is created; however, it can be used as a dictionary key or as
an element of another set.
Example:
As shown in the above example, the values of a set of type frozenset must be
provided in a single list when defined. (A frozenset type is needed when a set is
used as a key value in a given dictionary.)
Public members of a class, on the other hand, are directly accessible. For
example, the following are valid method calls,
[Link]() ALLOWED
[Link]() ALLOWED
[Link](4) ALLOWED
[Link](6) ALLOWED
These methods are referred to as getters and setters since their purpose is to
get (return) and set (assign) private instance variables of a class. Restricting access
to instance variables via getter and setter methods allows the methods to control
what values are assigned (such as not allowing an assignment of 0 to the
denominator), and how they are represented when retrieved. Thus, the instance
variables of a class are generally made private, and the methods of the class
generally made public.
The class keyword is used to define classes, much as def is used for defining
functions. All lines following the class declaration line are indented. Instance
variables are initialized in the __init__ special method. Being private, instance
variables __numerator and __denominator are not meant to be directly accessed.
>>> frac1.__numerator
>>>frac1._Fraction__numerator
self.__numerator = numerator
[Link]()
return self._numerator
def getDenominator (self):
return self._denominator
self.__numerator - value
"""
if value == 0:
To understand this, all private class members are automatically renamed to begin
with a single underscore character followed by the class name. Such renaming of
identifiers is called name mangling. Unless the variable or method is accessed with
its complete (mangled) name, it will not be found. Name mangling prevents
unintentional access of private members of a class, while still allowing access when
needed.
ENCAPSULATION:
Public members of a class, on the other hand, are directly accessible. For
example, the following are valid method calls,
[Link]() ALLOWED
[Link]() ALLOWED
[Link](4) ALLOWED
[Link](6) ALLOWED
These methods are referred to as getters and setters since their purpose is to
get (return) and set (assign) private instance variables of a class. Restricting access
to instance variables via getter and setter methods allows the methods to control
what values are assigned (such as not allowing an assignment of 0 to the
denominator), and how they are represented when retrieved. Thus, the instance
variables of a class are generally made private, and the methods of the class
generally made public.
INHERITANCE:
Inheritance, in object-oriented programming, is the ability of a class to inherit
members of another class as part of its own definition. The inheriting class is called a
subclass (also ―derived class‖ or ―child class‖), and the class inherited from is called
the superclass (also ―base class‖ or ―parent class‖). Superclasses may themselves
inherit from other classes, resulting in a hierarchy of classes.
Class A is the superclass of all the classes in the figure. Thus, subclasses B
and E each inherit variable var1 and method method1 from Class A. In addition,
Class B defines variable var2 and method method2, and Class E defines method5.
Since Class C is a subclass of Class B, it inherits everything in Class A and Class B,
adding var3 and method3 in its own definition. And since Class D is also a subclass
of Class B, it inherits everything in Class A and Class B, also defining method4.
POLYMORPHISM:
The word polymorphism derives from Greek meaning ―something that takes
many forms.‖ In objectoriented programming, polymorphism allows objects of
different types, each with their own specific behaviors, to be treated as the same
general type. For example, consider the Shape class and its subclasses.
class Shape:
self.__x = x
self.__y = y
def getXYLoc(self):
self.__x = x
self.__x = x
def calcArea(self):
Subclasses of the Shape class must implement the calcArea method, otherwise a
NotImplementedError exception is raised. A class in which one or more methods are
unimplemented is called an abstract class. It gives Circle, Square, and Triangle
subclasses of the Shape class.
class Circle (Shape):
Shape.__init__(self, x, y)
self.__radius = r
return [Link]*self.__radius**2
def__init_(self, x, y, s):
Shape.__init_(self, x, y)
self.__side=s
return self.__side** 2
Shape. init_(self, x, y)
self.__side = s
Each of the subclasses contains an __init__ method, in which the first two
arguments provide the x, y location of the shape (within a graphics window) and the
third argument indicates its size. Each first calls the __init__ method of the Shape
class with arguments x, y to set its location, since the x, y values are maintained by
the Shape class. Note that methods getXYLoc and setXYLoc are not defined in the
subclasses, as they are inherited from the Shape class.
The size of each shape is handled differently, however. In the Circle class
size is stored as the radius, and in the Square and Triangle classes it is stored as the
length of each side. Given these classes, we can now see how polymorphism works
in Python.
Suppose that there was a list of Shape objects for which the total area of all
shapes combined was to be calculated,
Because each implements the methods of the Shape class, they are all of a common
general type, and therefore can be treated in the same way,
total_area = 0
Special methods used to provide arithmetic operators for class types are
class Fraction:
[Link] = num
[Link] = deno
def str(self):
Output:
>>> frac1=Fraction(2,3)
>>> frac2=Fraction(2,4)
>>>print(frac1+frac2)
(14, 12)
Adding Relational Operators to the Fraction Class:
The special methods for providing the relational operators of the Fraction class.
class FracCompare:
[Link] num
[Link] deno
Output:
>>>FracCompare(2,2)<FracCompare(-1,-1)
False
>>>>FracCompare(2,2)=FracCompare(2,2)
True
Most other relational operators are grounded in the implementation of the less
than special method, _It_. The implementation of special method _le_(less than or
equal to) is based on the fact that a <b is the same as not (b< a). Special method
_neq_ (not equal to) is simply implemented as not (a = b). Finally, special method
_gt_ (greater than) is implemented as not (a <=b), and special method _ge_ (greater
than or equal to) is implemented as not (a <b).
INHERITANCE:
POLYMORPHISM:
The word polymorphism derives from Greek meaning ―something that takes
many forms.‖ In object-oriented programming, polymorphism allows objects of
different types, each with their own specific behaviors, to be treated as the same
general type. For example, consider the Shape class and its subclasses.
class Shape:
self.__x = x
self.__y = y
def getXYLoc(self):
self.__x = x
self.__x = x
def calcArea(self):
Shape.__init__(self, x, y)
self.__radius = r
return [Link]*self.__radius**2
def__init_(self, x, y, s):
Shape.__init_(self, x, y)
self.__side=s
def calcArea (self):
return self.__side** 2
Shape. init_(self, x, y)
self.__side = s
Each of the subclasses contains an __init__ method, in which the first two
arguments provide the x, y location of the shape and the third argument indicates its
size. Each first calls the __init__ method of the Shape class with arguments x, y to
set its location, since the x, y values are maintained by the Shape class.
Note that methods getXYLoc and setXYLoc are not defined in the
subclasses, as they are inherited from the Shape class.
The size of each shape is handled differently, however. In the Circle class
size is stored as the radius, and in the Square and Triangle classes it is stored as the
length of each side. Given these classes, we can now see how polymorphism works
in Python. Suppose that there was a list of Shape objects for which the total area of
all shapes combined was to be calculated,
Because each implements the methods of the Shape class, they are all of a common
general type, and therefore can be treated in the same way,
total_area = 0
A recursive function is often defined as ―a function that calls itself.‖ There are
two types of entities related to any function however—the function definition, and any
current execution instances. What is meant by the phrase ―a function that calls itself‖
is a function execution instance that calls another execution instance of the same
function.
Every time a call to a function is made, another execution instance of the function is
created. Thus, while there is only one definition for any function, there can be any
number of execution instances. In order to fully understand the mechanism of
recursive function calls, we first consider the general mechanism of non-recursive
function calls.
In the function calls, there is no trouble visualizing the sequence of events that
occur. This calling and suspending of executing function instances could continue
indefinitely. However, in this case, function C does not make a call to any other
function. Thus, it simply executes until termination, returning control to the function
that called it, function B. Function B then continues its execution until terminating,
returning control to the function that called it, function A. Finally, function A
completes and terminates, returning control to wherever it was called from.
Now, let’s consider the situation when the original function, function A, is a
recursive function—that is, its definition includes a call to function A (itself).Each
current execution instance of function A will spawn a new execution instance of
function A.
Thus, since all instances are identical, the function calls occur in exactly the same
place in each. Clearly, if the definition of a recursive function were written so that the
function calls itself unconditionally, then every execution instance would
unconditionally call another execution instance, ad infinitum. Such a nonterminating
sequence of calls is referred to as infinite recursion, similar to the notion of an infinite
loop. Therefore, properly designed recursive functions always conditionally call
another execution instance so that eventually the chain of function calls terminates.
factorial(n)=n.(n-1).(n-2)...1
factorial (n)=1, if n= 0
1. There must be at least one base case(a problem instance whose solution is
known without further recursive breakdown).
2. Problems that are not a base case are broken down into subproblems that are a
similar kind of problems as the original problem and work towards a base case.
3. There is a way to derive the solution of the original problem from the solutions of
the recursively solved subproblems.
if n == 0:
return 1
else:
return n*factorial(n-1)
Recall that all values in Python are objects. Thus, there exists a class definition for
each of the builtin types. To determine the type (class name) of a particular value
(object) in Python, the built-in function type can be used.
I __add__(...)
I __contains__(...)
I __. eq__(…)
I find(...)
I Return the lowest index in S where substring sub is found, such that
I sub is contained within S[start: end]. Optional arguments start and end
I are interpreted as in slice notation.
I Return -1 on failure.
.
Our new exploded string type can be used as shown below.
>>>print ([Link]())
MyFavoriteMovies
Let’s see how this works. The ExplodedStr class does not defi ne any instance
variables of its own. Thus, its __init__ method simply calls the __init__ method of the
built-in str class to pass the value that the string is to be initialized to. If an initial
value is not provided, the method has a default argument assigned to the empty
string,
str.__init__(value)
Method explode returns the exploded version of the string. First, a check is made to
see if the string is the empty string. If so, then the reference self is returned, thus
returning its unaltered value. Otherwise, a new string is created (temp_str), equal to
the original string referenced by self, with a blank appended after every character
except the last. A for loop is used for this construction,
for k in range(0,len(self)-1):
temp_str=temp_str+self[k] +blank_char
Since the range function is called with parameters 0 and len(self) – 1, all except the
last character of the original string is appended by this loop (since the last character
should not have a blank character appended after it). Finally, the newly constructed
exploded string (temp_str) is returned.
We can place the ExplodedStr class in its own module called exploded_str and
import it when needed. Testing this new string type, we see that it behaves as
desired.
'Hello'
>>> reg_str value of exploded string
'Hello'
Hello
True
>>>
We see that exploded strings can be used as a regular string or in exploded form.
Thus, it is only the added behavior of being able to be exploded that is different, not
its value. As a result, the ExplodedStr subclass serves as a subtype of the built-in
string class.
Method names that begin and end with two underscore characters are called special
methods in Python. Special methods are automatically called. For example, the
__init__ method of the Fraction class developed is automatically called whenever a
new Fraction object is created,
__str__ and
__repr__.
These methods are used for representing the value of an object as a string.
The __str__ method is called when an object is displayed using print (and
when the str conversion function is used.)
The __repr__ function is called when the value of an object is displayed in the
Python shell (when interactively using Python). This is demonstrated below.
class DemoStrRepr():
def __repr__(self):
def __str__(self):
Output:
>>>s= DemoStrRepr()
>>>print(s)
__str__ called
>>>s
__repr__called
>>>
The difference in these special methods is that __str__ is for producing a string
representation of an object’s value that is most readable (for humans), and __repr__
is for producing a string representation that Python can evaluate. If special method
__str__ is not implemented, then special method __repr__ is used in its place. An
implementation of __repr__ for the Fraction class is given below.
def __repr__(self):
>>> frac1
3/4
Value of frac1 is ¾
Special methods used to provide arithmetic operators for class types are
The expression frac1 + frac2, for example, evaluates to the returned value of
the add_method in the class, where the left operand (frac1) is the object on which
the method call is made: frac1._add (frac2). Arithmetic methods for the Fraction
class are given.
class Fraction:
[Link] = num
[Link] = deno
def str(self):
Output:
>>> frac1=Fraction(2,3)
>>> frac2=Fraction(2,4)
>>>print(frac1+frac2)
(14, 12)
Adding Relational Operators to the Fraction Class:
The special methods for providing the relational operators of the Fraction class.
class FracCompare:
[Link] num
[Link] deno
Output:
>>>FracCompare(2,2)<FracCompare(-1,-1)
False
>>>FracCompare(2,2)=FracCompare(2,2)
True
Most other relational operators are grounded in the implementation of the less
than special method, _It_. The implementation of special method _le_(less than or
equal to) is based on the fact that a <b is the same as not (b< a). Special method
_neq_ (not equal to) is simply implemented as not (a = b). Finally, special method
_gt_ (greater than) is implemented as not (a <=b), and special method _ge_ (greater
than or equal to) is implemented as not (a <b).