0% found this document useful (0 votes)
3 views70 pages

Unti II-python

PYHTON

Uploaded by

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

Unti II-python

PYHTON

Uploaded by

b.comcasvcas
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Strings

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)

Strings are Arrays


Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.
However, Python does not have a character data type, a single character is simply a string
with a length of 1.
Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(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])

Slice From the Start


By leaving out the start index, the range will start at the first character:
Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])

Slice To the End


By leaving out the end index, the range will go to the end:
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2])
python has a set of built-in methods that you can use on strings.

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

\' Single Quote

\\ Backslash

\n New Line

\r Carriage Return

\t Tab

\b Backspace

\f Form Feed

\ooo Octal value

\xhh Hex value

String Methods
Python has a set of built-in methods that you can use on strings.
Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string


endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the position
of where it was found

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the position
of where it was found

isalnum() Returns True if all characters in the string are alphanumeric

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

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string


ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a


specified value

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

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case


translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the


beginning

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

Check if Item Exists


To determine if a specified item is present in a list use the in keyword:
Example
Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Change Item Value
To change the value of a specific item, refer to the index number:
Example
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)

Change a Range of Item Values


To change the value of items within a specific range, define a list with the new values, and
refer to the range of index numbers where you want to insert the new values:
Example
Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
Example
Change the second value by replacing it with two new values:
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
Example
Change the second and third value by replacing it with one value:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
Insert Items
To insert a new list item, without replacing any of the existing values, we can use
the insert() method.
The insert() method inserts an item at the specified index:
Example
Insert "watermelon" as the third item:
thislist = ["apple", "banana", "cherry"]
[Link](2, "watermelon")
print(thislist)
Append Items
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
[Link]("orange")
print(thislist)
Insert Items
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index:
Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
[Link](1, "orange")
print(thislist)

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.

Add Any Iterable


The extend() method does not have to append lists, you can add any iterable object (tuples,
sets, dictionaries etc.).
Example
Add elements of a tuple to a list:
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
[Link](thistuple)
print(thislist)
Remove Specified Item
The remove() method removes the specified item.
Example
Remove "banana":
thislist = ["apple", "banana", "cherry"]
[Link]("banana")
print(thislist)
If there are more than one item with the specified value, the remove() method removes the
first occurance:
Example
Remove the first occurance of "banana":
thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
[Link]("banana")
print(thislist)

Remove Specified Index


The pop() method removes the specified index.
Example
Remove the second item:
thislist = ["apple", "banana", "cherry"]
[Link](1)
print(thislist)
If you do not specify the index, the pop() method removes the last item.
Example
Remove the last item:
thislist = ["apple", "banana", "cherry"]
[Link]()
print(thislist)
The del keyword also removes the specified index:
Example
Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
The del keyword can also delete the list completely.
Example
Delete the entire list:
thislist = ["apple", "banana", "cherry"]
del thislist
Clear the List
The clear() method empties the list.
The list still remains, but it has no content.
Example
Clear the list content:
thislist = ["apple", "banana", "cherry"]
[Link]()
print(thislist)
Loop Through a List
You can loop through the list items by using a for loop:
Example
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
Python For Loops
Loop Through the Index Numbers
You can also loop through the list items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.
Example
Print all items by referring to their index number:
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
The iterable created in the example above is [0, 1, 2].

Using a While Loop


You can loop through the list items by using a while loop.
Use the len() function to determine the length of the list, then start at 0 and loop your way
through the list items by referring to their indexes.
Remember to increase the index by 1 after each iteration.
Example
Print all items, using a while loop to go through all the index numbers
thislist = ["apple", "banana", "cherry"]
i=0
while i < len(thislist):
print(thislist[i])
i=i+1
Example
A short hand for loop that will print all items in a list:
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the
values of an existing list.
Example:
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in
the name.
Without list comprehension you will have to write a for statement with a conditional test
inside:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
if "a" in x:
[Link](x)

print(newlist)
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

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)

thislist = [100, 50, 65, 82, 23]


[Link](key = myfunc)
print(thislist)

Case Insensitive Sort


By default the sort() method is case sensitive, resulting in all capital letters being sorted
before lower case letters:
Example
Case sensitive sorting can give an unexpected result:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
[Link]()
print(thislist)
Luckily we can use built-in functions as key functions when sorting a list.
So if you want a case-insensitive sort function, use [Link] as a key function:
Example
Perform a case-insensitive sort of the list:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
[Link](key = [Link])
print(thislist)

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]

list3 = list1 + list2


print(list3)
Another way to join two lists is by appending all the items from list2 into list1, one by one:
Example
Append list2 into list1:
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))

Create Tuple With One Item


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:
thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

Tuple Items - Data Types


Tuple items can be of any data type:
Example
String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
A tuple can contain different data types:
Example
A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
type()
From Python's perspective, tuples are defined as objects with the data type 'tuple':
<class 'tuple'>
Example
What is the data type of a tuple?
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
The tuple() Constructor
It is also possible to use the tuple() constructor to make a tuple.
Example
Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)

Loop Through the Index Numbers


You can also loop through the tuple items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.
Example
Print all items by referring to their index number:
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])

Using a While Loop


You can loop through the tuple items by using a while loop.
Use the len() function to determine the length of the tuple, then start at 0 and loop your way
through the tuple items by referring to their indexes.
Remember to increase the index by 1 after each iteration.
Example
Print all items, using a while loop to go through all the index numbers:
thistuple = ("apple", "banana", "cherry")
i=0
while i < len(thistuple):
print(thistuple[i])
i=i+1
Join Two Tuples
To join two or more tuples you can use the + operator:
ExampleJoin two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)

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

count() Returns the number of times a specified value occurs in a tuple

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)

Get the Length of a Set


To determine how many items a set has, use the len() function.
Example
Get the number of items in a set:
thisset = {"apple", "banana", "cherry"}

print(len(thisset))

Set Items - Data Types


Set items can be of any data type:
Example
String, int and boolean data types:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}

A set can contain different data types:


Example
A set with strings, integers and boolean values:
set1 = {"abc", 34, True, 40, "male"}

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

The set() Constructor


It is also possible to use the set() constructor to make a set.
Example
Using the set() constructor to make a set:
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)

Keep ONLY the Duplicates


The intersection_update() method will keep only the items that are present in both sets.
Example
Keep the items that exist in both set x, and set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

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)

Keep All, But NOT the Duplicates


The symmetric_difference_update() method will keep only the elements that are NOT present
in both sets.
Example
Keep the items that are not present in both sets:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

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

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() Returns a set containing the difference between two or


more sets

difference_update() Removes the items in this set that are also included in
another, specified set

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other sets

intersection_update() Removes the items in this set that are not present in
other, specified set(s)

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update() inserts the symmetric differences from this set and


another

union() Return a set containing the union of sets

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.

Duplicates Not Allowed


Dictionaries cannot have two items with the same key:
Example
Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)

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

Dictionary Items - Data Types


The values in dictionary items can be of any data type:
Example
String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

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

The dict() Constructor


It is also possible to use the dict() constructor to make a dictionary.
Example
Using the dict() method to make a dictionary:
thisdict = dict(name = "John", age = 36, country = "Norway")
print(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)

Another way to make a copy is to use the built-in function dict().


Example
Make a copy of a dictionary with the dict() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
ExampleCreate a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}

Or, if you want to add three dictionaries into a new dictionary:


Example
Create three dictionaries, then create one dictionary that will contain the other three
dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}

myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}

Access Items in Nested Dictionaries


To access items from a nested dictionary, you use the name of the dictionaries, starting with
the outer dictionary:
Example
Print the name of child 2:
print(myfamily["child2"]["name"])
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the
key, with the specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary

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

print ("Fourth element = %d" %(a[3]))

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

def AbyB(a , b):


try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

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 :

from exceptions import Userexception

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 :

array = { 'a':1, 'b':2 }


print (array['c'])

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 ('Regular integer: (maxint=%s)' % [Link])


try:
i = [Link] * 3
print ('No overflow for ', type(i), 'i =', i)
except OverflowError, err:
print ('Overflowed at ', i, err)

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

Floating point values:


0 1.23794003929e+27
1 1.53249554087e+54
2 2.34854258277e+108
3 5.5156522631e+216
Overflowed after 5.5156522631e+216 (34, 'Numerical result out of range')

16. exception RecursionError


The RecursionError is derived from the RuntimeError. This exception is raised when
the interpreter detects that the maximum recursion depth is exceeded.
17. exception ReferenceError
The ReferenceError is raised when a weak reference proxy is used to access an
attribute of the referent after the garbage collection.
Example :

import gc
import weakref

class Foo(object):

def __init__(self, name):


[Link] = name

def __del__(self):
print ('(Deleting %s)' % self)

obj = Foo('obj')
p = [Link](obj)

print ('BEFORE:', [Link])


obj = None
print ('AFTER:', [Link])

Output :
BEFORE: obj
(Deleting )
AFTER:

Traceback (most recent call last):


File "[Link]", line 17, in
print 'AFTER:', [Link]
ReferenceError: weakly-referenced object no longer exists
18. exception RuntimeError
The RuntimeError is raised when no other exception applies. It returns a string
indicating what precisely went wrong.
19. exception StopIteration
The StopIteration error is raised by built-in function next() and an iterator‘s
__next__() method to signal that all items are produced by the iterator.
Example :
Arr = [3, 1, 2]
i=iter(Arr)

print (i)
print ([Link]())
print ([Link]())
print ([Link]())
print ([Link]())

Output :

3
1
2

Traceback (most recent call last):


File "[Link]", line 8, in
print [Link]()
StopIteration
20. exception SyntaxError
The SyntaxError is raised when the parser encounters a syntax error. A syntax error
may occur in an import statement or while calling the built-in functions exec() or
eval(), or when reading the initial script or standard input.
Example :

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

# A simple module, [Link]


def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)

Import module in Python


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

# importing module [Link]


import calc

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

# importing sqrt() and factorial from the


# module math
from math import sqrt, factorial

# if we simply do "import math", then


# [Link](16) and [Link]()
# are required.
print(sqrt(16))
print(factorial(6))

Output:
4.0
720
Import all Names
The * symbol used with the import statement is used to import all the names from a module
to a current namespace.
Syntax:
from module_name import *
What does import * do in Python
The use of * has its advantages and disadvantages. If you know exactly what you will be
needing from the module, it is not recommended to use *, else do so.

# importing sqrt() and factorial from the


# module math
from math import *

# if we simply do "import math", then


# [Link](16) and [Link]()
# are required.
print(sqrt(16))
print(factorial(6))

Output
4.0
720
Locating Python Modules
Whenever a module is imported in Python the interpreter looks for several locations. First, it
will check for the built-in module, if not found then it looks for a list of directories defined in
the [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 sys module


import sys

# 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

# if we simply do "import math", then


# [Link](16) and [Link]()
# are required.
print([Link](16))
print([Link](6))

Output
4.0
720
Python Built-in modules
There are several built-in modules in Python, which you can import whenever you like.
Python3

# importing built-in module math


import math

# using square root(sqrt) function contained


# in math module
print([Link](25))

# using pi function contained in math module


print([Link])

# 2 radians = 114.59 degrees


print([Link](2))

# 60 degrees = 1.04 radians


print([Link](60))

# Sine of 2 radians
print([Link](2))

# Cosine of 0.5 radians


print([Link](0.5))

# Tangent of 0.23 radians


print([Link](0.23))

# 1 * 2 * 3 * 4 = 24
print([Link](4))
# importing built in module random
import random

# printing random integer between 0 and 5


print([Link](0, 5))

# print random floating point number between 0 and 1


print([Link]())

# random number between 0 and 100


print([Link]() * 100)

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

# using choice function in random module for choosing


# a random element from a set such as a list
print([Link](List))

# importing built in module datetime


import datetime
from datetime import date
import time

# Returns the number of seconds since the


# Unix Epoch, January 1st 1970
print([Link]())

# Converts a number of seconds to a date object


print([Link](454554))

Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87
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>

The Module Search Path


Continuing with the above example, let’s take a look at what happens when Python executes
the statement:
Python
import mod
When the interpreter executes the above import statement, it searches for [Link] in a list of
directories assembled from the following sources:
 The directory from which the input script was run or the current directory if the
interpreter is being run interactively
 The list of directories contained in the PYTHONPATH environment variable, if it is
set. (The format for PYTHONPATH is OS-dependent but should mimic
the PATH environment variable.)
 An installation-dependent list of directories configured at the time Python is installed
The resulting search path is accessible in the Python variable [Link], which is obtained from
a module named sys:
Python
>>> import sys
>>> [Link]
['', 'C:\\Users\\john\\Documents\\Python\\doc', 'C:\\Python36\\Lib\\idlelib',
'C:\\Python36\\[Link]', 'C:\\Python36\\DLLs', 'C:\\Python36\\lib',
'C:\\Python36', 'C:\\Python36\\lib\\site-packages']
Note: The exact contents of [Link] are installation-dependent. The above will almost
certainly look slightly different on your computer.
Thus, to ensure your module is found, you need to do one of the following:
 Put [Link] in the directory where the input script is located or the current directory,
if interactive
 Modify the PYTHONPATH environment variable to contain the directory
where [Link] is located before starting the interpreter
o Or: Put [Link] in one of the directories already contained in
the PYTHONPATH variable
 Put [Link] in one of the installation-dependent directories, which you may or may
not have write-access to, depending on the OS
There is actually one additional option: you can put the module file in any directory of your
choice and then modify [Link] at run-time so that it contains that directory. For example, in
this case, you could put [Link] in directory C:\Users\john and then issue the following
statements:
Python
>>> [Link](r'C:\Users\john')
>>> [Link]
['', 'C:\\Users\\john\\Documents\\Python\\doc', 'C:\\Python36\\Lib\\idlelib',
'C:\\Python36\\[Link]', 'C:\\Python36\\DLLs', 'C:\\Python36\\lib',
'C:\\Python36', 'C:\\Python36\\lib\\site-packages', 'C:\\Users\\john']
>>> import mod
Once a module has been imported, you can determine the location where it was found with
the module’s __file__ attribute:
Python
>>> import mod
>>> mod.__file__
'C:\\Users\\john\\[Link]'

>>> 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> ...]

from <module_name> import <name(s)>


An alternate form of the import statement allows individual objects from the module to be
imported directly into the caller’s symbol table:
Python
from <module_name> import <name(s)>
Following execution of the above statement, <name(s)> can be referenced in the caller’s
environment without the <module_name> prefix:
Python
>>> from mod import s, foo
>>> s
'If Comrade Napoleon says it, it must be right.'
>>> foo('quux')
arg = quux

>>> from mod import Foo


>>> x = Foo()
>>> x
<[Link] object at 0x02E3AD50>
Because this form of import places the object names directly into the caller’s symbol table,
any objects that already exist with the same name will be overwritten:
Python
>>> a = ['foo', 'bar', 'baz']
>>> a
['foo', 'bar', 'baz']

>>> from mod import a


>>> a
[100, 200, 300]
It is even possible to indiscriminately import everything from a module at one fell swoop:
Python
from <module_name> import *
This will place the names of all objects from <module_name> into the local symbol table,
with the exception of any that begin with the underscore (_) character.
For example:
Python
>>> from mod import *
>>> s
'If Comrade Napoleon says it, it must be right.'
>>> a
[100, 200, 300]
>>> foo
<function foo at 0x03B449C0>
>>> Foo
<class '[Link]'>
This isn’t necessarily recommended in large-scale production code. It’s a bit dangerous
because you are entering names into the local symbol table en masse. Unless you know them
all well and can be confident there won’t be a conflict, you have a decent chance of
overwriting an existing name inadvertently. However, this syntax is quite handy when you
are just mucking around with the interactive interpreter, for testing or discovery purposes,
because it quickly gives you access to everything a module has to offer without a lot of
typing.
from <module_name> import <name> as <alt_name>
It is also possible to import individual objects but enter them into the local symbol table with
alternate names:
Python
from <module_name> import <name> as <alt_name>[, <name> as <alt_name> …]
This makes it possible to place names directly into the local symbol table but avoid conflicts
with previously existing names:
Python
>>> s = 'foo'
>>> a = ['foo', 'bar', 'baz']

>>> from mod import s as string, a as alist


>>> s
'foo'
>>> string
'If Comrade Napoleon says it, it must be right.'
>>> a
['foo', 'bar', 'baz']
>>> alist
[100, 200, 300]
import <module_name> as <alt_name>
You can also import an entire module under an alternate name:
Python
import <module_name> as <alt_name>
Python
>>> import mod as my_module
>>> my_module.a
[100, 200, 300]
>>> my_module.foo('qux')
arg = qux
Module contents can be imported from within a function definition. In that case,
the import does not occur until the function is called:
Python
>>> def bar():
... from mod import foo
... foo('corge')
...

>>> 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')
...

Module not found


Python
>>> try:
... # Existing module, but non-existent object
... from mod import baz
... except ImportError:
... print('Object not found in module')
...

Object not found in module

The dir() Function


The built-in function dir() returns a list of defined names in a namespace. Without arguments,
it produces an alphabetically sorted list of names in the current local symbol table:
Python
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__']

>>> qux = [1, 2, 3, 4, 5]


>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__', 'qux']

>>> class Bar():


... pass
...
>>> x = Bar()
>>> dir()
['Bar', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__', 'qux', 'x']
Note how the first call to dir() above lists several names that are automatically defined and
already in the namespace when the interpreter starts. As new names are defined (qux, Bar, x),
they appear on subsequent invocations of dir().
This can be useful for identifying what exactly has been added to the namespace by an import
statement:
Python
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__']

>>> import mod


>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__', 'mod']
>>> mod.s
'If Comrade Napoleon says it, it must be right.'
>>> [Link]([1, 2, 3])
arg = [1, 2, 3]

>>> from mod import a, Foo


>>> dir()
['Foo', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__', 'a', 'mod']
>>> a
[100, 200, 300]
>>> x = Foo()
>>> x
<[Link] object at 0x002EAD50>

>>> from mod import s as string


>>> dir()
['Foo', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__', 'a', 'mod', 'string', 'x']
>>> string
'If Comrade Napoleon says it, it must be right.'
When given an argument that is the name of a module, dir() lists the names defined in the
module:
Python
>>> import mod
>>> dir(mod)
['Foo', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', 'a', 'foo', 's']
Python
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__']
>>> from mod import *
>>> dir()
['Foo', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__', 'a', 'foo', 's']
Executing a Module as a Script
Any .py file that contains a module is essentially also a Python script, and there isn’t any
reason it can’t be executed like one.
Here again is [Link] as it was defined above:
[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
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]

>>> import mod

>>> import importlib


>>> [Link](mod)
a = [100, 200, 300]
<module 'mod' from 'C:\\Users\\john\\Documents\\Python\\doc\\[Link]'>
Python Packages
Suppose you have developed a very large application that includes many modules. As the
number of modules grows, it becomes difficult to keep track of them all if they are dumped
into one location. This is particularly so if they have similar names or functionality. You
might wish for a means of grouping and organizing them.
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.
Creating a package is quite straightforward, since it makes use of the operating system’s
inherent hierarchical file structure. Consider the following arrangement:

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

>>> from pkg import mod2 as quux


>>> [Link]()
[mod2] bar()
You can technically import the package as well:
Python
>>> import pkg
>>> pkg
<module 'pkg' (namespace)>
But this is of little avail. Though this is, strictly speaking, a syntactically correct Python
statement, it doesn’t do much of anything useful. In particular, it does not place any of the
modules in pkg into the local namespace:
Python
>>> pkg.mod1
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
pkg.mod1
AttributeError: module 'pkg' has no attribute 'mod1'
>>> [Link]()
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
[Link]()
AttributeError: module 'pkg' has no attribute 'mod1'
>>> [Link]()
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
[Link]()
AttributeError: module 'pkg' has no attribute 'mod2'
To actually import the modules or their contents, you need to use one of the forms shown
above.
Package Initialization
If a file named __init__.py is present in a package directory, it is invoked when the package
or a module in the package is imported. This can be used for execution of package
initialization code, such as initialization of package-level data.
For example, consider the following __init__.py file:
__init__.py
Python
print(f'Invoking __init__.py for {__name__}')
A = ['quux', 'corge', 'grault']
Let’s add this file to the pkg directory from the above example:

Now when the package is imported, the global list A is initialized:


Python
>>> import pkg
Invoking __init__.py for pkg
>>> pkg.A
['quux', 'corge', 'grault']
A module in the package can access the global variable by importing it in turn:
[Link]
Python
def foo():
from pkg import A
print('[mod1] foo() / A = ', A)

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__']

>>> from pkg import *


>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__']
Hmph. Not much. You might have expected (assuming you had any expectations at all) that
Python would dive down into the package directory, find all the modules it could, and import
them all. But as you can see, by default that is not what happens.
Instead, Python follows this convention: if the __init__.py file in the package directory
contains a list named __all__, it is taken to be a list of modules that should be imported when
the statement from <package_name> import * is encountered.
For the present example, suppose you create an __init__.py in the pkg directory like this:
pkg/__init__.py
Python
__all__ = [
'mod1',
'mod2',
'mod3',
'mod4'
]
Now from pkg import * imports all four modules:
Python
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__']

>>> from pkg import *


>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__', 'mod1', 'mod2', 'mod3', 'mod4']
>>> [Link]()
[mod2] bar()
>>> [Link]
<class '[Link]'>
Using import * still isn’t considered terrific form, any more for packages than for modules.
But this facility at least gives the creator of the package some control over what happens
when import * is specified. (In fact, it provides the capability to disallow it entirely, simply
by declining to define __all__ at all. As you have seen, the default behavior for packages is to
import nothing.)
By the way, __all__ can be defined in a module as well and serves the same purpose: to
control what is imported with import *. For example, modify [Link] as follows:
pkg/[Link]
Python
__all__ = ['foo']

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__']

>>> from pkg.mod1 import *


>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__', 'foo']

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

>>> from pkg.sub_pkg1 import mod2


>>> [Link]()
[mod2] bar()

>>> from pkg.sub_pkg2.mod3 import baz


>>> baz()
[mod3] baz()

>>> from pkg.sub_pkg2.mod4 import qux as grault


>>> grault()
[mod4] qux()
In addition, a module in one subpackage can reference objects in a sibling subpackage (in
the event that the sibling contains some functionality that you need). For example, suppose
you want to import and execute function foo() (defined in module mod1) from within
module mod3. You can either use an absolute import:
pkg/sub__pkg2/[Link]
Python
def baz():
print('[mod3] baz()')
class Baz:
pass

from pkg.sub_pkg1.mod1 import foo


foo()
Python
>>> from pkg.sub_pkg2 import mod3
[mod1] foo()
>>> [Link]()
[mod1] foo()
Or you can use a relative import, where .. refers to the package one level up. From
within [Link], which is in subpackage sub_pkg2,
 .. evaluates to the parent package (pkg), and
 ..sub_pkg1 evaluates to subpackage sub_pkg1 of the parent package.
pkg/sub__pkg2/[Link]
Python
def baz():
print('[mod3] baz()')

class Baz:
pass

from .. import sub_pkg1


print(sub_pkg1)

from ..sub_pkg1.mod1 import foo


foo()
Python
>>> from pkg.sub_pkg2 import mod3
<module 'pkg.sub_pkg1' (namespace)>
[mod1] foo()

You might also like