0% found this document useful (0 votes)
30 views32 pages

Unit 2

Module-2 provides an overview of Python collection objects like strings, lists, and tuples. It discusses how to create, access, and modify these objects. Some key points covered include: - Strings can be defined using single or double quotes and support operations like slicing and indexing. - Lists are ordered collections that allow duplicates and support methods like append(), pop(), sort() to modify them. - Tuples are like lists but are immutable - they do not support modification after creation. The document also discusses file handling in Python using functions like open(), read(), readline(), and close(). It shows how to open, read, and close files. Finally, it provides a brief introduction to errors and exceptions

Uploaded by

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

Unit 2

Module-2 provides an overview of Python collection objects like strings, lists, and tuples. It discusses how to create, access, and modify these objects. Some key points covered include: - Strings can be defined using single or double quotes and support operations like slicing and indexing. - Lists are ordered collections that allow duplicates and support methods like append(), pop(), sort() to modify them. - Tuples are like lists but are immutable - they do not support modification after creation. The document also discusses file handling in Python using functions like open(), read(), readline(), and close(). It shows how to open, read, and close files. Finally, it provides a brief introduction to errors and exceptions

Uploaded by

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

Module-2

PYTHON COLLECTION OBJECTS, CLASSES,


MODULES, FILES, EXCEPTION HANDLING
Strings

 Strings in Python are arrays of bytes representing unicode


characters.
 Python does not have a character data type a single
character is simply a string with a length of 1.
Creating String

 Strings in python are surrounded by either single quotation marks, or double quotation marks with
‘=‘.
 You can display a string literal with the print() function or Assign String to a Variable.
Multiline Strings:-
You can assign a multiline string to a variable by using three quotes.
Eg: x=“””Good morning all,
I am from MCA section A,
I study Python”””
print(x)
Looping through a string
Eg: for i in “MCA”
Accessing Characters in String

 Square brackets can be used to access elements of the string.


Ex: a = "Hello, World!"
print(a[1])
Basic String Operations
String Length:To get the length of a string, use the len() function.
Ex: str=“Good Morning”
print(len(str))

Check String : To check if a certain phrase or character is


present in a string, we can use the keyword in.
Ex: txt = "The best things in life are free!"
print("free" in txt)

Check if NOT: To check if a certain phrase or character is


NOT present in a string, we can use the keyword not in.

Ex: txt = "The best things in life are free!"


print(“sky" not in txt)
String Slicing

 You 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.

b = "Hello, World!"
print(b[2:5])

 Slice From the Start

 Slice To the End


String Methods
Lists

 Lists are used to store multiple items in a single variable.


 Lists are used to store multiple items in a single variable.
 List is a collection which is ordered and changeable.
 Allows duplicate members.
 In Python lists are written with square brackets.
Example :
mylist = [“red", "blue", “pink"]
print(mylist)
List Items

 List items are ordered, changeable, and allow duplicate values.


 List items are indexed, the first item has index [0], the second item has index [1] etc.
 List is a collection which is ordered and changeable. Allows duplicate members
 Ordered : When we say that lists are ordered, it means that the items have a defined
order, and that order will not change.
 Changeable : The list is changeable, meaning that we can change, add, and remove
 items in a list after it has been created.
 Allow Duplicates : Since lists are indexed, lists can have items with the same value
List Items

•List items can be of any data type:


Example : String, int and boolean data types:
Example : A list with strings, integers and
boolean values:
type()
•From Python's perspective, lists are defined as
objects with the data type 'list':
<class 'list'>
Example : What is the data type of a list?
Access Items :
•List items are indexed and you can access them by referring to the index
number:
Example : Print the second item of the list:

Note: The first item has index 0.


List Methods

Python List provides different methods to add items to a list.


append() - The append() method adds an item at the end of the list.
For example:
numbers = [21, 34, 54, 12]
print("Before Append:", numbers)
# using append method
numbers.append(32)
print("After Append:", numbers)
 extend()- We use the extend() method to add all items of one list to another. For example,
prime_numbers = [2, 3, 5]
print("List1:", prime_numbers)
even_numbers = [4, 6, 8]
print("List2:", even_numbers)
# join two lists
prime_numbers.extend(even_numbers)
print("List after append:", prime_numbers)
 Clear - removes all items from the list.
Example :
prime_numbers = [2, 3, 5]
prime_numbers.clear()

 Copy - returns the shallow copy of the list.


prime_numbers = [2, 3, 5]
prime_numbers.copy()
 count() returns the count of the specified item in the list.
prime_numbers = [2, 3, 5]
prime_numbers.count ()
 index() returns the index of the first matched item
prime_numbers = [2, 3, 5]
X= prime_numbers.index (2)
 insert() inserts an item at the specified index
prime_numbers = [2, 3, 5]
prime_numbers.insert (2,8)
 pop() returns and removes item present at the given index
prime_numbers = [2, 3, 5]
prime_numbers.pop(2)
 reverse()reverses the item of the list.
prime_numbers.reverse()
print(prime_numbers)
 sort() sort the list in ascending/descending order.
prime_numbers.sort()
print(prime_numbers)
Join - There are several ways to join, or concatenate, two or more lists in Python.
Example:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)
List Methods

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Negative Indexing

•Negative indexing means start from the end


•-1 refers to the last item, -2 refers to the second last item etc.
Example : Print the last item of the list:
Range of Indexes

•You can specify a range of indexes by specifying where to start and where to end
the range.
•When specifying a range, the return value will be a new list with the specified
items.
Example : Return the third, fourth, and fifth item:
Range of Negative Indexes

Specify negative indexes if you want to start the search from the end of the list:
Example : This example returns the items from "orange" (-4) to, but NOT including
"mango" (-1):
TUPLES

mytuple = ("apple", "banana", "cherry")


•Tuples are used to store multiple items in a single variable.
•Tuple is a collection which is ordered and unchangeable.
•Allows duplicate members.
•In Python tuples are written with round brackets.
•Tuple items are ordered, unchangeable, and allow duplicate values.
•Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
 To create a tuple with only one item, you have to add a comma after
the item, otherwise Python will not recognize it as a tuple.

Example : One item tuple, remember the comma:


Tuple Length

 To determine how many items a tuple has, use the len() method
File - Handling
 File handling is an important part of any web application.
 Python has several functions for creating, reading, updating, and deleting files.
 The key function for working with files in Python is the open() function.
 The open() function takes two parameters; filename, and mode.
 There are four different methods (modes) for opening a file:
 "r" - Read - Default value. Opens a file for reading, error if the file does not
exist
 "a" - Append - Opens a file for appending, creates the file if it does not exist
 "w" - Write - Opens a file for writing, creates the file if it does not exist
 "x" - Create - Creates the specified file, returns an error if the file exists
Syntax
 To open a file for reading it is enough to specify the name of the
file:
f = open("demofile.txt")
 The code above is the same as:
f = open("demofile.txt", "rt")
 Because "r" for read, and "t" for text are the default values, you
do not need to specify them.
 Note: Make sure the file exists, or else you will get an error.
 Assume we have the following file, located in the same folder as
Python:
 Python File Open - Open a File on the Server.
 To open the file, use the built-in open() function.
 The open() function returns a file object, which has a read() method
for reading the content of the file:
Ex – 1:
f = open("demofile.txt", "r")
 print(f.read())
Read only Parts of the file
 By default the read() method returns the whole text, but you can also
specify how many characters you want to return:
 Ex – 3 : Return the 5 first characters of the file
f = open("demofile.txt", "r")
 print(f.read(5))

readline() method:You can return one line by using the readline() method.
Read one line of the file
f = open("demofile.txt", "r")
print(f.readline())
Close Files

 Itis a good practice to always close the file when you are
done with it.
 Ex : Close the file when you are finish with it.
f = open("demofile.txt", "r")
 print(f.readline())
 f.close()
Create a new file
Errors and Exceptions in Python

Errors are the problems in a program due to which the program will
stop the execution. On the other hand, exceptions are raised when
some internal events occur which changes the normal flow of the
program.
Two types of Error occurs in python.
 Syntax errors
 Logical errors (Exceptions)

You might also like