Unit 4
Unit 4
UNIT 4:
Objects and their use: Software Objects - Turtle Graphics – Turtle attributes-Modular Design:
Modules - Top-Down Design - Python Modules -Text Files: Opening, reading and writing text
files. String Processing - Exception Handling
In Python, an object is an instance of a class, which acts as a blueprint for creating objects. Each
object contains data (variables) and methods to operate on that data. Python is object-oriented,
meaning it focuses on objects and their interactions. For a better understanding of the concept of
objects in Python. Let's consider an example, many of you have played CLASH OF CLANS, So
let's assume base layout as the class which contains all the buildings, defenses, resources, etc.
Based on these descriptions we make a village, here the village is the object in Python.
Creating an object
When creating an object from a class, we use a special method called the constructor, defined as
__init__(), to initialize the object's attributes. Example:
class Car:
def __init__(self, model, price):
self.model = model
self.price = price
Output
R8
100000
Explanation: Car class defines a blueprint for car objects. The __init__() constructor initializes
the model and price attributes, using self to refer to the current object. When Audi = Car("R8",
100000) is executed, "R8" is assigned to model and 100000 to price. These attributes are
accessed via dot notation, like Audi.model and Audi.price.
Accessing class members
1
In Python, you can access both instance variables and methods of a class using an object.
Instance variables are unique to each object, while methods define the behavior of the objects.
Below are examples demonstrating how to access and interact with class members:
Example 1: In this example, we use methods to access and modify the car's attributes.
class Car:
def __init__(self, model):
self.model = model
def getprice(self):
return self.price
Audi = Car("R8")
Audi.setprice(1000000)
print(Audi.getprice())
Output
1000000
Explanation: Car class defines a blueprint for car objects with a constructor (__init__()) to
initialize the model attribute. The setprice() method assigns a price and getprice() retrieves it.
When Audi = Car("R8") is executed, the model is set to "R8", the price is set using setprice() and
the price is accessed with getprice().
Example 2: In this example, we create multiple car objects and access the model and price
attributes directly using the objects, without the need for methods.
class Car:
vehicle = 'Car'
print(Audi.model, Audi.price)
print(BMW.model, BMW.price)
2
Output
R8 100000
I8 10000000
Explanation: Car class defines a blueprint with a class variable vehicle and a constructor to
initialize model and price. When Audi = Car("R8", 100000) and BMW = Car("I8",
10000000) are executed, the attributes are set and accessed directly,
like Audi.model and Audi.price.
Self keyword in Python objects
In Python objects, the self keyword represents the current instance of the class. It is
automatically passed to instance methods and is used to access and modify the object's own
attributes and methods. By using self, each object can maintain its own separate state, ensuring
that operations are performed on the correct instance. Example:
class Test:
def __init__(self, a, b):
self.country = a
self.capital = b
def fun(self):
print("Capital of " + self.country + " is " + self.capital)
x = Test("India", "Delhi")
x.fun()
Output
Capital of India isDelhi
Explanation: Test class uses the __init__() constructor to initialize the country and capital
attributes with self. When x is created with "India" and "Delhi", x.country and x.capital are set.
The fun() method then accesses these attributes via self .
Deleting an object
You can delete objects, variables or object properties using the del keyword. This removes the
reference to the object or attribute from memory, allowing Python's garbage collector to reclaim
the memory if no other references exist. Example:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
3
del Audi # deleting obj
print(Audi.brand)
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 10, in <module>
print(Audi.brand)
^^^^
NameError: name 'Audi' is not defined
SOFTWARE OBJECT:
In Python, a software object is a fundamental concept of object-oriented programming
(OOP). It's an instance of a class, which acts as a blueprint defining the object's structure and
behavior. Key aspects of software objects in Python include:
1. Encapsulation: Objects bundle data (attributes) and methods (functions) that operate on that
data. This encapsulation helps manage complexity and protects the object's internal state.
2. State: An object's state is represented by its attributes, which store data specific to that
instance.
3. Behavior: An object's behavior is defined by its methods, which perform actions and
operations on the object's data.
4. Identity: Each object has a unique identity, which distinguishes it from other objects.
5. Classes: Objects are created from classes. A class is a template or blueprint that defines the
structure and behavior of objects.
6. Instantiation: The process of creating an object from a class is called instantiation.
7. Examples:
A "Car" object might have attributes like color, model, and speed, and methods like start,
stop, and accelerate.
A "Student" object might have attributes like name, age, and grade, and methods like
study and take_exam.
Even basic data types like integers, strings, lists, and dictionaries are objects in Python.
8. Object-Oriented Programming (OOP) Principles: Software objects in Python support OOP
principles such as:
Inheritance: Allows a class to inherit properties and methods from another class.
Polymorphism: Enables objects of different classes to be treated as objects of a common
type.
Abstraction: Hides complex implementation details and exposes only essential
information.
9. Benefits:
4
Objects help organize code into reusable and manageable units.
Objects allow for modeling real-world entities and their interactions.
Objects promote code flexibility and maintainability.
10. Creation: Objects are created by calling the class like a function, passing any necessary
arguments to the constructor (__init__ method).
TURTLE GRAPHICS:
“Turtle” is a Python feature like a drawing board, which lets us command a turtle to draw all
over it! We can use functions like turtle.forward(...) and turtle.right(...) which can move the turtle
around. Commonly used turtle methods are :
fillcolor() Color name Changes the color of the turtle will use to fill a polygon
5
Method Parameter Description
end_fill() None Close the polygon and fill with the current fill color
6
wn.title("Turtle")
skk = turtle.Turtle()
Now that we have created the window and the turtle, we need to move the turtle. To move
forward 100 pixels in the direction skk is facing, we code:
skk.forward(100)
We have moved skk 100 pixels forward, Awesome! Now we complete the program with the
done() function and We're done!
turtle.done()
So, we have created a program that draws a line 100 pixels long. We can draw various shapes
and fill different colors using turtle methods. There's plethora of functions and programs to be
coded using the turtle library in python. Let's learn to draw some of the basic shapes.
Shape 1: Square
# Python program to draw square
# using Turtle Programming
import turtle
skk = turtle.Turtle()
for i in range(4):
skk.forward(50)
skk.right(90)
turtle.done()
Output:
Shape 2: Star
# Python program to draw star
# using Turtle Programming
import turtle
star = turtle.Turtle()
7
star.right(75)
star.forward(100)
for i in range(4):
star.right(144)
star.forward(100)
turtle.done()
Output:
Shape 3: Hexagon
# Python program to draw hexagon
# using Turtle Programming
import turtle
polygon = turtle.Turtle()
num_sides = 6
side_length = 70
angle = 360.0 / num_sides
for i in range(num_sides):
polygon.forward(side_length)
polygon.right(angle)
turtle.done()
Output:
8
Shape 4: parallelogram
import turtle
Shape 5 : Circle
9
import turtle
# Set up the turtle screen and set the background color to white
screen = turtle.Screen()
screen.bgcolor("white")
# Create a new turtle and set its speed to the fastest possible
pen = turtle.Turtle()
pen.speed(0)
10
Visit pythonturtle.org to get a taste of Turtle without having python pre-installed. The shell in
PythonTurtle is a full Python shell, and you can do with it almost anything you can with a
standard Python shell. You can make loops, define functions, create classes, etc.
Some amazing Turtle Programs
def sqrfunc(size):
for i in range(4):
skk.fd(size)
skk.left(90)
size = size + 5
sqrfunc(6)
sqrfunc(26)
11
sqrfunc(46)
sqrfunc(66)
sqrfunc(86)
sqrfunc(106)
sqrfunc(126)
sqrfunc(146)
Output:
print ("This program draws shapes based on the number you enter in a uniform pattern.")
num_str = input("Enter the side number of the shape you want to draw: ")
if num_str.isdigit():
squares = int(num_str)
turtle.up
x=0
y=0
turtle.setpos(x, y)
numshapes = 8
for x in range(numshapes):
turtle.color(random.random(), random.random(), random.random())
x += 5
y += 5
turtle.forward(x)
turtle.left(y)
for i in range(squares):
12
turtle.begin_fill()
turtle.down()
turtle.forward(40)
turtle.left(angle)
turtle.forward(40)
print (turtle.pos())
turtle.up()
turtle.end_fill()
time.sleep(11)
turtle.bye()
3. Spiral Helix Pattern
# Python program to draw
# Spiral Helix Pattern
# using Turtle Programming
import turtle
loadWindow = turtle.Screen()
turtle.speed(2)
for i in range(100):
turtle.circle(5*i)
turtle.circle(-5*i)
turtle.left(i)
turtle.exitonclick()
Output:
4. Rainbow Benzene
# Python program to draw
# Rainbow Benzene
# using Turtle Programming
import turtle
colors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow']
t = turtle.Pen()
turtle.bgcolor('black')
for x in range(360):
t.pencolor(colors[x%6])
t.width(x//100 + 1)
13
t.forward(x)
t.left(59)
Output:
PYTHON MODULES:
Python Module is a file that contains built-in functions, classes,its and variables. There are
many Python modules, each with its specific work.
In this article, we will cover all about Python modules, such as How to create our own simple
module, Import Python modules, From statements in Python, we can use the alias to rename the
module, etc.
What is Python Module
A Python module is a file containing Python definitions and statements. A module can define
functions, classes, and variables. A module can also include runnable code.
Grouping related code into a module makes the code easier to understand and use. It also makes
the code logically organized.
Create a Python Module
To create a Python module, write the desired code and save that in a file with .py extension. Let's
understand it better with an example:
Example:
Let's create a simple calc.py in which we define two functions, one add and another subtract.
14
# A simple module, calc.py
def add(x, y):
return (x+y)
print(calc.add(10, 2))
Output:
12
Python Import From Module
Python's from statement lets you import specific attributes from a module without importing the
module as a whole.
Import Specific Attributes from a Python module
Here, we are importing specific sqrt and factorial attributes from the math module.
# importing sqrt() and factorial from the
# module math
from math import sqrt, factorial
15
print(factorial(6))
Output:
4.0
720
Import all Names
The * symbol used with the import statement is used to import all the names from a module to a
current namespace.
Syntax:
from module_name import *
What does import * do in Python?
The use of * has its advantages and disadvantages. If you know exactly what you will be needing
from the module, it is not recommended to use *, else do so.
# importing sqrt() and factorial from the
# module math
from math import *
16
# importing sys.path
print(sys.path)
Output:
['/home/nikhil/Desktop/gfg', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-
dynload', '', '/home/nikhil/.local/lib/python3.8/site-packages', '/usr/local/lib/python3.8/dist-
packages', '/usr/lib/python3/dist-packages',
'/usr/local/lib/python3.8/dist-packages/IPython/extensions', '/home/nikhil/.ipython']
Renaming the Python Module
We can rename the module while importing it using the keyword.
Syntax: Import Module_name as Alias_name
# importing sqrt() and factorial from the
# module math
import math as mt
Output
4.0
720
Python Built-in modules
There are several built-in modules in Python, which you can import whenever you like.
# importing built-in module math
import math
17
# 60 degrees = 1.04 radians
print(math.radians(60))
# Sine of 2 radians
print(math.sin(2))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
18
# Returns the number of seconds since the
# Unix Epoch, January 1st 1970
print(time.time())
Python provides built-in functions for creating, writing, and reading files. Two types of files can
be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s).
Text files: In this type of file, Each line of text is terminated with a special character
called EOL (End of Line), which is the new line character ('\n') in Python by default.
Binary files: In this type of file, there is no terminator for a line, and the data is stored
after converting it into machine-understandable binary language.
This article will focus on opening, closing, reading, and writing data in a text file. Here, we will
also see how to get Python output in a text file.
19
Table of Content
Opening a Text File
Read Text File
Write to Text File
Appending to a File
Closing a Text File
Opening a Text File in Python
It is done using the open() function. No module is required to be imported for this function.
File_object = open(r"File_Name","Access_Mode")
Example: Here, file1 is created as an object for MyFile1 and file2 as object for MyFile2.
# Open function to open the file "MyFile1.txt"
# (same directory) in append mode and
file1 = open("MyFile1.txt","a")
read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire
file.
File_object.read([n])
READING A TEXT FILE USING READLINE()
readline(): Reads a line of the file and returns in form of a string.For specified n, reads at most n
bytes. However, does not reads more than one line, even if n exceeds the length of the line.
File_object.readline([n])
20
READING A FILE USING READLINES()
readlines(): Reads all the lines and return them as each line a string element in a list.
File_object.readlines()
file1.seek(0)
21
file1.seek(0)
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Read(9) function is
Hello
Th
Output of Readline(9) function is
Hello
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
write(): Inserts the string str1 in a single line in the text file.
22
File_object.write(str1)
file = open("Employees.txt", "w")
for i in range(3):
name = input("Enter the name of the employee: ")
file.write(name)
file.write("\n")
file.close()
writelines(): For a list of string elements, each string is inserted in the text file.Used to insert
multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
file1 = open("Employees.txt", "w")
lst = []
for i in range(3):
name = input("Enter the name of the employee: ")
lst.append(name + '\n')
file1.writelines(lst)
file1.close()
print("Data is written into the file.")
Output:
Data is written into the file.
In this example, a file named "myfile.txt" is initially opened in write mode ( "w" ) to write lines
of text. The file is then reopened in append mode ( "a" ), and "Today" is added to the existing
content. The output after appending is displayed using readlines . Subsequently, the file is
reopened in write mode, overwriting the content with "Tomorrow". The final output after writing
is displayed using readlines.
file1 = open("myfile.txt", "w")
23
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
file1.writelines(L)
file1.close()
# Append-adds at last
file1 = open("myfile.txt", "a") # append mode
file1.write("Today \n")
file1.close()
# Write-Overwrites
file1 = open("myfile.txt", "w") # write mode
file1.write("Tomorrow \n")
file1.close()
Python close() function closes the file and frees the memory space acquired by that file. It is used
at the time when the file is no longer needed or if it is to be opened in a different file mode.
File_object.close()
# Opening and Closing a file "MyFile.txt"
# for object name file1.
file1 = open("MyFile.txt","a")
24
file1.close()
STRING PROCESSING:
Python string is a sequence of Unicode characters that is enclosed in quotation marks. In this
article, we will discuss the in-built string functions i.e. the functions provided by Python to
operate on strings.
Case Changing of Python String Methods
The below Python functions are used to change the case of the strings. Let's look at some Python
string methods with examples:
lower(): Converts all uppercase characters in a string into lowercase
upper(): Converts all lowercase characters in a string into uppercase
title(): Convert string to title case
swapcase(): Swap the cases of all characters in a string
capitalize(): Convert the first character of a string to uppercase
Example: Changing the case of Python String Methods
# Python3 program to show the
# working of upper() function
text = 'geeKs For geEkS'
25
# convert the first character of a string to uppercase
print("\nConverted String:")
print(text.capitalize())
Output
Converted String:
GEEKS FOR GEEKS
Converted String:
geeks for geeks
Converted String:
Geeks For Geeks
Converted String:
GEEkS fOR GEeKs
Original String
geeKs For geEkS
Time complexity: O(n) where n is the length of the string 'text'
Auxiliary space: O(1)
List of String Methods in Python
Here is the list of in-built Python string methods, that you can use to perform actions on string:
26
Function Name Description
27
Function Name Description
28
Function Name Description
29
Function Name Description
Exception handling in Python is a mechanism to manage errors that occur during program
execution, preventing abrupt termination. This involves using try, except, else, and finally blocks
to anticipate, catch, and handle errors.
Key Concepts:
try Block: Encloses code that might raise an exception.
except Block: Specifies how to handle a particular exception, such
as ValueError, TypeError, or ZeroDivisionError. Multiple except blocks can handle
different exceptions.
else Block: Executes if the try block runs without raising an exception.
finally Block: Always executes, regardless of whether an exception was raised or not,
often used for cleanup actions like closing files.
raise Statement: Used to manually raise an exception.
Example:
Python
30
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input. Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Result:", result)
finally:
print("Execution complete.")
In this example, if the user enters a non-numeric value, the ValueError will be caught, and if the
user enters 0, the ZeroDivisionError will be caught. If no exception occurs, the else block will
execute, and finally, the finally block will always execute.
Exception handling enhances program reliability by allowing graceful recovery from errors and
preventing program crashes.
31