0% found this document useful (0 votes)
3 views47 pages

Python Unit IV

This document covers various concepts related to problem-solving using Python, including object-oriented programming, turtle graphics, modules, namespaces, and file operations. It explains the attributes and behaviors of objects, the importance of references, garbage collection, and how to manipulate turtle graphics. Additionally, it discusses file handling, string processing, and the structure of Python modules.

Uploaded by

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

Python Unit IV

This document covers various concepts related to problem-solving using Python, including object-oriented programming, turtle graphics, modules, namespaces, and file operations. It explains the attributes and behaviors of objects, the importance of references, garbage collection, and how to manipulate turtle graphics. Additionally, it discusses file handling, string processing, and the structure of Python modules.

Uploaded by

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

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.

Creating a Turtle Graphics Window


= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
8. What is Default Turtle?
➢ A default turtle is created when the setup method is called.
➢ A call to method getturtle returns the reference to the default turtle and causes it to
appear on the screen.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
9. What are the fundamental turtle attributes?
➢ Turtle objects have three fundamental attributes:
1. position
2. heading (orientation)
3. pen attributes.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
10. How can you change the turtle’s position?
➢ A turtle’s position can be changed using:
1. Absolute positioning
2. Relative Positioning

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.

Copying of Lists by Use of the List Constructor

➢ A copy of the list structure has been made.


➢ Therefore, changes to the list elements of list1 will not result in changes in
list2.
>>>list1[0] = 5
>>>list2[0]
10
Shallow Copy:
➢ The situation is different if a list contains sublists, however.
>>>list1 = [[10, 20], [30, 40], [50, 60]]
>>>list2 = list(list1)
The resulting list structure after the assignment is depicted in the following Figure.

Shallow Copy List Structures

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.

Top-Level Reassignment of Shallow Copies

➢ 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.

Sublevel Reassignment of Shallow Copies

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 = copy.deepcopy(list1)
➢ The result of this form of copying is given in the following Figure.

Deep Copy List Structures


➢ A deep copy operation makes a complete copy of a list.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
3. Distinguish the difference between Shallow Copy and Deep Copy in Python?
Sl.no Shallow Copy Deep Copy
1 A shallow copy also makes a separate A deep copy makes a new and separate
new object or list, but instead of copying copy of an entire object or list with its
the child elements to the new object, it own unique memory address.
simply copies the references to their
memory addresses.
2 shallow copy stories reference to the Deep copy stores copies of an object's
original memory address values
3 In shallow copy, a reference of object is In Deep copy, a copy of object is copied
copied in another object. It means that in another object. It means that any
any changes made to a copy of object changes made to a copy of object do not
do reflect in the original object. reflect in the original object.
4 a shallow copy doesn't create a copy of This process happens by first creating a
nested objects, instead it just copies the new list or object, followed by recursively
reference of nested objects. copying the elements from the original
one to the new one.

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 = copy.copy(result_A) Student A grades
result_B = copy.deepcopy(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
turtle.methodname .
➢ 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.

Python Turtle Graphics Window (of size 800 3 600)

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:
>>> turtle.goto(100,100)

➢ To bring the turtle back to its home position, you type the following:

>>> turtle.home()
➢ This is like a shortcut command that sends the turtle back to the point (0,0).
➢ It’s quicker than typing turtle.goto(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 = turtle.Screen()
window.bgcolor('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 = turtle.getturtle()
➢ 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.

The Default Turtle


➢ The default turtle shape is an arrowhead.
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
6. Explain the moving methods of turtle?
There are four directions that a turtle can move in:
• Forward
• Backward
• Left
• Right

Initialize the variable t, to refer the turtle:

>>> t = turtle.Turtle()
>>> t.right(90)
>>> t.forward(100)
>>> t.left(90)
>>> t.backward(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:
• t.rt() instead of t.right()
• t.fd() instead of t.forward()
• t.lt() instead of t.left()
• t.bk() instead of t.backward()
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
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:

➢ The turtle is made invisible by a call to method hideturtle.

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,
turtle.colormode(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.

Changing the Size of a Turtle

➢ The first instruction sets the resize attribute of a turtle to ‘user’.


➢ This allows the user (programmer) to change the size of the turtle by use of method
turtlesize.
➢ In the second instruction calls to turtlesize with two parameters.
➢ The first parameter is used to change the width of the shape (perpendicular to its
orientation), and the second parameter changes its length (parallel to its orientation).
➢ Each value provides a factor by which the size is to be changed.
➢ Thus, the_turtle.turtlesize(3, 3)stretches both the width and length of
the current turtle shape by a factor of 3. (A third parameter can also be added that
determines the thickness of the shape’s outline.)
Turtle Shape & Fill Color
➢ There are a number of ways to change that a turtle’s default shape (the arrowhead) and
fill color (black).
➢ First, a turtle may be assigned one of the following provided shapes: 'arrow',
'turtle', 'circle', 'square', 'triangle', and 'classic' (the
default arrowhead shape), as shown in the following Figure.

Available Turtle Shapes

➢ 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.

Creating a New Polygon Turtle Shape

➢ 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 turtle.tilt(angle)
27
Example:
# tilt turtleshape by 45
turtle.tilt(45)
= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
9. How will you create multiple turtle?
➢ Any number of turtle objects can be created by use of method Turtle().
turtle1 = turtle.Turtle()
turtle2 = turtle.Turtle()
etc.
➢ By storing turtle objects in a list, any number of turtles may be maintained,
turtles = []
turtles.append(turtle.Turtle())
turtles.append(turtle.Turtle())
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.

Example :Name Clash of Imported Functions

➢ 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:
module1.double and module2.double

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.

Local, Global, and Built-in Namespaces of Python

= = = == = = = = = = = = = = = = = = = == = = = = = = = = = = = = = = = = == = = = = = =
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('myfile.txt','r')
➢ The first argument is the file name to be opened, 'myfile.txt'.
➢ 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('mynewfile.txt','w')
➢ The first argument is the file name to be opened, 'mynewfile.txt'.

➢ 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

Reading from a Text File

Using FOR statement


➢ It is also possible to read the lines of a file by use of the FOR statement,

33
input_fi le = \
open('myfile.txt','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.

Writing to a Text File

➢ This code copies the contents of the input file, 'myfile.txt', 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 le.readline()
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.
string.count(substring)
Example:
s = 'Hello Goodbye!'
s.count('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.
➢ string.index(value, start, end); start & end is optional.
Example:
s = 'Hello Goodbye!'
s.index('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: string.isalpha()
Example 1:
S=’hello’
X=S.isalpha()
Print(X)
Output:
True
Example 2:
S=’hello!!’
X=S.isalpha()
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: string.isdigit()
Example 1:
S=’123’

42
X=S.isdigit()
Print(X)
Output:
True
Example 2:
S=’123aa’
X=S.isdigit()
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: string.islower()
Example:
a = "Welcome Python World!"
print(a.islower())
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: string.isupper()
Example:
a = "Welcome Python World!"
print(a.isupper())
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: string.lower()
Example:
a = "Welcome Python World!"
print(a.lower())
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: string.upper()
Example:
a = "Welcome Python World!"
print(a.upper())
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(a.find("e"))
Output:
1
Example 2:
a = "Welcome Python World!"
print(a.find(“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(a.replace("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!'
S.strip(' !')
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 = txt.split()
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

You might also like