0% found this document useful (0 votes)
163 views31 pages

Unit 4

Unit IV of the Python programming course covers the use of objects, turtle graphics, and modular design. It explains the concept of objects in Python, including their creation, attributes, and methods, as well as the turtle graphics library for drawing shapes. Additionally, it introduces Python modules, detailing how to create and import them for better code organization.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
163 views31 pages

Unit 4

Unit IV of the Python programming course covers the use of objects, turtle graphics, and modular design. It explains the concept of objects in Python, including their creation, attributes, and methods, as well as the turtle graphics library for drawing shapes. Additionally, it introduces Python modules, detailing how to create and import them for better code organization.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 31

UNIT-IV NOTES

Course name: Python programming Course code: 24BCA3C10

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

OBJECTS AND THEIR USE:

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

Audi = Car("R8", 100000)


print(Audi.model)
print(Audi.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 setprice(self, price):


self.price = price

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'

def __init__(self, model, price):


self.model = model
self.price = price

Audi = Car("R8", 100000)


BMW = Car("I8", 10000000)

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

Audi = Car("Audi", "A6") # creating obj

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 :

Method Parameter Description

Turtle() None Creates and returns a new turtle object

forward() amount Moves the turtle forward by the specified amount

backward() amount Moves the turtle backward by the specified amount

right() angle Turns the turtle clockwise

left() angle Turns the turtle counterclockwise

penup() None Picks up the turtle's Pen

pendown() None Puts down the turtle's Pen

up() None Picks up the turtle's Pen

down() None Puts down the turtle's Pen

color() Color name Changes the color of the turtle's pen

fillcolor() Color name Changes the color of the turtle will use to fill a polygon

5
Method Parameter Description

heading() None Returns the current heading

position() None Returns the current position

goto() x, y Move the turtle to position x,y

begin_fill() None Remember the starting point for a filled polygon

end_fill() None Close the polygon and fill with the current fill color

dot() None Leave the dot at the current position

stamp() None Leaves an impression of a turtle shape at the current location

shape() shapename Should be 'arrow', 'classic', 'turtle' or 'circle'

Plotting using Turtle


To make use of the turtle methods and functionalities, we need to import turtle."turtle" comes
packed with the standard Python package and need not be installed externally. The roadmap for
executing a turtle program follows 4 steps:
1. Import the turtle module
2. Create a turtle to control.
3. Draw around using the turtle methods.
4. Run turtle.done().
So as stated above, before we can use turtle, we need to import it. We import it as :
from turtle import *
# or
import turtle
After importing the turtle library and making all the turtle functionalities available to us, we need
to create a new drawing board(window) and a turtle. Let's call the window as wn and the turtle as
skk. So we code as:
wn = turtle.Screen()
wn.bgcolor("light green")

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

# Initialize the turtle


t = turtle.Turtle()

# Set the turtle's speed


t.speed(1)

# Draw the parallelogram


for i in range(2):
t.forward(100)
t.left(60)
t.forward(50)
t.left(120)
Output:

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)

# Set the fill color to red


pen.fillcolor("red")
pen.begin_fill()

# Draw the circle with a radius of 100 pixels


pen.circle(100)

# End the fill and stop drawing


pen.end_fill()
pen.hideturtle()

# Keep the turtle window open until it is manually closed


turtle.done()
Output:

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

1. Spiral Square Outside In and Inside Out


import turtle #Inside_Out
wn = turtle.Screen()
wn.bgcolor("light green")
skk = turtle.Turtle()
skk.color("blue")

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:

2. User Input Pattern


# Python program to user input pattern
# using Turtle Programming
import turtle #Outside_In
import turtle
import time
import random

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)

angle = 180 - 180*(squares-2)/squares

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)

def subtract(x, y):


return (x-y)
Import module in Python
We can import the functions, and classes defined in a module to another module using the import
statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module if the module is
present in the search path.
Note: A search path is a list of directories that the interpreter searches for importing a module.
For example, to import the module calc.py, we need to put the following command at the top of
the script.
Syntax to Import Module in Python
import module
Note: This does not import the functions or classes directly instead imports the module only. To
access the functions inside the module the dot(.) operator is used.
Importing modules in Python Example
Now, we are importing the calc that we created earlier to perform add operation.
# importing module calc.py
import calc

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

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))

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 *

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))
Output
4.0
720
Locating Python Modules
Whenever a module is imported in Python the interpreter looks for several locations. First, it will
check for the built-in module, if not found then it looks for a list of directories defined in
the sys.path. Python interpreter searches for the module in the following manner -
 First, it searches for the module in the current directory.
 If the module isn’t found in the current directory, Python then searches each directory in
the shell variable PYTHONPATH. The PYTHONPATH is an environment variable,
consisting of a list of directories.
 If that also fails python checks the installation-dependent list of directories configured at
the time Python is installed.
Directories List for Modules
Here, sys.path is a built-in variable within the sys module. It contains a list of directories that the
interpreter will search for the required module.
# importing sys module
import sys

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

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(mt.sqrt(16))
print(mt.factorial(6))

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

# using square root(sqrt) function contained


# in math module
print(math.sqrt(25))

# using pi function contained in math module


print(math.pi)

# 2 radians = 114.59 degrees


print(math.degrees(2))

17
# 60 degrees = 1.04 radians
print(math.radians(60))

# Sine of 2 radians
print(math.sin(2))

# Cosine of 0.5 radians


print(math.cos(0.5))

# Tangent of 0.23 radians


print(math.tan(0.23))

# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))

# importing built in module random


import random

# printing random integer between 0 and 5


print(random.randint(0, 5))

# print random floating point number between 0 and 1


print(random.random())

# random number between 0 and 100


print(random.random() * 100)

List = [1, 4, True, 800, "python", 27, "hello"]

# using choice function in random module for choosing


# a random element from a set such as a list
print(random.choice(List))

# importing built in module datetime


import datetime
from datetime import date
import time

18
# Returns the number of seconds since the
# Unix Epoch, January 1st 1970
print(time.time())

# Converts a number of seconds to a date object


print(date.fromtimestamp(454554))
Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87
We have covered Python Modules and it's operations like create, import, etc. This article will
give the overview about Python modules so that you can easily create and use modules in
Python.

TEXT FILES IN PYTHON:

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")

# store its reference in the variable file1


# and "MyFile2.txt" in D:\Text in file2
file2 = open(r"D:\Text\MyFile2.txt","w+")
Also Read: File Mode in Python
Python Read Text File
There are three ways to read txt file in Python:
 Using read()
 Using readline()
 Using readlines()

READING FROM A FILE USING READ()

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()

Note: '\n' is treated as a special character of two bytes.


In this example, a file named "myfile.txt" is created and opened in write mode ( "w" ). Data is
written to the file using write and writelines methods. The file is then reopened in read and
append mode ( "r+" ). Various read operations, including read , readline , readlines , and the use
of seek , demonstrate different ways to retrieve data from the file. Finally, the file is closed.
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

# \n is placed to indicate EOL (End of Line)


file1.write("Hello \n")
file1.writelines(L)
file1.close() # to change file access modes

file1 = open("myfile.txt", "r+")

print("Output of Read function is ")


print(file1.read())
print()

# seek(n) takes the file handle to the nth


# byte from the beginning.
file1.seek(0)

print("Output of Readline function is ")


print(file1.readline())
print()

file1.seek(0)

# To show difference between read and readline


print("Output of Read(9) function is ")
print(file1.read(9))
print()

21
file1.seek(0)

print("Output of Readline(9) function is ")


print(file1.readline(9))

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 TO TEXT FILE IN PYTHON

There are two ways to write in a file:


 Using write()
 Using writelines()
Reference: write() VS writelines()

WRITING TO A PYTHON TEXT FILE USING WRITE()

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()

print("Data is written into the file.")


Output:
Data is written into the file.

WRITING TO A TEXT FILE USING WRITELINES()

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.

APPENDING TO A FILE IN PYTHON

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()

file1 = open("myfile.txt", "r")


print("Output of Readlines after appending")
print(file1.readlines())
print()
file1.close()

# Write-Overwrites
file1 = open("myfile.txt", "w") # write mode
file1.write("Tomorrow \n")
file1.close()

file1 = open("myfile.txt", "r")


print("Output of Readlines after writing")
print(file1.readlines())
print()
file1.close()
Output:
Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']
Output of Readlines after writing
['Tomorrow \n']

Closing a Text File in Python

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'

# upper() function to convert


# string to upper case
print("\nConverted String:")
print(text.upper())

# lower() function to convert


# string to lower case
print("\nConverted String:")
print(text.lower())

# converts the first character to


# upper case and rest to lower case
print("\nConverted String:")
print(text.title())

# swaps the case of all characters in the string


# upper case character to lowercase and viceversa
print("\nConverted String:")
print(text.swapcase())

25
# convert the first character of a string to uppercase
print("\nConverted String:")
print(text.capitalize())

# original string never changes


print("\nOriginal String")
print(text)

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:

Function Name Description

Converts the first character of the string to a


capitalize()
capital (uppercase) letter

casefold() Implements caseless string matching

center() Pad the string with the specified character.

26
Function Name Description

Returns the number of occurrences of a


count()
substring in the string.

Encodes strings with the specified encoded


encode()
scheme

Returns "True" if a string ends with the given


endswith()
suffix

Specifies the amount of space to be


expandtabs()
substituted with the “\t” symbol in the string

Returns the lowest index of the substring if it


find()
is found

format() Formats the string for printing it to console

Formats specified values in a string using a


format_map()
dictionary

Returns the position of the first occurrence of


index()
a substring in a string

Checks whether all the characters in a given


isalnum()
string is alphanumeric or not

Returns “True” if all characters in the string


isalpha()
are alphabets

Returns true if all characters in a string are


isdecimal()
decimal

27
Function Name Description

Returns “True” if all characters in the string


isdigit()
are digits

Check whether a string is a valid identifier or


isidentifier()
not

Checks if all characters in the string are


islower()
lowercase

Returns “True” if all characters in the string


isnumeric()
are numeric characters

Returns “True” if all characters in the string


isprintable()
are printable or the string is empty

Returns “True” if all characters in the string


isspace()
are whitespace characters

Returns "True" if the string is a title cased


istitle()
string

Checks if all characters in the string are


isupper()
uppercase

join() Returns a concatenated String

Left aligns the string according to the width


ljust()
specified

Converts all uppercase characters in a string


lower()
into lowercase

28
Function Name Description

Returns the string with leading characters


lstrip()
removed

maketrans() Returns a translation table

Splits the string at the first occurrence of the


partition()
separator

Replaces all occurrences of a substring with


replace()
another substring

rfind() Returns the highest index of the substring

Returns the highest index of the substring


rindex()
inside the string

Right aligns the string according to the width


rjust()
specified

rpartition() Split the given string into three parts

Split the string from the right by the specified


rsplit()
separator

rstrip() Removes trailing characters

splitlines() Split the lines at line boundaries

Returns "True" if a string starts with the given


startswith()
prefix

29
Function Name Description

Returns the string with both leading and


strip()
trailing characters

Converts all uppercase characters to


swapcase()
lowercase and vice versa

title() Convert string to title case

Modify string according to given translation


translate()
mappings

Converts all lowercase characters in a string


upper()
into uppercase

Returns a copy of the string with ‘0’


zfill()
characters padded to the left side of the string

EXCEPTION HANDLING IN PYTHON:

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

You might also like