Unti II-python
Unti II-python
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
Example
print("Hello")
print('Hello')
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 = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Or three single quotes:
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.
Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
Use it in an if statement:
Example
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
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 "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print("expensive" not in txt)
Use it in an if statement:
Example
print only if "expensive" is NOT present:
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
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.
Exampleb = "Hello, World!"
print(b[2:5])
Upper Case
ExampleGet your own Python Server
The upper() method returns the string in upper case:
a = "Hello, World!"
print([Link]())
Lower Case
Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print([Link]())
Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often you want to remove
this space.
Example
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print([Link]()) # returns "Hello, World!"
Replace String
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print([Link]("H", "J"))
Split String
The split() method returns a list where the text between the specified separator becomes the
list items.
Example
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print([Link](",")) # returns ['Hello', ' World!']
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
ExampleMerge variable a with variable b into variable c:
a = "Hello"
b = "World"
c=a+b
print(c)
Example
To add a space between them, add a " ":
a = "Hello"
b = "World"
c=a+""+b
print(c)
String Format
we can combine strings and numbers by using the format() method!
Example
age = 36
txt = "My name is John, I am " + age
print(txt)
The format() method takes the passed arguments, formats them, and places them in the string
where the placeholders {} are:
Example
Use the format() method to insert numbers into strings:
age = 36
txt = "My name is John, and I am {}"
print([Link](age))
The format() method takes unlimited number of arguments, and are placed into the respective
placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print([Link](quantity, itemno, price))
You can use index numbers {0} to be sure the arguments are placed in the correct
placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print([Link](quantity, itemno, price))
Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by
double quotes:
ExampleYou will get an error if you use double quotes inside a string that is surrounded by
double quotes:
txt = "We are the so-called "Vikings" from the north."
To fix this problem, use the escape character \":
Example
The escape character allows you to use double quotes when you normally would not be
allowed:
txt = "We are the so-called \"Vikings\" from the north."
Escape Characters
Other escape characters used in Python:
Code Result
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
String Methods
Python has a set of built-in methods that you can use on strings.
Method Description
find() Searches the string for a specified value and returns the position
of where it was found
index() Searches the string for a specified value and returns the position
of where it was found
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
partition() Returns a tuple where the string is parted into three parts
rfind() Searches the string for a specified value and returns the last
position of where it was found
rindex() Searches the string for a specified value and returns the last
position of where it was found
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
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.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and that
order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
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:
Example
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
List Items - Data Types
List items can be of any data type:
Example
String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
A list can contain different data types:
Example
A list with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]
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?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
The list() Constructor
It is also possible to use the list() constructor when creating a new list.
Example
Using the list() constructor to make a List:
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
Python Collections (Arrays)
There are four collection data types in the Python programming language:
List is a collection which is ordered and changeable. Allows duplicate members.
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate
members.
Dictionary is a collection which is ordered** and changeable. No duplicate members.
*Set items are unchangeable, but you can remove and/or add items whenever you like.
**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
When choosing a collection type, it is useful to understand the properties of that type.
Choosing the right type for a particular data set could mean retention of meaning, and, it
could mean an increase in efficiency or security.
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:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
The first item has index 0.
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:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
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:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT including, "kiwi":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
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):
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Extend List
To append elements from another list to the current list, use the extend() method.
Example
Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
[Link](tropical)
print(thislist)
The elements will be added to the end of the list.
for x in fruits:
if "a" in x:
[Link](x)
print(newlist)
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
print(newlist)
Syntax
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.
Condition
The condition is like a filter that only accepts the items that valuate to True.
Example
Only accept items that are not "apple":
newlist = [x for x in fruits if x != "apple"]
The condition if x != "apple" will return True for all elements other than "apple", making the
new list contain all fruits except "apple".
The condition is optional and can be omitted:
Example
With no if statement:
newlist = [x for x in fruits]
Iterable
The iterable can be any iterable object, like a list, tuple, set etc.
Example
You can use the range() function to create an iterable:
newlist = [x for x in range(10)]
Example
Accept only numbers lower than 5:
newlist = [x for x in range(10) if x < 5]
Expression
The expression is the current item in the iteration, but it is also the outcome, which you can
manipulate before it ends up like a list item in the new list:
Example
Set the values in the new list to upper case:
newlist = [[Link]() for x in fruits]
Example
Set all values in the new list to 'hello':
newlist = ['hello' for x in fruits]
The expression can also contain conditions, not like a filter, but as a way to manipulate the
outcome:
Example
Return "orange" instead of "banana":
newlist = [x if x != "banana" else "orange" for x in fruits]
Sort List Alphanumerically
List objects have a sort() method that will sort the list alphanumerically, ascending, by
default:
ExampleSort the list alphabetically:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
[Link]()
print(thislist)
Example
Sort the list numerically:
thislist = [100, 50, 65, 82, 23]
[Link]()
print(thislist)
Sort Descending
To sort descending, use the keyword argument reverse = True:
Example
Sort the list descending:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
[Link](reverse = True)
print(thislist)
Example
Sort the list descending:
thislist = [100, 50, 65, 82, 23]
[Link](reverse = True)
print(thislist)
Customize Sort Function
You can also customize your own function by using the keyword argument key = function.
The function will return a number that will be used to sort the list (the lowest number first):
Example
Sort the list based on how close the number is to 50:
def myfunc(n):
return abs(n - 50)
Reverse Order
What if you want to reverse the order of a list, regardless of the alphabet?
The reverse() method reverses the current sorting order of the elements.
Example
Reverse the order of the list items:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
[Link]()
print(thislist)
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only be
a reference to list1, and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
ExampleMake a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = [Link]()
print(mylist)
Another way to make a copy is to use the built-in method list().
Example
Make a copy of a list with the list() method:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
Join Two Lists
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
ExampleJoin two list:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
for x in list2:
[Link](x)
print(list1)
Or you can use the extend() method, where the purpose is to add elements from one list to
another list:
Example
Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
[Link](list2)
print(list1)
Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple Items
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.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that
order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple
has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuples allow duplicate values:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Multiply Tuples
If you want to multiply the content of a tuple a given number of times, you can use
the * operator:
Example
Multiply the fruits tuple by 2:
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
index() Searches the tuple for a specified value and returns the position of where
it was found
Set
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.
A set is a collection which is unordered, unchangeable*, and unindexed.
* Note: Set items are unchangeable, but you can remove items and add new items.
Sets are written with curly brackets.
ExampleCreate a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to
by index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been
created.
Once a set is created, you cannot change its items, but you can remove items and add new
items.
Duplicates Not Allowed
Sets cannot have two items with the same value.
Example
Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
Example
True and 1 is considered the same value:
thisset = {"apple", "banana", "cherry", True, 1, 2}
Example
False and 0 is considered the same value:
thisset = {"apple", "banana", "cherry", False, True, 0}
print(thisset)
print(len(thisset))
type()
From Python's perspective, sets are defined as objects with the data type 'set':
<class 'set'>
Example
What is the data type of a set?
myset = {"apple", "banana", "cherry"}
print(type(myset))
x.intersection_update(y)
print(x)
The intersection() method will return a new set, that only contains the items that are present
in both sets.
Example
Return a set that contains the items that exist in both set x, and set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = [Link](y)
print(z)
x.symmetric_difference_update(y)
print(x)
The symmetric_difference() method will return a new set, that contains only the elements that
are NOT present in both sets.
Example
Return a set that contains all items from both sets, except items that are present in both:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)
Example
True and 1 is considered the same value:
x = {"apple", "banana", "cherry", True}
y = {"google", 1, "apple", 2}
z = x.symmetric_difference(y)
print(z)
Set Methods
Python has a set of built-in methods that you can use on sets.
Method Description
add() Adds an element to the set
difference_update() Removes the items in this set that are also included in
another, specified set
intersection_update() Removes the items in this set that are not present in
other, specified set(s)
update() Update the set with the union of this set and others
Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
Dictionaries are written with curly brackets, and have keys and values:
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.
Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
Dictionary Length
To determine how many items a dictionary has, use the len() function:
Example
Print the number of items in the dictionary:
print(len(thisdict))
type()
From Python's perspective, dictionaries are defined as objects with the data type 'dict':
<class 'dict'>
Example
Print the data type of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
Update Dictionary
The update() method will update the dictionary with the items from a given argument. If the
item does not exist, the item will be added.
The argument must be a dictionary, or an iterable object with key:value pairs.
Example
Add a color item to the dictionary by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"color": "red"})
Removing Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]("model")
print(thisdict)
Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item
is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
Example
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Example
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.
Example
The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but there
are methods to return the values as well.
Example
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Example
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
Example
You can also use the values() method to return values of a dictionary:
for x in [Link]():
print(x)
Example
You can use the keys() method to return the keys of a dictionary:
for x in [Link]():
print(x)
Example
Loop through both keys and values, by using the items() method:
for x, y in [Link]():
print(x, y)
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be
a reference to dict1, and changes made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = [Link]()
print(mydict)
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the
key, with the specified value
Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are 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 change the normal flow of the program.
Different types of exceptions in python:
In Python, there are several built-in Python exceptions that can be raised when an error
occurs during the execution of a program. Here are some of the most common types of
exceptions in Python:
SyntaxError: This exception is raised when the interpreter encounters a syntax error
in the code, such as a misspelled keyword, a missing colon, or an unbalanced
parenthesis.
TypeError: This exception is raised when an operation or function is applied to an
object of the wrong type, such as adding a string to an integer.
NameError: This exception is raised when a variable or function name is not found
in the current scope.
IndexError: This exception is raised when an index is out of range for a list, tuple, or
other sequence types.
KeyError: This exception is raised when a key is not found in a dictionary.
ValueError: This exception is raised when a function or method is called with an
invalid argument or input, such as trying to convert a string to an integer when the
string does not represent a valid integer.
AttributeError: This exception is raised when an attribute or method is not found on
an object, such as trying to access a non-existent attribute of a class instance.
IOError: This exception is raised when an I/O operation, such as reading or writing a
file, fails due to an input/output error.
ZeroDivisionError: This exception is raised when an attempt is made to divide a
number by zero.
ImportError: This exception is raised when an import statement fails to find or load
a module.
These are just a few examples of the many types of exceptions that can occur in Python. It’s
important to handle exceptions properly in your code using try-except blocks or other error-
handling techniques, in order to gracefully handle errors and prevent the program from
crashing.
Difference between Syntax Error and Exceptions
Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It
leads to the termination of the program.
Example:
There is a syntax error in the code . The ‘if' statement should be followed by a colon (:), and
the ‘print' statement should be indented to be inside the ‘if' block.
Python3
amount = 10000
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")
Output:
Exceptions: Exceptions are raised when the program is syntactically correct, but the code
results in an error. This error does not stop the execution of the program, however, it changes
the normal flow of the program.
Example:
Here in this code a s we are dividing the ‘marks’ by zero so a error will occur known
as ‘ZeroDivisionError’
Python3
marks = 10000
a = marks / 0
print(a)
Output:
In the above example raised the ZeroDivisionError as we are trying to divide a number by 0.
Note: Exception is the base class for all the exceptions in Python. You can check the
exception hierarchy here.
Example:
1) TypeError: This exception is raised when an operation or function is applied to an object
of the wrong type. Here’s an example:
Here a ‘TypeError’ is raised as both the datatypes are different which are being added.
Python3
x=5
y = "hello"
z=x+y
output:
Traceback (most recent call last):
File "[Link]", line 4, in <module>
z=x+y
TypeError: unsupported operand type(s) for +: 'int' and 'str'
try catch block to resolve it:
The code attempts to add an integer (‘x') and a string (‘y') together, which is not a valid
operation, and it will raise a ‘TypeError'. The code used a ‘try' and ‘except' block to catch
this exception and print an error message.
Python3
x=5
y = "hello"
try:
z=x+y
except TypeError:
print("Error: cannot add an int and a str")
Output
Error: cannot add an int and a str
Try and Except Statement – Catching Exceptions
Try and except statements are used to catch and handle exceptions in Python. Statements that
can raise exceptions are kept inside the try clause and the statements that handle the
exception are written inside except clause.
Example: Here we are trying to access the array element whose index is out of bound and
handle the corresponding exception.
Python3
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
except:
print ("An error occurred")
Output
Second element = 2
An error occurred
In the above example, the statements that can cause the error are placed inside the try
statement (second print statement in our case). The second print statement tries to access the
fourth element of the list which is not there and this throws an exception. This exception is
then caught by the except statement.
Catching Specific Exception
A try statement can have more than one except clause, to specify handlers for different
exceptions. Please note that at most one handler will be executed. For example, we can add
IndexError in the above code. The general syntax for adding specific exceptions are –
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Example: Catching specific exceptions in the Python
The code defines a function ‘fun(a)' that calculates b based on the input a. If a is less than 4,
it attempts a division by zero, causing a ‘ZeroDivisionError'. The code
calls fun(3) and fun(5) inside a try-except block. It handles
the ZeroDivisionError for fun(3) and prints “ZeroDivisionError Occurred and
Handled.” The ‘NameError' block is not executed since there are
no ‘NameError' exceptions in the code.
Python3
def fun(a):
if a < 4:
b = a/(a-3)
print("Value of b = ", b)
try:
fun(3)
fun(5)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
Output
ZeroDivisionError Occurred and Handled
If you comment on the line fun(3), the output will be
NameError Occurred and Handled
The output above is so because as soon as python tries to access the value of b, NameError
occurs.
Try with Else Clause
In Python, you can also use the else clause on the try-except block which must be present
after all the except clauses. The code enters the else block only if the try clause does not raise
an exception.
Try with else clause
The code defines a function AbyB(a, b) that calculates c as ((a+b) / (a-b)) and handles a
potential ZeroDivisionError. It prints the result if there’s no division by zero error.
Calling AbyB(2.0, 3.0) calculates and prints -5.0, while calling AbyB(3.0, 3.0) attempts to
divide by zero, resulting in a ZeroDivisionError, which is caught and “a/b results in 0” is
printed.
Python3
Output:
-5.0
a/b result in 0
Finally Keyword in Python
Python provides a keyword finally, which is always executed after the try and except blocks.
The final block always executes after the normal termination of the try block or after the try
block terminates due to some exception.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
Example:
The code attempts to perform integer division by zero, resulting in a ZeroDivisionError. It
catches the exception and prints “Can’t divide by zero.” Regardless of the exception,
the finally block is executed and prints “This is always executed.”
Python3
try:
k = 5//0
print(k)
except ZeroDivisionError:
print("Can't divide by zero")
finally:
print('This is always executed')
Output:
Can't divide by zero
This is always executed
Raising Exception
The raise statement allows the programmer to force a specific exception to occur. The sole
argument in raise indicates the exception to be raised. This must be either an exception
instance or an exception class (a class that derives from Exception).
This code intentionally raises a NameError with the message “Hi there” using
the raise statement within a try block. Then, it catches the NameError exception, prints “An
exception,” and re-raises the same exception using raise. This demonstrates how exceptions
can be raised and handled in Python, allowing for custom error messages and further
exception propagation.
Python3
try:
raise NameError("Hi there")
except NameError:
print ("An exception")
raise
The output of the above code will simply line printed as “An exception” but a Runtime error
will also occur in the last due to the raise statement in the last line. So, the output on your
command line will look like
Traceback (most recent call last):
File "/home/[Link]", line 5, in <module>
raise NameError("Hi there") # Raise Error
NameError: Hi there
Advantages of Exception Handling:
Improved program reliability: By handling exceptions properly, you can prevent
your program from crashing or producing incorrect results due to unexpected errors or
input.
Simplified error handling: Exception handling allows you to separate error handling
code from the main program logic, making it easier to read and maintain your code.
Cleaner code: With exception handling, you can avoid using complex conditional
statements to check for errors, leading to cleaner and more readable code.
Easier debugging: When an exception is raised, the Python interpreter prints a
traceback that shows the exact location where the exception occurred, making it easier
to debug your code.
Disadvantages of Exception Handling:
Performance overhead: Exception handling can be slower than using conditional
statements to check for errors, as the interpreter has to perform additional work to
catch and handle the exception.
Increased code complexity: Exception handling can make your code more complex,
especially if you have to handle multiple types of exceptions or implement complex
error handling logic.
Possible security risks: Improperly handled exceptions can potentially reveal
sensitive information or create security vulnerabilities in your code, so it’s important
to handle exceptions carefully and avoid exposing too much information about your
program.
Overall, the benefits of exception handling in Python outweigh the drawbacks, but it’s
important to use it judiciously and carefully in order to maintain code quality and program
reliability.
All instances in Python must be instances of a class that derives from BaseException. Two
exception classes that are not related via subclassing are never equivalent, even if they have
the same name. The built-in exceptions can be generated by the interpreter or built-in
functions.
There are several built-in exceptions in Python that are raised when errors occur. These built-
in exceptions can be viewed using the local() built-in functions as follows :
>>> locals()['__builtins__']
This returns a dictionary of built-in exceptions, functions and attributes.
Base Classes
The following exceptions are used mostly as base classes for other exceptions.
1. exception BaseException
This is the base class for all built-in exceptions. It is not meant to be directly inherited
by user-defined classes. For, user-defined classes, Exception is used. This class is
responsible for creating a string representation of the exception using str() using the
arguments passed. An empty string is returned if there are no arguments.
args : The args are the tuple of arguments given to the exception constructor.
with_traceback(tb) : This method is usually used in exception handling. This
method sets tb as the new traceback for the exception and returns the
exception object.
Code :
try:
...
except SomeException:
tb = sys.exc_info()[2]
raise OtherException(...).with_traceback(tb)
2. exception Exception
This is the base class for all built-in non-system-exiting exceptions. All user-defined
exceptions should also be derived from this class.
3. exception ArithmeticError
This class is the base class for those built-in exceptions that are raised for various
arithmetic errors such as :
OverflowError
ZeroDivisionError
FloatingPointError
Example :
try:
a = 10/0
print (a)
except ArithmeticError:
print ("This statement is raising an arithmetic exception.")
else:
print ("Success.")
Output :
This statement is raising an arithmetic exception.
4. exception BufferError
This exception is raised when buffer related operations cannot be performed.
5. exception LookupError
This is the base class for those exceptions that are raised when a key or index used on
a mapping or sequence is invalid or not found. The exceptions raised are :
KeyError
IndexError
Example :
try:
a = [1, 2, 3]
print (a[3])
except LookupError:
print ("Index out of bound error.")
else:
print ("Success")
Output :
Index out of bound error.
Concrete exceptions
The following exceptions are the exceptions that are usually raised.
1. exception AssertionError
An AssertionError is raised when an assert statement fails.
Example :
assert False, 'The assertion failed'
Output :
Traceback (most recent call last):
File "exceptions_AssertionError.py", line 12, in
assert False, 'The assertion failed'
AssertionError: The assertion failed
2. exception AttributeError
An AttributeError is raised when an attribute reference or assignment fails such as
when a non-existent attribute is referenced.
Example :
class Attributes(object):
pass
object = Attributes()
print ([Link])
Output :
Traceback (most recent call last):
File "[Link]", line 5, in
print [Link]
AttributeError: 'Attributes' object has no attribute 'attribute'
3. exception EOFError
An EOFError is raised when built-in functions like input() hits an end-of-file
condition (EOF) without reading any data. The file methods like readline() return an
empty string when they hit EOF.
Example :
while True:
data = input('Enter name : ')
print ('Hello ', data)
Output :
Enter Name :Hello Aditi
Enter Name :Traceback (most recent call last):
File "exceptions_EOFError.py", line 13, in
data = raw_input('Enter name :')
EOFError: EOF when reading a line
4. exception FloatingPointError
A FloatingPointError is raised when a floating point operation fails. This exception is
always defined, but can only be raised when Python is configured with the–with-
fpectl option, or the WANT_SIGFPE_HANDLER symbol is defined in the
pyconfig.h file.
Example :
import math
print ([Link](1000))
Output :
Traceback (most recent call last):
File "", line 1, in
FloatingPointError: in math_1
5. exception GeneratorExit
This exception directly inherits from BaseException instead of Exception since it is
technically not an error. A GeneratorExit exception is raised when a generator or
coroutine is closed.
Example :
def my_generator():
try:
for i in range(5):
print ('Yielding', i)
yield i
except GeneratorExit:
print ('Exiting early')
g = my_generator()
print ([Link]())
[Link]()
Output :
Yielding 0
0
Exiting early
6. exception ImportError
An ImportError is raised when the import statement is unable to load a module or
when the “from list” in from … import has a name that cannot be found.
Example :
import module_does_not_exist
Output :
Traceback (most recent call last):
File "exceptions_ImportError_nomodule.py", line 12, in
import module_does_not_exist
ImportError: No module named module_does_not_exist
Example :
Output :
Traceback (most recent call last):
File "exceptions_ImportError_missingname.py", line 12, in
from exceptions import Userexception
ImportError: cannot import name Userexception
7. exception ModuleNotFoundError
This is the subclass of ImportError which is raised by import when a module could
not be found. It is also raised when None is found in [Link].
8. exception IndexError
An IndexError is raised when a sequence is referenced which is out of range.
Example :
array = [ 0, 1, 2 ]
print (array[3])
Output :
Traceback (most recent call last):
File "exceptions_IndexError.py", line 13, in
print array[3]
IndexError: list index out of range
9. exception KeyError
A KeyError is raised when a mapping key is not found in the set of existing keys.
Example :
Output :
Traceback (most recent call last):
File "exceptions_KeyError.py", line 13, in
print array['c']
KeyError: 'c'
10. exception KeyboardInterrupt
This error is raised when the user hits the interrupt key such as Control-C or Delete.
Example :
try:
print ('Press Return or Ctrl-C:',)
ignored = input()
except Exception, err:
print ('Caught exception:', err)
except KeyboardInterrupt, err:
print ('Caught KeyboardInterrupt')
else:
print ('No exception')
Output :
Press Return or Ctrl-C: ^CCaught KeyboardInterrupt
11. exception MemoryError
This error is raised when an operation runs out of memory.
Example :
def fact(a):
factors = []
for i in range(1, a+1):
if a%i == 0:
[Link](i)
return factors
num = 600851475143
print (fact(num))
Output :
Traceback (most recent call last):
File "[Link]", line 9, in
print fact(num)
File "[Link]", line 3, in fact
for i in range(1, a+1):
MemoryError
12. exception NameError
This error is raised when a local or global name is not found. For example, an
unqualified variable name.
Example :
def func():
print ans
func()
Output :
Traceback (most recent call last):
File "[Link]", line 4, in
func()
File "[Link]", line 2, in func
print ans
NameError: global name 'ans' is not defined
13. exception NotImplementedError
This exception is derived from RuntimeError. Abstract methods in user defined
classed should raise this exception when the derived classes override the method.
Example :
class BaseClass(object):
"""Defines the interface"""
def __init__(self):
super(BaseClass, self).__init__()
def do_something(self):
"""The interface, not implemented"""
raise NotImplementedError(self.__class__.__name__ + '.do_something')
class SubClass(BaseClass):
"""Implements the interface"""
def do_something(self):
"""really does something"""
print (self.__class__.__name__ + ' doing something!')
SubClass().do_something()
BaseClass().do_something()
Output :
Traceback (most recent call last):
File "[Link]", line 16, in
BaseClass().do_something()
File "[Link]", line 7, in do_something
raise NotImplementedError(self.__class__.__name__ + '.do_something')
NotImplementedError: BaseClass.do_something
14. exception OSError([arg])
The OSError exception is raised when a system function returns a system-related
error, including I/O failures such as “file not found” or “disk full” errors.
Example :
def func():
print (ans)
func()
Output :
Traceback (most recent call last):
File "[Link]", line 4, in
print i, [Link](i)
OSError: [Errno 25] Inappropriate ioctl for device
15. exception OverflowError
The OverflowError is raised when the result of an arithmetic operation is out of range.
Integers raise MemoryError instead of OverflowError. OverflowError is sometimes
raised for integers that are outside a required range. Floating point operations are not
checked because of the lack of standardization of floating point exception handling in
C.
Example :
import sys
print()
print ('Long integer:')
for i in range(0, 100, 10):
print ('%2d' % i, 2L ** i)
print()
print ('Floating point values:')
try:
f = 2.0**i
for i in range(100):
print (i, f)
f = f ** 2
except OverflowError, err:
print ('Overflowed after ', f, err)
Output :
Regular integer: (maxint=9223372036854775807)
No overflow for i = 27670116110564327421
Long integer:
01
10 1024
20 1048576
30 1073741824
40 1099511627776
50 1125899906842624
60 1152921504606846976
70 1180591620717411303424
80 1208925819614629174706176
90 1237940039285380274899124224
import gc
import weakref
class Foo(object):
def __del__(self):
print ('(Deleting %s)' % self)
obj = Foo('obj')
p = [Link](obj)
Output :
BEFORE: obj
(Deleting )
AFTER:
print (i)
print ([Link]())
print ([Link]())
print ([Link]())
print ([Link]())
Output :
3
1
2
try:
print (eval('geeks for geeks'))
except SyntaxError, err:
print ('Syntax error %s (%s-%s): %s' % \
([Link], [Link], [Link], [Link]))
print (err)
Output :
Syntax error (1-9): geeks for geeks
invalid syntax (, line 1)
21. exception SystemError
The SystemError is raised when the interpreter finds an internal error. The associated
value is a string indicating what went wrong.
22. exception SystemExit
The SystemExit is raised when [Link]() function is called. A call to [Link]() is
translated into an exception to execute clean-up handlers (finally clauses of try
statements) and to debug a script without running the risk of losing control.
23. exception TypeError
TypeError is raised when an operation or function is applied to an object of
inappropriate type. This exception returns a string giving details about the type
mismatch.
Example :
arr = ('tuple', ) + 'string'
print (arr)
Output :
Traceback (most recent call last):
File "[Link]", line 1, in
arr = ('tuple', ) + 'string'
TypeError: can only concatenate tuple (not "str") to tuple
24. exception UnboundLocalError
UnboundLocalError is a subclass of NameError which is raised when a reference is
made to a local variable in a function or method, but no value has been assigned to
that variable.
Example :
def global_name_error():
print (unknown_global_name)
def unbound_local():
local_val = local_val + 1
print (local_val)
try:
global_name_error()
except NameError, err:
print ('Global name error:', err)
try:
unbound_local()
except UnboundLocalError, err:
print ('Local name error:', err)
Output :
Global name error: global name 'unknown_global_name' is not defined
Local name error: local variable 'local_val' referenced before assignment
25. exception UnicodeError
This exception is a subclass of ValueError. UnicodeError is raised when a Unicode-
related encoding or decoding error occurs.
26. exception ValueError
A ValueError is raised when a built-in operation or function receives an argument that
has the right type but an invalid value.
Example :
print (int('a'))
Output :
Traceback (most recent call last):
File "[Link]", line 1, in
print int('a')
ValueError: invalid literal for int() with base 10: 'a'
27. exception ZeroDivisionError
A ZeroDivisionError is raised when the second argument of a division or modulo
operation is zero. This exception returns a string indicating the type of the operands
and the operation.
Example :
print (1/0)
Output :
Traceback (most recent call last):
File "[Link]", line 1, in
print 1/0
ZeroDivisionError: integer division or modulo by zero
Python throws errors and exceptions whenever code behaves abnormally & its execution stop
abruptly. Python provides us tools to handle such scenarios by the help of exception handling
method using try-except statements. Some standard exceptions which are found are include
ArithmeticError, AssertionError, AttributeError, ImportError, etc.
Creating a User-defined Exception class
Here we created a new exception class i.e. User_Error. Exceptions need to be derived from
the built-in Exception class, either directly or indirectly. Let’s look at the given example
which contains a constructor and display method within the given class.
Example
# class MyError is extended from super class Exception
class User_Error(Exception):
# Constructor method
def __init__(self, value):
[Link] = value
# __str__ display function
def __str__(self):
return(repr([Link]))
try:
raise(User_Error("User defined error"))
# Value of Exception is stored in error
except User_Error as error:
print('A New Exception occured:',[Link])
Output
A New Exception occured: User defined error
Creating a User-defined Exception class (Multiple Inheritance)
Derived class Exceptions are created when a single module handles multiple several distinct
errors. Here we created a base class for exceptions defined by that module. This base class is
inherited by various user-defined class to handle different types of errors.
Example
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class Dividebyzero(Error):
"""Raised when the input value is zero"""
pass
try:
i_num = int(input("Enter a number: "))
if i_num ==0:
raise Dividebyzero
except Dividebyzero:
print("Input value is zero, try again!")
print()
Output
Enter a number: Input value is zero, try again!
Creating a User-defined Exception class (standard Exceptions)
Runtime error is a built-in class which is raised whenever a generated error does not fall into
mentioned categories. The program below explains how to use runtime error as base class
and user-defined error as derived class.
Example
# User defined error
class Usererror(RuntimeError):
def __init__(self, arg):
[Link] = arg
try:
raise Usererror("userError")
except Usererror as e:
print ([Link])
Output
('u', 's', 'e', 'r', 'E', 'r', 'r', 'o', 'r')
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
Let’s create a simple [Link] in which we define two functions, one add and
another subtract.
Python3
print([Link](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.
Python3
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.
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 [Link]. 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, [Link] is a built-in variable within the sys module. It contains a list of directories that
the interpreter will search for the required module.
Python3
# importing [Link]
print([Link])
Output:
[‘/home/nikhil/Desktop/gfg’, ‘/usr/lib/[Link]’, ‘/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
Python3
# 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.
Python3
# Sine of 2 radians
print([Link](2))
# 1 * 2 * 3 * 4 = 24
print([Link](4))
# importing built in module random
import random
Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87
Modular programming refers to the process of breaking a large, unwieldy programming
task into separate, smaller, more manageable subtasks or modules. Individual modules can
then be cobbled together like building blocks to create a larger application.
There are several advantages to modularizing code in a large application:
Simplicity: Rather than focusing on the entire problem at hand, a module typically
focuses on one relatively small portion of the problem. If you’re working on a single
module, you’ll have a smaller problem domain to wrap your head around. This makes
development easier and less error-prone.
Maintainability: Modules are typically designed so that they enforce logical
boundaries between different problem domains. If modules are written in a way that
minimizes interdependency, there is decreased likelihood that modifications to a
single module will have an impact on other parts of the program. (You may even be
able to make changes to a module without having any knowledge of the application
outside that module.) This makes it more viable for a team of many programmers to
work collaboratively on a large application.
Reusability: Functionality defined in a single module can be easily reused (through
an appropriately defined interface) by other parts of the application. This eliminates
the need to duplicate code.
Scoping: Modules typically define a separate namespace, which helps avoid
collisions between identifiers in different areas of a program. (One of the tenets in
the Zen of Python is Namespaces are one honking great idea—let’s do more of
those!)
Functions, modules and packages are all constructs in Python that promote code
modularization.
Free PDF Download: Python 3 Cheat Sheet
Python Modules: Overview
There are actually three different ways to define a module in Python:
1. A module can be written in Python itself.
2. A module can be written in C and loaded dynamically at run-time, like the re (regular
expression) module.
3. A built-in module is intrinsically contained in the interpreter, like
the itertools module.
A module’s contents are accessed the same way in all three cases: with the import statement.
Here, the focus will mostly be on modules that are written in Python. The cool thing about
modules written in Python is that they are exceedingly straightforward to build. All you need
to do is create a file that contains legitimate Python code and then give the file a name with
a .py extension. That’s it! No special syntax is necessary.
For example, suppose you have created a file called [Link] containing the following:
[Link]
Python
s = "If Comrade Napoleon says it, it must be right."
a = [100, 200, 300]
def foo(arg):
print(f'arg = {arg}')
class Foo:
pass
Several objects are defined in [Link]:
s (a string)
a (a list)
foo() (a function)
Foo (a class)
Assuming [Link] is in an appropriate location, which you will learn more about shortly,
these objects can be accessed by importing the module as follows:
Python
>>> import mod
>>> print(mod.s)
If Comrade Napoleon says it, it must be right.
>>> mod.a
[100, 200, 300]
>>> [Link](['quux', 'corge', 'grault'])
arg = ['quux', 'corge', 'grault']
>>> x = [Link]()
>>> x
<[Link] object at 0x03C181F0>
>>> import re
>>> re.__file__
'C:\\Python36\\lib\\[Link]'
The directory portion of __file__ should be one of the directories in [Link].
The import Statement
Module contents are made available to the caller with the import statement.
The import statement takes many different forms, shown below.
import <module_name>
The simplest form is the one already shown above:
Python
import <module_name>
Note that this does not make the module contents directly accessible to the caller. Each
module has its own private symbol table, which serves as the global symbol table for all
objects defined in the module. Thus, a module creates a separate namespace, as already
noted.
The statement import <module_name> only places <module_name> in the caller’s symbol
table. The objects that are defined in the module remain in the module’s private symbol table.
From the caller, objects in the module are only accessible when prefixed
with <module_name> via dot notation, as illustrated below.
After the following import statement, mod is placed into the local symbol table.
Thus, mod has meaning in the caller’s local context:
Python
>>> import mod
>>> mod
<module 'mod' from 'C:\\Users\\john\\Documents\\Python\\doc\\[Link]'>
But s and foo remain in the module’s private symbol table and are not meaningful in the local
context:
Python
>>> s
NameError: name 's' is not defined
>>> foo('quux')
NameError: name 'foo' is not defined
To be accessed in the local context, names of objects defined in the module must be prefixed
by mod:
Python
>>> mod.s
'If Comrade Napoleon says it, it must be right.'
>>> [Link]('quux')
arg = quux
Several comma-separated modules may be specified in a single import statement:
Python
import <module_name>[, <module_name> ...]
>>> bar()
arg = corge
However, Python 3 does not allow the indiscriminate import * syntax from within a function:
Python
>>> def bar():
... from mod import *
...
SyntaxError: import * only allowed at module level
Lastly, a try statement with an except ImportError clause can be used to guard against
unsuccessful import attempts:
Python
>>> try:
... # Non-existent module
... import baz
... except ImportError:
... print('Module not found')
...
def foo(arg):
print(f'arg = {arg}')
class Foo:
pass
This can be run as a script:
Windows Command Prompt
C:\Users\john\Documents>python [Link]
C:\Users\john\Documents>
There are no errors, so it apparently worked. Granted, it’s not very interesting. As it is
written, it only defines objects. It doesn’t do anything with them, and it doesn’t generate any
output.
Let’s modify the above Python module so it does generate some output when run as a script:
[Link]
Python
s = "If Comrade Napoleon says it, it must be right."
a = [100, 200, 300]
def foo(arg):
print(f'arg = {arg}')
class Foo:
pass
print(s)
print(a)
foo('quux')
x = Foo()
print(x)
Now it should be a little more interesting:
Windows Command Prompt
C:\Users\john\Documents>python [Link]
If Comrade Napoleon says it, it must be right.
[100, 200, 300]
arg = quux
<__main__.Foo object at 0x02F101D0>
Unfortunately, now it also generates output when imported as a module:
Python
>>> import mod
If Comrade Napoleon says it, it must be right.
[100, 200, 300]
arg = quux
<[Link] object at 0x0169AD50>
This is probably not what you want. It isn’t usual for a module to generate output when it is
imported.
Wouldn’t it be nice if you could distinguish between when the file is loaded as a module and
when it is run as a standalone script?
Ask and ye shall receive.
When a .py file is imported as a module, Python sets the
special dunder variable __name__ to the name of the module. However, if a file is run as a
standalone script, __name__ is (creatively) set to the string '__main__'. Using this fact, you
can discern which is the case at run-time and alter behavior accordingly:
[Link]
Python
s = "If Comrade Napoleon says it, it must be right."
a = [100, 200, 300]
def foo(arg):
print(f'arg = {arg}')
class Foo:
pass
if (__name__ == '__main__'):
print('Executing as standalone script')
print(s)
print(a)
foo('quux')
x = Foo()
print(x)
Now, if you run as a script, you get output:
Windows Command Prompt
C:\Users\john\Documents>python [Link]
Executing as standalone script
If Comrade Napoleon says it, it must be right.
[100, 200, 300]
arg = quux
<__main__.Foo object at 0x03450690>
But if you import as a module, you don’t:
Python
>>> import mod
>>> [Link]('grault')
arg = grault
Modules are often designed with the capability to run as a standalone script for purposes of
testing the functionality that is contained within the module. This is referred to as unit
testing. For example, suppose you have created a module [Link] containing
a factorial function, as follows:
[Link]
Python
def fact(n):
return 1 if n == 1 else n * fact(n-1)
if (__name__ == '__main__'):
import sys
if len([Link]) > 1:
print(fact(int([Link][1])))
The file can be treated as a module, and the fact() function imported:
Python
>>> from fact import fact
>>> fact(6)
720
But it can also be run as a standalone by passing an integer argument on the command-line
for testing:
Windows Command Prompt
C:\Users\john\Documents>python [Link] 6
720
Reloading a Module
For reasons of efficiency, a module is only loaded once per interpreter session. That is fine
for function and class definitions, which typically make up the bulk of a module’s contents.
But a module can contain executable statements as well, usually for initialization. Be aware
that these statements will only be executed the first time a module is imported.
Consider the following file [Link]:
[Link]
Python
a = [100, 200, 300]
print('a =', a)
Python
>>> import mod
a = [100, 200, 300]
>>> import mod
>>> import mod
>>> mod.a
[100, 200, 300]
The print() statement is not executed on subsequent imports. (For that matter, neither is the
assignment statement, but as the final display of the value of mod.a shows, that doesn’t
matter. Once the assignment is made, it sticks.)
If you make a change to a module and need to reload it, you need to either restart the
interpreter or use a function called reload() from module importlib:
Python
>>> import mod
a = [100, 200, 300]
Here, there is a directory named pkg that contains two modules, [Link] and [Link]. The
contents of the modules are:
[Link]
Python
def foo():
print('[mod1] foo()')
class Foo:
pass
[Link]
Python
def bar():
print('[mod2] bar()')
class Bar:
pass
Given this structure, if the pkg directory resides in a location where it can be found (in one of
the directories contained in [Link]), you can refer to the two modules with dot
notation (pkg.mod1, pkg.mod2) and import them with the syntax you are already familiar
with:
Python
import <module_name>[, <module_name> ...]
Python
>>> import pkg.mod1, pkg.mod2
>>> [Link]()
[mod1] foo()
>>> x = [Link]()
>>> x
<[Link] object at 0x033F7290>
Python
from <module_name> import <name(s)>
Python
>>> from pkg.mod1 import foo
>>> foo()
[mod1] foo()
Python
from <module_name> import <name> as <alt_name>
Python
>>> from pkg.mod2 import Bar as Qux
>>> x = Qux()
>>> x
<[Link] object at 0x036DFFD0>
You can import modules with these statements as well:
Python
from <package_name> import <modules_name>[, <module_name> ...]
from <package_name> import <module_name> as <alt_name>
Python
>>> from pkg import mod1
>>> [Link]()
[mod1] foo()
class Foo:
pass
Python
>>> from pkg import mod1
Invoking __init__.py for pkg
>>> [Link]()
[mod1] foo() / A = ['quux', 'corge', 'grault']
__init__.py can also be used to effect automatic importing of modules from a package. For
example, earlier you saw that the statement import pkg only places the name pkg in the
caller’s local symbol table and doesn’t import any modules. But if __init__.py in
the pkg directory contains the following:
__init__.py
Python
print(f'Invoking __init__.py for {__name__}')
import pkg.mod1, pkg.mod2
then when you execute import pkg, modules mod1 and mod2 are imported automatically:
Python
>>> import pkg
Invoking __init__.py for pkg
>>> [Link]()
[mod1] foo()
>>> [Link]()
[mod2] bar()
[Link]
Python
def foo():
print('[mod1] foo()')
class Foo:
pass
[Link]
Python
def bar():
print('[mod2] bar()')
class Bar:
pass
[Link]
Python
def baz():
print('[mod3] baz()')
class Baz:
pass
[Link]
Python
def qux():
print('[mod4] qux()')
class Qux:
pass
(Imaginative, aren’t they?)
You have already seen that when import * is used for a module, all objects from the module
are imported into the local symbol table, except those whose names begin with an underscore,
as always:
Python
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__']
>>> from pkg.mod3 import *
>>> dir()
['Baz', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__', 'baz']
>>> baz()
[mod3] baz()
>>> Baz
<class '[Link]'>
The analogous statement for a package is this:
Python
from <package_name> import *
What does that do?
Python
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__']
def foo():
print('[mod1] foo()')
class Foo:
pass
Now an import * statement from pkg.mod1 will only import what is contained in __all__:
Python
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__']
>>> foo()
[mod1] foo()
>>> Foo
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
Foo
NameError: name 'Foo' is not defined
foo() (the function) is now defined in the local namespace, but Foo (the class) is not, because
the latter is not in __all__.
Subpackages
Packages can contain nested subpackages to arbitrary depth. For example, let’s make one
more modification to the example package directory as follows:
The four modules ([Link], [Link], [Link] and [Link]) are defined as previously. But
now, instead of being lumped together into the pkg directory, they are split out into
two subpackage directories, sub_pkg1 and sub_pkg2.
Importing still works the same as shown previously. Syntax is similar, but additional dot
notation is used to separate package name from subpackage name:
Python
>>> import pkg.sub_pkg1.mod1
>>> pkg.sub_pkg1.[Link]()
[mod1] foo()
class Baz:
pass