UNIT 2_PythonProgramming (1)
UNIT 2_PythonProgramming (1)
Strings
The string can be defined as the sequence of characters represented in the quotation
marks. In python, we can use single, double, or triple quotes to define a string.
String handling in python is a straightforward task since there are various inbuilt functions and
operators provided.In the case of string handling, the operator + is used to concatenate two
strings as the operation "hello"+" python" returns "hello python". Strings in Python are
immutable. You can’t change a string in-place, but you can copy parts of strings to another string
to get the same effect.
The operator * is known as repetition operator as the operation "Python " *2 returns "Python
Python ".
A substring (a part of a string) froma string extracted by using a slice.A slice is defined by using
square brackets, a start offset, an end offset, and an optional step size. Some of these can be
omitted. The slice will include characters from offset start to one before end.
4. [ start : end ] indicates from the start offset to the end offset minus 1.
5. [ start : end : step ] extracts from the start offset to the end offset minus 1, skipping
characters by step.
Example
output
Go
d
Good MorningGood Morning
Good Morning how are you
s = "-"
l = ["a", "b", "c"]
print(s.join(l)) # Output: "a-b-c"
Lists
Lists are positionally ordered collections of arbitrarily typed objects, and they have no fixed size.
They are also mutable—unlike strings, lists can be modified in place by assignment to offsets as
well as a variety of list method calls.A list is created by placing all the items (elements) inside a
square bracket [ ], separated by commas. The same value can occur more than once in a list.
Empty list is created with list = []
1. First, define a list of five items. Note that they retain their original order.
2. A list can be used like a zero-based array. The first item of any non-empty list is always
a_list[0].
3. The last item of this five-item list is a_list[4], because lists are always zero-based.
4. A negative index accesses items from the end of the list counting backwards. The last item of
any non-empty list is always a_list[-1].
5. If the negative index is confusing to you, think of it this way: a_list[-n] == a_list[len(a_list) -
n]. So in this list, a_list[-3] == a_list[5 - 3] == a_list[2].
Slicing a List
A range of items in a list can be accesses by using the slicing operator (:). Part of a list, called a
“slice”is obtained by specifying two indices. The return value is a new list containing all the
items of the list, in order, starting with the first slice index (in this case a_list[1]), up to but not
including the second slice index (in this case a_list[3]).
1. The + operator concatenates lists to create a new list. A list can contain any number of items;
there is no size limit (other than available memory).
2. The append() method adds a single item to the end of the list.
4. Lists are implemented as classes. “Creating” a list is really instantiating a class. As such, a list
has methods that operate on it. The extend() method takes one argument, a list, and appends each
of the items of the argument to the original list.
5. The insert() method inserts a single item into a list. The first argument is the index of the first
item in the list that will get bumped out of position. List items do not need to be unique; for
example, there are now two separate items with the value 'Ω': the first item, a_list[0], and the last
item, a_list[6].
a_list = ['a']
a_list = a_list + [2.0, 3]
print(a_list) # Output: ['a', 2.0, 3]
a_list.append(True)
print(a_list) # Output: ['a', 2.0, 3, True]
a_list.extend(['four', 'Ω'])
print(a_list) # Output: ['a', 2.0, 3, True, 'four', 'Ω']
a_list.insert(0, 'Ω')
print(a_list) # Output: ['Ω', 'a', 2.0, 3, True, 'four', 'Ω']
Append: Adds its argument as a single element to the end of a list. The length of the list
increases by one.
Extend(): Iterates over its argument and adding each element to the list and extending the list.
The length of the list increases by number of elements in it’s argument
Lists can expand and contract automatically. There are several different ways to remove items
from a list. The elements of a list is removed by using del function. Elements can also removed
from the List by using built-in remove() function but an Error arises if element doesn’t exist in
the set. Remove() method only removes one element at a time, to remove range of elements,
iterator is used. Pop() function can also be used to remove and return an element from the set, but
by default it removes only the last element of the set, to remove element from a specific position
of the List, index of the element is passed as an argument to the pop() method.
Method Description
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
Python provides the following built-in functions which can be used with the lists.
Tuples
A tuple is an immutable list. A tuple can not be changed in any way once it is created. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets. Creating a tuple is as simple as putting different
comma-separated values.
Lists have methods like append(), extend(), insert(), remove(), and pop(). Tuples have none of
these methods. Tuples are faster than lists. The operators like concatenation (+), repetition (*),
Membership (in) works in the same way as they work with the list. We can store list inside tuple
or tuple inside the list up to any number of level.Tuples use less space. Tuples can be used as a
dictionary keys.Empty list is created with list = ().
Creating a tuple with one element is a bit tricky.Having one element within parentheses is not
enough. We will need a trailing comma to indicate that it is, in fact, a tuple.
There are various ways in which we can access the elements of a tuple.
1. Indexing
Function Description
cmp(list1, list2) It compares the elements of both the lists.
len(list) It is used to calculate the length of the list.
max(list) It returns the maximum element of the list.
min(list) It returns the minimum element of the list.
list(seq) It converts any sequence to the list.
We can use the index operator [] to access an item in a tuple where the index starts from 0.So, a
tuple having 6 elements will have indices from 0 to 5. Trying to access an element outside of
tuple (for example, 6, 7,...) will raise an IndexError.The index must be an integer; so we cannot
use float or other types. This will result in TypeError.
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
2. Negative Indexing
Python allows negative indexing for its sequences.The index of -1 refers to the last item, -2 to the
second last item and so on.
my_tuple = ('p','e','r','m','i','t')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. That also means we cannot delete
or remove items from a tuple.
But deleting a tuple entirely is possible using the keyword del.
my_tuple = ('p','r','o','g','r','a','m','i','z')
# In operation
# Output: True
print('a' in my_tuple)
# Output: False
print('b' in my_tuple)
# Not in operation
# Output: True
print('g' not in my_tuple)
2. Iterating Through a Tuple
Using a for loop we can iterate through each item in a tuple.
for name in ('John','Kate'):
print("Hello",name)
# Output:
# Hello John
# Hello Kate
2. You can’t remove elements from a tuple. Tuples have no remove () or pop() method. To
explicitly remove an entire tuple, del statement is used.
3. You can find elements in a tuple, since this doesn’t change the tuple.
4. You can also use the in operator to check if an element exists in the tuple.
List Tuple
The literal syntax of list is shown by the The literal syntax of the tuple is shown by the
[]. ().
The List has the variable length. The tuple has the fixed length.
The list provides more functionality than The tuple provides less functionality than the
tuple. list.
The list Is used in the scenario in which The tuple is used in the cases where we need to
we need to store the simple collections store the read-only collections i.e., the value of
the items cannot be changed. It can be used as
with no constraints where the value of the
the key inside the dictionary.
items can be changed.
Sets
set is a collection which is unordered and unindexed. In Python sets are written with
curly brackets. The elements of the set cannot be duplicate. Unlike other collections in python,
there is no index attached to the elements of the set, i.e., we cannot directly access any element
of the set by the index. However, we can print them all together or we can get the list of elements
by looping through the set.
The major advantage of using a set, as opposed to a list, is that it has a highly optimized method
for checking whether a specific element is contained in the set.
A set is created by placing all the items (elements) inside curly braces {}, separated by comma or
by using the built-in function set().It can have any number of items and they may be of different
types (integer, float, tuple, string etc.).But a set cannot have a mutable element, like list, set
or dictionary, as its element.Sets can be used to filter duplicates out of other collections
# Set of integers
my_set = {1, 2, 3}
Creating Set
Creating an empty set is a bit tricky. Empty curly braces {} will make an empty dictionary in
Python. To make a set without any elements we use the set() function without any argument.
# initialize a with {}
a = {}
# check data type of a
print(type(a))
# Output: <class 'dict'>
Access Items
You cannot access items in a set by referring to an index, since sets are unordered the items has
no index.But you can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in keyword.
Example:
Once a set is created, you cannot change its items, but you can add new items.Single element can
be added using the add() method and multiple elements can be added using the update() method.
The update() method can take tuples, lists, strings or other sets as its argument. In all cases,
duplicates are avoided.
# Define a set
thisset = {"apple", "banana", "cherry"}
A particular item can be removed from set using methods, discard() and remove().The only
difference between the two is that, while using discard() if the item does not exist in the set, it
remains unchanged. But remove() will raise an error in such condition. Similarly, an item can be
removed and returned using the pop() method. All items from a set is removed
using clear().The del keyword will delete the set completely.
Example
# Initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set) # Output: {1, 3, 4, 5, 6}
Set Operations
Sets can be used to carry out mathematical set operations like union, intersection, difference and
symmetric difference. This can be do with operators or methods. Union is performed
using | operator or the method union().Union of A and B is a set of all elements from both
sets.Intersection is performed using & operator or the method intersection().Intersection
of A and B is a set of elements that are common in both sets.Difference is performed
using - operator or method difference(). Difference of A and B (A - B) is a set of elements that
are only in A but not in B. Similarly, B - A is a set of element in B but not in A.Symmetric
difference is performed using ^ operator or method symmetric_difference().Symmetric
Difference of A and B is a set of elements in both A and B except those that are common in both.
Example:
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A|B)
print(A&B)
print(A-B)
print(A^B)
Output
{1, 2, 3, 4, 5, 6, 7, 8}
{4, 5}
{1, 2, 3}
{1, 2, 3, 6, 7, 8}
Python Frozenset
Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed
once assigned. While tuples are immutable lists, frozensets are immutable sets.
Dictionaries
Dictionary in Python is an unordered collection of data values, used to store data values like a
map, which unlike other Data Types that hold only single value as an element, Dictionary
holds key:value pair. Key value is provided in the dictionary to make it more optimized. Each
key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a
‘comma’.
A Dictionary in Python works similar to the Dictionary in a real world. Keys of a Dictionary
must be unique and of immutable data type such as Strings, Integers and tuples, but the key-
values can be repeated and be of any type.
Creating a Dictionary
In Python, a Dictionary can be created by placing sequence of elements within curly {} braces,
separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other
corresponding pair element being its Key:value. Values in a dictionary can be of any datatype
and can be duplicated, whereas keys can’t be repeated and must be immutable.
Dictionary can also be created by the built-in function dict(). An empty dictionary can be created
by just placing to curly braces{}.
Dict = {}
print("Empty Dictionary:")
print(Dict)
print(Dict)
print(Dict)
print(Dict)
OutPut:
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'Arun', 2: 'Deepa', 3: 'Keerthi'}
Dictionary with the use of Mixed Keys:
{'Name': 'Arun', 1: [1, 2, 3, 4]}
Dictionary with the use of dict():
{1: 'Arun', 2: 'Keerthi', 3: 'Deepa'}
Dictionary with each item as a pair:
{1: 'Arun', 2: 'Deepa'}
Accessing elements from a Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used inside square
brackets.There is also a method called get() that will also help in accessing the element from a
dictionary.
# Creating a dictionary
Dict = {1: 'arun', 'name': 'kalai', 3: 'kumar'}
In Python Dictionary, deletion of keys can be done by using the del keyword. Using del
keyword, specific values from a dictionary as well as whole dictionary can be deleted. Other
functions like pop() and popitem() can also be used for deleting specific values and arbitrary
values from a Dictionary. All the items from a dictionary can be deleted at once by
using clear() method.
print(squares.pop(4)) # Output: 16
print(squares.popitem()) # Output: (5, 25) (or another random pair in older versions)
del squares[3]
squares.clear()
print(squares) # Output: {}
del squares
Output:
16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{1: 1, 2: 4}
{}
Dictionary Methods
METHODS DESCRIPTION
clear() The clear() method removes all items from the dictionary.
dictionary_name.values(
) returns a list of all the values available in a given dictionary.
Create a new dictionary with keys from seq and values set to
fromkeys() value.
Python Exceptions
An exception can be defined as an abnormal condition in a program resulting in the disruption in
the flow of the program.
Whenever an exception occurs, the program halts the execution, and thus the further code is not
executed. Therefore, an exception is the error which python script is unable to tackle with.
Python provides us with the way to handle the Exception so that the other part of the code can be
executed without any disruption. However, if we do not handle the exception, the interpreter
doesn't execute all the code that exists after the that.
Errors can also occur at runtime and these are called exceptions. They occur, for example, when
a file we try to open does not exist (FileNotFoundError), dividing a number by zero
(ZeroDivisionError), module we try to import is not found (ImportError) etc.
Whenever these type of runtime error occur, Python creates an exception object. If not handled
properly, it prints a traceback to that error along with some details about why that error occurred.
Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that are
raised when corresponding errors occur.
Python Built-in Exceptions
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
RuntimeError Raised when an error does not fall under any other category.
UnicodeTranslateErro
r Raised when a Unicode-related error occurs during translating.
Syntax
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
We can also use the else statement with the try-except statement in which, we can place the code
which will be executed in the scenario if no exception occurs in the try block.A try clause can
have any number of except clause to handle them differently, but only one will be executed in
case an exception occurs.
Syntax
try:
#block of code
except Exception1:
#block of code
else:
#this code executes if no except block is executed
try-finally clause
The try statement in Python can have an optional finally clause. In case if there is any code
which you want to be executed, whether exception occurs or not, then that code can be placed
inside the finally block. When an exception occurs, the control immediately goes to finally block
and all the lines in finally block gets executed first. After that the control goes to except block to
handle exception.
Syntax
try:
#block of code
else:
#block of code
finally:
# block of code
# this will always be executed
Raising exceptions
An exception can be raised by using the raise clause in python. The syntax to use the raise
statement is given below.
syntax
raise Exception_class,<value>
Example
try:
a = int(input("Enter a: "))
b = int(input("Enter b: "))
if b == 0:
else:
print("a / b =", a / b)
except ArithmeticError:
except ValueError:
print("Invalid input! Please enter integer values.") # Added exception handling for non-
integer input
Output:
1.Enter a: 10
Enter b: 2
a / b = 5.0
2. Enter a: 10
Enter b: 0
3. Enter a: hello
User-Defined Exceptions
It is possible to define our own exception in Python. The built-in and user-defined exceptions in
Python using try, except and finally statements.
In Python, users can define such exceptions by creating a new class. This exception class has to
be derived, either directly or indirectly, from Exception class. Most of the built-in exceptions are
also derived from this class.
class Error(Exception):
pass
class ValueTooSmallError(Error):
pass
class ValueTooLargeError(Error):
pass
# Number to be guessed
number = 10
while True:
try:
except ValueTooSmallError:
print()
except ValueTooLargeError:
print()
Python Modules
A module is a file containing Python definitions and statements. A module can define functions,
classes and variables. A module can also include runnable code. Python modules are .py files
that consist of Python code. Any Python file can be referenced as a module.Grouping related
code into a module makes the code easier to understand and use.
# calc.py - A simple calculator module
We can use any Python source file as a module by executing an import statement in some other
Python source file.
The import has the following syntax
import module1[, module2[,... moduleN]
Python's from statement lets you import specific attributes from a module into the current
namespace. The from...import has the following syntax
from modname import name1[, name2[, ... nameN]]
It is also possible to import all the names from a module into the current namespace by using the
following import statement −
from modname import *
This provides an easy way to import all the items from a module into the current namespace.
When interpreter encounters an import statement, it imports the module if the module is present
in the search path. 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 :
main.py
import calc
Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.
Math module
Python Math module provides access to the mathematical functions. These include trigonometric
functions, representation functions, logarithmic functions, angle conversion functions, etc. So,
we can do many complex mathematical operations with the help of the Python Math functions
eg
import math
number = -2.34
Output
The given number is: -2.34
Floor value is: -3
Ceiling value is: -2
Absolute value is: 2.34
Random module
The random module gives access to various useful functions and one of them being able to
generate random numbers, which is randint().randint() is an inbuilt function of the random
module in Python
Syntax :
import random
r1 = random.randint(0, 10)
r2 = random.randint(-10, -1)
r3 = random.randint(-5, 5)
print("Random number between -5 and 5 is:", r3)
Output:
Packages in Python
Packages are namespaces which contain multiple packages and modules themselves. A
package is a collection of Python modules, i.e., a package is a directory of Python modules
containing an additional __init__.py file. The __init__.py distinguishes a package from a
directory that just happens to contain a bunch of Python scripts. Packages can be nested to any
depth, provided that the corresponding directories contain their own __init__.py file.
When you import a module or a package, the corresponding object created by Python is always
of type module. This means that the distinction between module and package is just at the file
system level. Note, however, when you import a package, only variables/functions/classes in the
__init__.py file of that package are directly visible, not sub-packages or modules.
Packages allow for a hierarchical structuring of the module namespace using dot notation. In
the same way that modules help avoid collisions between global variable names, packages help
avoid collisions between module names. Packages can contain nested subpackages to arbitrary
depth.
__init__.py
The package folder contains a special file called __init__.py, which stores the package's content.
It serves two purposes:
1. The Python interpreter recognizes a folder as the package if it contains __init__.py file.
2. __init__.py exposes specified resources from its modules to be imported.
An empty __init__.py file makes all functions from above modules available when this package
is imported. Note that __init__.py is essential for the folder to be recognized by Python as a
package.
The __init__.py file is normally kept empty. However, it can also be used to choose specific
functions from modules in the package folder and make them available for import.
Steps to Create a Python Package
importing packages
def display_details(self):
print("Name:", self.name, ", Age:", self.age)
Output: