Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
26 views

Unit 2 Python Programming Diploma-1

Functions are reusable blocks of code that can be called multiple times in a Python program. There are two types of functions - user-defined functions created by the user, and built-in functions that are pre-defined in Python. Functions improve modularity and code reusability. They are defined using the def keyword and can accept arguments. Functions can return values using the return statement. Arguments passed to functions in Python are call by reference.

Uploaded by

hamza.034975
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Unit 2 Python Programming Diploma-1

Functions are reusable blocks of code that can be called multiple times in a Python program. There are two types of functions - user-defined functions created by the user, and built-in functions that are pre-defined in Python. Functions improve modularity and code reusability. They are defined using the def keyword and can accept arguments. Functions can return values using the return statement. Arguments passed to functions in Python are call by reference.

Uploaded by

hamza.034975
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Diploma (CS) Semester 6th

DCS606 Python Programming


Unit 2 Functions, List, Tuple, Dictionary
Python Function
Functions are the most important aspect of an application. A function can be defined as the
organized block of reusable code, which can be called whenever required.
Python allows us to divide a large program into the basic building blocks known as a function.
A function can be called multiple times to provide reusability and modularity to the Python
program.
The Function helps to programmer to break the program into the smaller part. It organizes the
code very effectively and avoids the repetition of the code. As the program grows, function
makes the program more organized.
Python provide us various inbuilt functions like range() or print(). Although, the user can
create its functions, which can be called user-defined functions.
There are mainly two types of functions.
o User-define functions - The user-defined functions are those define by the user to
perform the specific task.
o Built-in functions - The built-in functions are those functions that are pre-defined in
Python.

Advantage of Functions in Python


There are the following advantages of Python functions.
o Using functions, we can avoid rewriting the same logic/code again and again in a program.
o We can call Python functions multiple times in a program and anywhere in a program.
o We can track a large Python program easily when it is divided into multiple functions.
o Reusability is the main achievement of Python functions.
o However, Function calling is always overhead in a Python program.

Creating a Function
Python provides the def keyword to define the function. The syntax of the define function is
given below.

Syntax:
1. def my_function(parameters):
2. function_block
3. return expression
Let's understand the syntax of functions definition.
o The def keyword, along with the function name is used to define the function.
o The identifier rule must follow the function name.
o A function accepts the parameter (argument), and they can be optional.
o The function block is started with the colon (:), and block statements must be at the same
indentation.
o The return statement is used to return the value. A function can have only one return

Function Calling
In Python, after the function is created, we can call it from another function. A function must
be defined before the function call; otherwise, the Python interpreter gives an error. To call the
function, use the function name followed by the parentheses.
Consider the following example of a simple example that prints the message "Hello World".
1. #function definition
2. def hello_world():
3. print("hello world")
4. # function calling
5. hello_world()

Output:
hello world

The return statement


The return statement is used at the end of the function and returns the result of the function. It
terminates the function execution and transfers the result where the function is called. The
return statement cannot be used outside of the function.

Syntax
1. return [expression_list]
It can contain the expression which gets evaluated and value is returned to the caller function.
If the return statement has no expression or does not exist itself in the function then it returns
the None object.
Consider the following example:

Example 1
1. # Defining function
2. def sum():
3. a = 10
4. b = 20
5. c = a+b
6. return c
7. # calling sum() function in print statement
8. print("The sum is:",sum())

Output:
The sum is: 30
In the above code, we have defined the function named sum, and it has a statement c = a+b, which computes the
given values, and the result is returned by the return statement to the caller function.

Example 2 Creating function without return statement


# Defining function
def sum():
a = 10
b = 20
c = a+b
# calling sum() function in print statement
print(sum())

Output:
None
In the above code, we have defined the same function without the return statement as we can
see that the sum() function returned the None object to the caller function.
Arguments in function
The arguments are types of information which can be passed into the function. The arguments
are specified in the parentheses. We can pass any number of arguments, but they must be
separate them with a comma.
Consider the following example, which contains a function that accepts a string as the
argument.

Example 1
1. #defining the function
2. def func (name):
3. print("Hi ",name)
4. #calling the function
5. func("Devansh")

Output:
Hi Devansh

Example 2
1. #Python function to calculate the sum of two variables
2. #defining the function
3. def sum (a,b):
4. return a+b;
5. #taking values from the user
6. a = int(input("Enter a: "))
7. b = int(input("Enter b: "))
8. #printing the sum of a and b
9. print("Sum = ",sum(a,b))

Output:
Enter a: 10
Enter b: 20
Sum = 30

Call by reference in Python


In Python, call by reference means passing the actual value as an argument in the function. All
the functions are called by reference, i.e., all the changes made to the reference inside the
function revert back to the original value referred by the reference.

Example 1 Passing mutable Object (List)


1. #defining the function
2. def change_list(list1):
3. list1.append(20)
4. list1.append(30)
5. print("list inside function = ",list1)
6. #defining the list
7. list1 = [10,30,40,50]
8. #calling the function
9. change_list(list1)
10. print("list outside function = ",list1)
Output:
list inside function = [10, 30, 40, 50, 20, 30]
list outside function = [10, 30, 40, 50, 20, 30]

Example 2 Passing Imutable Object (String)


1. #defining the function
2. def change_string (str):
3. str = str + " Hows you "
4. print("printing the string inside function :",str)
5. string1 = "Hi I am there"
6. #calling the function
7. change_string(string1)
8. print("printing the string outside function :",string1)
Output:
printing the string inside function : Hi I am there Hows you
printing the string outside function : Hi I am there

Types of arguments
There may be several types of arguments which can be passed at the time of function call.
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments
Till now, we have learned about function calling in Python. However, we can provide the
arguments at the time of the function call. As far as the required arguments are concerned, these
are the arguments which are required to be passed at the time of function calling with the exact
match of their positions in the function call and function definition. If either of the arguments
is not provided in the function call, or the position of the arguments is changed, the Python
interpreter will show the error.
Consider the following example.

Example 1
1. def func(name):
2. message = "Hi "+name
3. return message
4. name = input("Enter the name:")
5. print(func(name))
Output:
Enter the name: John
Hi John

Example 2
1. #the function simple_interest accepts three arguments and returns the simple interest accordin
gly
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4. p = float(input("Enter the principle amount? "))
5. r = float(input("Enter the rate of interest? "))
6. t = float(input("Enter the time in years? "))
7. print("Simple Interest: ",simple_interest(p,r,t))
Output:
Enter the principle amount: 5000
Enter the rate of interest: 5
Enter the time in years: 3
Simple Interest: 750.0

Example 3
1. #the function calculate returns the sum of two arguments a and b
2. def calculate(a,b):
3. return a+b
4. calculate(10) # this causes an error as we are missing a required arguments b.
Output:
TypeError: calculate() missing 1 required positional argument: 'b'

Default Arguments
Python allows us to initialize the arguments at the function definition. If the value of any of the
arguments is not provided at the time of function call, then that argument can be initialized
with the value given in the definition even if the argument is not specified at the function call.
Example 1
1. def printme(name, age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john")
Output:
My name is John and age is 22
Example 2
1. def printme(name, age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john") #the variable age is not passed into the function however the default
value of age is considered in the function
4. printme(age = 10,name="David") #the value of age is overwritten here, 10 will be printed as
age
Output:
My name is john and age is 22
My name is David and age is 10

Variable-length Arguments (*args)


In large projects, sometimes we may not know the number of arguments to be passed in
advance. In such cases, Python provides us the flexibility to offer the comma-separated values
which are internally treated as tuples at the function call. By using the variable-length
arguments, we can pass any number of arguments.
However, at the function definition, we define the variable-length argument using
the *args (star) as *<variable - name >.
Consider the following example.
Example
1. def printme(*names):
2. print("type of passed argument is ",type(names))
3. print("printing the passed arguments...")
4. for name in names:
5. print(name)
6. printme("john","David","smith","nick")

Output:
type of passed argument is <class 'tuple'>
printing the passed arguments...
john
David
smith
nick
In the above code, we passed *names as variable-length argument. We called the function and
passed values which are treated as tuple internally. The tuple is an iterable sequence the same
as the list. To print the given values, we iterated *arg names using for loop.

Keyword arguments(**kwargs)
Python allows us to call the function with the keyword arguments. This kind of function call
will enable us to pass the arguments in the random order.
The name of the arguments is treated as the keywords and matched in the function calling and
definition. If the same match is found, the values of the arguments are copied in the function
definition.
Consider the following example.

Example 1
1. #function func is called with the name and message as the keyword arguments
2. def func(name, message):
3. print("printing the message with", name, "and ",message)
4. #name and message is copied with the values John and hello respectively
5. func(name = "John", message="hello")
Output:
printing the message with John and hello

Example 2 providing the values in different order at the calling


1. #The function simple_interest(p, t, r) is called with the keyword arguments the order of argu
ments doesn't matter in this case
2. def simple_interest(p, t, r):
3. return (p*t*r)/100
4. print("Simple Interest: ",simple_interest(t=10,r=10,p=1900))
Output: Simple Interest: 1900.0
If we provide the different name of arguments at the time of function call, an error will be
thrown.
Consider the following example.

Example 3
1. #The function simple_interest (p, t, r) is called with the keyword arguments.
2. def simple_interest(p, t, r):
3. return (p*t*r)/100
4. # doesn't find the exact match of the name of the arguments (keywords)
5. print("Simple Interest: ",simple_interest(time=10,rate=10,principle=1900))
Output:
TypeError: simple_interest() got an unexpected keyword argument 'time'
The Python allows us to provide the mix of the required arguments and keyword arguments at
the time of function call. However, the required argument must not be given after the keyword
argument, i.e., once the keyword argument is encountered in the function call, the following
arguments must also be the keyword arguments.
Consider the following example.

Example 4
1. def func(name1,message,name2):
2. print("printing the message with",name1,",",message,",and",name2)
3. #the first argument is not the keyword argument
4. func("John",message="hello",name2="David")
Output: printing the message with John , hello ,and David
The following example will cause an error due to an in-proper mix of keyword and required
arguments being passed in the function call.

Example 5
1. def func(name1,message,name2):
2. print("printing the message with",name1,",",message,",and",name2)
3. func("John",message="hello","David")
Output: SyntaxError: positional argument follows keyword argument
Python provides the facility to pass the multiple keyword arguments which can be represented
as **kwargs. It is similar as the *args but it stores the argument in the dictionary format.
This type of arguments is useful when we do not know the number of arguments in advance.
Consider the following example:

Example 6: Many arguments using Keyword argument


1. def food(**kwargs):
2. print(kwargs)
3. food(a="Apple")
4. food(fruits="Orange", Vegetables="Carrot")
Output:
{'a': 'Apple'}
{'fruits': 'Orange', 'Vegetables': 'Carrot'}

Python Lambda Functions (anonymous function)


Python Lambda function is known as the anonymous function that is defined without a name.
Python allows us to not declare the function in the standard manner, i.e., by using
the def keyword. Rather, the anonymous functions are declared by using the lambda keyword.
However, Lambda functions can accept any number of arguments, but they can return only one
value in the form of expression.
The anonymous function contains a small piece of code. It simulates inline functions of C and
C++, but it is not exactly an inline function.
The syntax to define an anonymous function is given below.

Syntax
lambda arguments: expression
It can accept any number of arguments and has only one expression. It is useful when the function
objects are required.
Consider the following example of the lambda function.

Example 1
1. # a is an argument and a+10 is an expression which got evaluated and returned.
2. x = lambda a:a+10
3. # Here we are printing the function object
4. print(x)
5. print("sum = ",x(20))
Output:
<function <lambda> at 0x0000019E285D16A8>
sum = 30

In the above example, we have defined the lambda a: a+10 anonymous function where a is an
argument and a+10 is an expression. The given expression gets evaluated and returned the result. The
above lambda function is same as the normal function.

1. def x(a):
2. return a+10
3. print(“sum =”, x(10))

Example 2
Multiple arguments to Lambda function
# a and b are the arguments and a*b is the expression which gets evaluated and returned.
x = lambda a,b: a*b
print("mul = ", x(20,10))
mul = 200

Example
#the function table(n) prints the table of n
def table(n):
return lambda a:a*n # a will contain the iteration variable i and a multiple of n is
returned at each function call
n = int(input("Enter the number:"))
b = table(n) #the entered number is passed into the function table. b will contain a
lambda function which is called again and again with the iteration variable i
for i in range(1,11):
print(n,"X",i,"=",b(i)) #the lambda function b is called with the iteration variable
i
Output:
Enter the number:10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100

Python List
A list in Python is used to store the sequence of various types of data. Python lists are mutable
type its mean we can modify its element after it created. However, Python consists of six data-
types that are capable to store the sequences, but the most common and reliable type is the list.

A list can be defined as a collection of values or items of different types. The items in the list
are separated with the comma (,) and enclosed with the square brackets [].

A list can be define as below

1. L1 = ["John", 102, "USA"]


2. L2 = [1, 2, 3, 4, 5, 6]

IIf we try to print the type of L1, L2, and L3 using type() function then it will come out
to be a list.

1. print(type(L1))
2. print(type(L2))

Output:

<class 'list'>
<class 'list'>

Characteristics of Lists

The list has the following characteristics:

o The lists are ordered.


o The element of the list can access by index.
o The lists are the mutable type.
o The lists are mutable types.
o A list can store the number of various elements.

Let's check the first statement that lists are the ordered.
1. a = [1,2,"Peter",4.50,"Ricky",5,6]
2. b = [1,2,5,"Peter",4.50,"Ricky",6]
3. a ==b

Output:
False

Both lists have consisted of the same elements, but the second list changed the index
position of the 5th element that violates the order of lists. When compare both lists it
returns the false.

Lists maintain the order of the element for the lifetime. That's why it is the ordered
collection of objects.

1. a = [1, 2,"Peter", 4.50,"Ricky",5, 6]


2. b = [1, 2,"Peter", 4.50,"Ricky",5, 6]
3. a == b
Output:
True
Let's have a look at the list example in detail.
Example
emp = ["John", 102, "USA"]
Dep1 = ["CS",10]
Dep2 = ["IT",11]
HOD_CS = [10,"Mr. Holding"]
HOD_IT = [11, "Mr. Bewon"]
print("printing employee data...")
print("Name : %s, ID: %d, Country: %s"%(emp[0],emp[1],emp[2]))
print("printing departments...")
print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID: %s
"%(Dep1[0],Dep2[1],Dep2[0],Dep2[1]))
print("HOD Details ....")
print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]))
print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]))
print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT))
Output
printing employee data...
Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class 'list'><class 'list'><class 'list'><class 'list'><class 'list'>
List indexing and splitting

The indexing is processed in the same way as it happens with the strings. The elements
of the list can be accessed by using the slice operator [].

The index starts from 0 and goes to length - 1. The first element of the list is stored at
the 0th index, the second element of the list is stored at the 1st index, and so on.

We can get the sub-list of the list using the following syntax.
1. list_varible(start:stop:step)
 The start denotes the starting index position of the list.
 The stop denotes the last index position of the list.
 The step is used to skip the nth element within a start:stop

Consider the following example:

Example
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default the index value is 0 so its starts from the 0th element an
d go for index -1.
print(list[:])
print(list[2:5])
print(list[1:6:2])
Output
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
Unlike other languages, Python provides the flexibility to use the negative indexing also. The
negative indices are counted from the right. The last element (rightmost) of the list has the
index -1; its adjacent left element is present at the index -2 and so on until the left-most
elements are encountered.

Let's have a look at the following example where we will use negative indexing to access the
elements of the list.
Example
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])
Output
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]

As we discussed above, we can get an element by using negative indexing. In the above
code, the first print statement returned the rightmost element of the list. The second
print statement returned the sub-list, and so on.

Updating List values

Lists are the most versatile data structures in Python since they are mutable, and their
values can be updated by using the slice and assignment operator.

Python also provides append() and insert() methods, which can be used to add values
to the list.

Consider the following example to update the values inside the list.
Example
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second index
list[2] = 10
print(list)
# Adding multiple-element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
Output
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

Insert() Function:
EXAMPLE

# create a list of vowels


vowel = ['a', 'e', 'i', 'u']
# 'o' is inserted at index 3 (4th position)
vowel.insert(3, 'o')
print('List:', vowel)

#Output:

List: ['a', 'e', 'i', 'o', 'u']

Python List Operations

The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings.

Let's see how the list responds to various operators.

1. Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8] to perform operation.

Operator Description Example

Repetition The repetition operator enables the list L1*2 = [1, 2, 3, 4,


1, 2, 3, 4]
elements to be repeated multiple times.
Concatenation It concatenates the list mentioned on l1+l2 = [1, 2, 3, 4,
5, 6, 7, 8]
either side of the operator.

Membership It returns true if a particular item exists in a print(2 in l1)


prints True.
particular list otherwise false.

Iteration The for loop is used to iterate over the list for i in l1:
print(i)
elements.
Output
1
2
3
4

Length It is used to get the length of the list len(l1) = 4

Iterating a List

A list can be iterated by using a for - in loop. A simple list containing four strings, which
can be iterated as follows.

Example
list = ["John", "David", "James", "Jonathan"]
for i in list:
# The i variable will iterate over the elements of the List and con
tains each element in each iteration.
print(i)
Output
John
David
James
Jonathan
Adding elements to the list

Python provides append() function which is used to add an element to the list.
However, the append() function can only add value to the end of the list.

Consider the following example in which, we are taking the elements of the list from
the user and printing the list on the console.

Example
#Declaring the empty list
l =[]
#Number of elements will be entered by the user
n = int(input("Enter the number of elements in the list:"))
# for loop to take the input
for i in range(0,n):
# The input is taken from the user and added to the list as the ite
m
l.append(input("Enter the item:"))
print("printing the list items..")
# traversal loop to print the list items
for i in l:
print(i, end = " ")
Output
Enter the number of elements in the list:5
Enter the item:6
Enter the item:4
Enter the item:2
Enter the item:8
Enter the item:9
printing the list items..
6 4 2 8 9
Removing elements from the list

Python provides the remove() function which is used to remove the element from the
list. Consider the following example to understand this concept.

Example
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
list.remove(2)
print("\nprinting the list after the removal of first element...")
for i in list:
print(i,end=" ")
Output
printing original list:
0 1 2 3 4
printing the list after the removal of first element...
0 1 3 4
Python List Built-in functions

Python provides the following built-in functions, which can be used with the lists.

SN Function Description Example

1 cmp(list1, It compares the elements of This method is not used in the Python 3
list2) both the lists. and the above versions.
2 len(list) It is used to calculate the L1 = [1,2,3,4,5,6,7,8]
print(len(L1))
length of the list. 8

3 max(list) It returns the maximum L1 = [12,34,26,48,72]


print(max(L1))
element of the list. 72

4 min(list) It returns the minimum L1 = [12,34,26,48,72]


print(min(L1))
element of the list. 12

5 list(seq) It converts any sequence to str = "Johnson"


s = list(str)
the list. print(type(s))
<class list>

Let's have a look at the few list examples.

Example: 1- Write the program to remove the duplicate element of the list.

list1 = [1,2,2,3,55,98,65,65,13,29]
# Declare an empty list that will store unique values
list2 = []
for i in list1:
if i not in list2:
list2.append(i)
print(list2)
Output
[1, 2, 3, 55, 98, 65, 13, 29]
Example:2- Write a program to find the sum of the element in the list.
list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)
Output
The sum is: 67
Example: 3- Write the program to find the lists consist of at least one common element.
list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y:
print("The common element is:",x)
Output
The common element is: 2
Python Tuple
Python Tuple is used to store the sequence of immutable Python objects. The tuple is
similar to lists since the value of the items stored in the list can be changed, whereas
the tuple is immutable, and the value of the items stored in the tuple cannot be
changed.

Creating a tuple

A tuple can be written as the collection of comma-separated (,) values enclosed with
the small () brackets. The parentheses are optional but it is good practice to use. A
tuple can be defined as follows.

Example
T1 = (101, "Peter", 22)
T2 = ("Apple", "Banana", "Orange")
T3 = 10,20,30,40,50
print(type(T1))
print(type(T2))
print(type(T3))
Output
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
An empty tuple can be created as follows.
T4 = ()
Creating a tuple with single element is slightly different. We will need to put comma after the
element to declare the tuple.
Example
tup1 = ("Python")
print(type(tup1))
#Creating a tuple with single element
tup2 = ("Python",)
print(type(tup2))
Output
<class 'str'>
<class 'tuple'>

A tuple is indexed in the same way as the lists. The items in the tuple can be accessed
by using their specific index value.

Consider the following example of tuple:

Example-1
tuple1 = (10, 20, 30, 40, 50, 60)
print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %d"%(count, i))
count = count+1
Output
(10, 20, 30, 40, 50, 60)
tuple1[0] = 10
tuple1[1] = 20
tuple1[2] = 30
tuple1[3] = 40
tuple1[4] = 50
tuple1[5] = 60
Example-2
tuple1 = tuple(input("Enter the tuple elements ..."))
print(tuple1)
count = 0
for i in tuple1:
print("tuple1[%d] = %s"%(count, i))
count = count+1
Output
Enter the tuple elements ...102369
('1', '0', '2', '3', '6', '9')
tuple1[0] = 1
tuple1[1] = 0
tuple1[2] = 2
tuple1[3] = 3
tuple1[4] = 6
tuple1[5] = 9

A tuple is indexed in the same way as the lists. The items in the tuple can be accessed
by using their specific index value.

We will see all these aspects of tuple in this section of the tutorial.

Tuple indexing and slicing

The indexing and slicing in the tuple are similar to lists. The indexing in the tuple starts
from 0 and goes to length(tuple) - 1.

The items in the tuple can be accessed by using the index [] operator. Python also
allows us to use the colon operator to access multiple items in the tuple.

Consider the following image to understand the indexing and slicing in detail.
Consider the following example:
Example-
tup = (1,2,3,4,5,6,7)
print(tup[0])
print(tup[1])
print(tup[2])
# It will give the IndexError
print(tup[8])
Output-
1
2
3
IndexError: tuple index out of range

In the above code, the tuple has 7 elements which denote 0 to 6. We tried to access an
element outside of tuple that raised an IndexError.
Example-
tuple = (1,2,3,4,5,6,7)
#element 1 to end
print(tuple[1:])
#element 0 to 3 element
print(tuple[:4])
#element 1 to 4 element
print(tuple[1:5])
# element 0 to 6 and take step of 2
print(tuple[0:6:2])
Output-
(2, 3, 4, 5, 6, 7)
(1, 2, 3, 4)
(2, 3, 4, 5)
(1, 3, 5)
Negative Indexing

The tuple element can also access by using negative indexing. The index of -1 denotes
the rightmost element and -2 to the second last item and so on.

The elements from left to right are traversed using the negative indexing. Consider the
following example:
Example-
tuple1 = (1, 2, 3, 4, 5)
print(tuple1[-1])
print(tuple1[-4])
print(tuple1[-3:-1])
print(tuple1[:-1])
print(tuple1[-2:])
Output-
5
2
(3, 4)
(1, 2, 3, 4)
(4, 5)
Deleting Tuple

Unlike lists, the tuple items cannot be deleted by using the del keyword as tuples are
immutable. To delete an entire tuple, we can use the del keyword with the tuple name.

Consider the following example.


Example-
tuple1 = (1, 2, 3, 4, 5, 6)
print(tuple1)
del tuple1[0]
print(tuple1)
del tuple1
print(tuple1)
Output-
(1, 2, 3, 4, 5, 6)
TypeError: 'tuple' object doesn't support item deletion.
Basic Tuple operations

The operators like concatenation (+), repetition (*), Membership (in) works in the same
way as they work with the list. Consider the following table for more detail.

Let's say Tuple T1 = (1, 2, 3, 4, 5) and Tuple T2 = (6, 7, 8, 9) are declared.

Operator Description Example


Repetition The repetition operator enables the tuple T1*2 = (1, 2, 3, 4, 5,
1, 2, 3, 4, 5)
elements to be repeated multiple times.

Concatenation It concatenates the tuple mentioned on either T1+T2 = (1, 2, 3, 4, 5,


6, 7, 8, 9)
side of the operator.

Membership It returns true if a particular item exists in the print (2 in T1) prints
True.
tuple otherwise false

Iteration The for loop is used to iterate over the tuple for i in T1:
print(i)
elements.
Output

1
2
3
4
5

Length It is used to get the length of the tuple. len(T1) = 5

Python Tuple inbuilt functions


SN Function Description

1 cmp(tuple1, It compares two tuples and returns true if tuple1 is greater than
tuple2) tuple2 otherwise false.

2 len(tuple) It calculates the length of the tuple.

3 max(tuple) It returns the maximum element of the tuple

4 min(tuple) It returns the minimum element of the tuple.

5 tuple(seq) It converts the specified sequence to the tuple.

Where use tuple?

Using tuple instead of list is used in the following scenario.


1. Using tuple instead of list gives us a clear idea that tuple data is constant
and must not be changed.
2. Tuple can simulate a dictionary without keys. Consider the following
nested structure, which can be used as a dictionary.
o [(101, "John", 22), (102, "Mike", 28), (103, "Dustin", 30)]
List vs. Tuple
SN List Tuple

1 The literal syntax of list is shown by the The literal syntax of the tuple is shown by the
[]. ().

2 The List is mutable. The tuple is immutable.

3 The List has the a variable length. The tuple has the fixed length.

4 The list provides more functionality than The tuple provides less functionality than the
a tuple. list.

5 The list is used in the scenario in which The tuple is used in the cases where we need
we need to store the simple collections to store the read-only collections i.e., the value
with no constraints where the value of of the items cannot be changed. It can be used
the items can be changed. as the key inside the dictionary.

6 The lists are less memory efficient than a The tuples are more memory efficient because
tuple. of its immutability.

Python Dictionary
Python Dictionary is used to store the data in a key-value pair format. The dictionary
is the data type in Python, which can simulate the real-life data arrangement where
some specific value exists for some particular key. It is the mutable data-structure. The
dictionary is defined into element Keys and values.

o Keys must be a single element


o Value can be any type such as list, tuple, integer, etc.
In other words, we can say that a dictionary is the collection of key-value pairs where
the value can be any Python object. In contrast, the keys are the immutable Python
object, i.e., Numbers, string, or tuple.

Creating the dictionary


The dictionary can be created by using multiple key-value pairs enclosed with the curly
brackets {}, and each key is separated from its value by the colon (:).The syntax to define
the dictionary is given below.

Syntax:

1. Dict = {"Name": "Tom", "Age": 22}

In the above dictionary Dict, The keys Name and Age are the string that is an
immutable object.

Let's see an example to create a dictionary and print its content.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)

Output
<class 'dict'>
Printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company':
'GOOGLE'}
Python provides the built-in function dict() method which is also used to create dictionary.
The empty curly braces {} is used to create empty dictionary.
1. # Creating an empty Dictionary
2. Dict = {}
3. print("Empty Dictionary: ")
4. print(Dict)
5. # Creating a Dictionary
6. # with dict() method
7. Dict = dict({1: 'Python', 2: 'T', 3:'Point'})
8. print("\nCreate Dictionary by using dict(): ")
9. print(Dict)
10. # Creating a Dictionary
11. # with each item as a Pair
12. Dict = dict([(1, 'Devansh'), (2, 'Sharma')])
13. print("\nDictionary with each item as a pair: ")
14. print(Dict)

Output:
Empty Dictionary:
{}

Create Dictionary by using dict():


{1: 'Python', 2: 'T', 3: 'Point'}

Dictionary with each item as a pair:


{1: 'Devansh', 2: 'Sharma'}

Accessing the dictionary values


We have discussed how the data can be accessed in the list and tuple by using the
indexing.

However, the values can be accessed in the dictionary by using the keys as keys are
unique in the dictionary.

The dictionary values can be accessed in the following way.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print("Name : %s" %Employee["Name"])
5. print("Age : %d" %Employee["Age"])
6. print("Salary : %d" %Employee["salary"])
7. print("Company : %s" %Employee["Company"])

Output:
<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE
Python provides us with an alternative to use the get() method to access the dictionary
values. It would give the same result as given by the indexing.

Adding dictionary values


The dictionary is a mutable data type, and its values can be updated by using the
specific keys. The value can be updated along with key Dict[key] = value. The update()
method is also used to update an existing value.

Note: If the key-value already present in the dictionary, the value gets updated.
Otherwise, the new keys added in the dictionary.

Let's see an example to update the dictionary values.

Example - 1:

1. # Creating an empty Dictionary


2. Dict = {}
3. print("Empty Dictionary: ")
4. print(Dict)
5. # Adding elements to dictionary one at a time
6. Dict[0] = 'Peter'
7. Dict[2] = 'Joseph'
8. Dict[3] = 'Ricky'
9. print("\nDictionary after adding 3 elements: ")
10. print(Dict)
11. # Adding set of values
12. # with a single Key
13. # The Emp_ages doesn't exist to dictionary
14. Dict['Emp_ages'] = 20, 33, 24
15. print("\nDictionary after adding 3 elements: ")
16. print(Dict)
17. # Updating existing Key's Value
18. Dict[3] = 'Python'
19. print("\nUpdated key value: ")
20. print(Dict)

Output:

Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}

Updated key value:


{0: 'Peter', 2: 'Joseph', 3: 'Python', 'Emp_ages': (20, 33, 24)}

Example - 2:

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Enter the details of the new employee....");
6. Employee["Name"] = input("Name: ");
7. Employee["Age"] = int(input("Age: "));
8. Employee["salary"] = int(input("Salary: "));
9. Employee["Company"] = input("Company:");
10. print("printing the new data");
11. print(Employee)

Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}

Updated key value:

Deleting elements using del keyword


The items of the dictionary can be deleted by using the del keyword as given below.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Deleting some of the employee data")
6. del Employee["Name"]
7. del Employee["Company"]
8. print("printing the modified information ")
9. print(Employee)
10. print("Deleting the dictionary: Employee");
11. del Employee
12. print("Lets try to print it again ");
13. print(Employee)

Output:
<class 'dict'>
printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company':
'GOOGLE'}
Deleting some of the employee data
printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined

The last print statement in the above code, it raised an error because we tried to print
the Employee dictionary that already deleted.

o Using pop() method

The pop() method accepts the key as an argument and remove the associated value.
Consider the following example.

1. # Creating a Dictionary
2. Dict = {1: 'Python', 2: 'Peter', 3: 'Thomas'}
3. # Deleting a key
4. # using pop() method
5. pop_ele = Dict.pop(3)
6. print(Dict)

Output: {1: 'Python', 2: 'Peter'}

Python also provides a built-in methods popitem() and clear() method for remove
elements from the dictionary. The popitem() removes the arbitrary element from a
dictionary, whereas the clear() method removes all elements to the whole dictionary.
Iterating Dictionary
A dictionary can be iterated using for loop as given below.

Example 1
# for loop to print all the keys of a dictionary

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. for x in Employee:
3. print(x)

Output:
Name
Age
salary
Company

Example 2
#for loop to print all the values of the dictionary
1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
2. for x in Employee:
3. print(Employee[x])

Output:
John
29
25000

Example - 3
#for loop to print the values of the dictionary by using values() method.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. for x in Employee.values():
3. print(x)
Output:
John
29
25000
GOOGLE

Example 4
#for loop to print the items of the dictionary by using items() method.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. for x in Employee.items():
3. print(x)

Output:
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')
Properties of Dictionary keys
1. In the dictionary, we cannot store multiple values for the same keys. If we pass more
than one value for a single key, then the value which is last assigned is considered as
the value of the key.

Consider the following example.

1. Employee={"Name":"John","Age":29,"Salary":25000,"Company":"GOOGLE","Name":"J
ohn"}
2. for x,y in Employee.items():
3. print(x,y)
Output:
Name John
Age 29
Salary 25000
Company GOOGLE

2. In python, the key cannot be any mutable object. We can use numbers, strings, or
tuples as the key, but we cannot use any mutable object like the list as the key in the
dictionary.

Consider the following example.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE",[100,20


1,301]:"Department ID"}
2. for x,y in Employee.items():
3. print(x,y)
Output:
Traceback (most recent call last):
File "dictionary.py", line 1, in
Employee = {"Name": "John", "Age": 29,
"salary":25000,"Company":"GOOGLE",[100,201,301]:"Department
ID"}
TypeError: unhashable type: 'list'

Built-in Dictionary functions


The built-in python dictionary methods along with the description are given below.

SN Function Description

1 cmp(dict1, It compares the items of both the dictionary and returns true if the first dictionary values
dict2) are greater than the second dictionary, otherwise it returns false.

2 len(dict) It is used to calculate the length of the dictionary.

3 str(dict) It converts the dictionary into the printable string representation.

4 type(variable) It is used to print the type of the passed variable.

Built-in Dictionary methods


The built-in python dictionary methods along with the description are given below.

SN Method Description

1 dic.clear() It is used to delete all the items of the dictionary.

2 dict.copy() It returns a shallow copy of the dictionary.

3 dict.fromkeys(iterable, value = Create a new dictionary from the iterable with the values equal to
None, /) value.

4 dict.get(key, default = "None") It is used to get the value specified for the passed key.

5 dict.has_key(key) It returns true if the dictionary contains the specified key.

6 dict.items() It returns all the key-value pairs as a tuple.


7 dict.keys() It returns all the keys of the dictionary.

8 dict.setdefault(key,default= "None") It is used to set the key to the default value if the key is not specified
in the dictionary

9 dict.update(dict2) It updates the dictionary by adding the key-value pair of dict2 to


this dictionary.

10 dict.values() It returns all the values of the dictionary.

11 len()

12 popItem()

13 pop()

14 count()

15 index()

Python Modules
A python module can be defined as a python program file which contains a python
code including python functions, class, or variables. In other words, we can say that
our python code file saved with the extension (.py) is treated as the module. We may
have a runnable code inside the python module.

Modules in Python provides us the flexibility to organize the code in a logical way.

To use the functionality of one module into another, we must have to import the
specific module.
Example
In this example, we will create a module named as file.py which contains a function
func that contains a code to print some message on the console.

Let's create the module named as file.py.


1. #displayMsg prints a message to the name being passed.
2. def displayMsg(name)
3. print("Hi "+name);

Here, we need to include this module into our main module to call the method
displayMsg() defined in the module named file.

Loading the module in our python code


We need to load the module in our python code to use its functionality. Python
provides two types of statements as defined below.

1. The import statement


2. The from-import statement

The import statement


The import statement is used to import all the functionality of one module into
another. Here, we must notice that we can use the functionality of any python source
file by importing that file as the module into another python source file.

We can import multiple modules with a single import statement, but a module is
loaded once regardless of the number of times, it has been imported into our file.

The syntax to use the import statement is given below.

1. import module1,module2,........ module n

Hence, if we need to call the function displayMsg() defined in the file file.py, we have
to import that file as a module into our module as shown in the example below.

Example:
1. import file;
2. name = input("Enter the name?")
3. file.displayMsg(name)
Output:
Enter the name?John
Hi John
The from-import statement
Instead of importing the whole module into the namespace, python provides the
flexibility to import only the specific attributes of a module. This can be done by using
from? import statement. The syntax to use the from-import statement is given below.

1. from < module-name> import <name 1>, <name 2>..,<name n>

Consider the following module named as calculation which contains three functions
as summation, multiplication, and divide.

calculation.py:

1. #place the code in the calculation.py


2. def summation(a,b):
3. return a+b
4. def multiplication(a,b):
5. return a*b;
6. def divide(a,b):
7. return a/b;

Main.py:

1. from calculation import summation


2. #it will import only the summation() from calculation.py
3. a = int(input("Enter the first number"))
4. b = int(input("Enter the second number"))
5. print("Sum = ",summation(a,b)) #we do not need to specify the module name while
accessing summation()

Output:

Enter the first number10


Enter the second number20
Sum = 30

The from...import statement is always better to use if we know the attributes to be


imported from the module in advance. It doesn't let our code to be heavier. We can
also import all the attributes from a module by using *.

Consider the following syntax.


from <module> import *

Renaming a module
Python provides us the flexibility to import some module with a specific name so that
we can use this name to use that module in our python source file.

The syntax to rename a module is given below.

1. import <module-name> as <specific-name>


Example
1. #the module calculation of previous example is imported in this example as cal.
2. import calculation as cal;
3. a = int(input("Enter a?"));
4. b = int(input("Enter b?"));
5. print("Sum = ",cal.summation(a,b))

Output:

Enter a?10
Enter b?20
Sum = 30

Python Math Module


Python math module is defined as the most famous mathematical functions, which
includes trigonometric functions, representation functions, logarithmic functions, etc.
Furthermore, it also defines two mathematical constants, i.e., Pie and Euler number,
etc.

Pie (n): It is a well-known mathematical constant and defined as the ratio of


circumstance to the diameter of a circle. Its value is 3.141592653589793.

Euler's number(e): It is defined as the base of the natural logarithmic, and its value is
2.718281828459045.

There are different math modules which are given below:

math.log()
This method returns the natural logarithm of a given number. It is calculated to the
base e.

Example
1. import math
2. number = 2e-7 # small value of of x
3. print('log(fabs(x), base) is :', math.log(math.fabs(number), 10))
Output:
log(fabs(x), base) is : -6.698970004336019

math.log10()
This method returns base 10 logarithm of the given number and called the standard
logarithm.

Example

1. import math
2. x=13 # small value of of x
3. print('log10(x) is :', math.log10(x))

Output:
log10(x) is : 1.1139433523068367

math.exp()
This method returns a floating-point number after raising e to the given number.

Example

import math
number = 5e-2 # small value of of x
print('The given number (x) is :', number)
print('e^x (using exp() function) is :', math.exp(number)-1)

Output:
The given number (x) is : 0.05
e^x (using exp() function) is : 0.05127109637602412

math.pow(x,y)
This method returns the power of the x corresponding to the value of y. If value of x is
negative or y is not integer value than it raises a ValueError.

Example
1. import math
2. number = math.pow(10,2)
3. print("The power of number:",number)

Output:
The power of number: 100.0

math.floor(x)
This method returns the floor value of the x. It returns the less than or equal value to
x.

Example:
1. import math
2. number = math.floor(10.25201)
3. print("The floor value is:",number)

Output:
The floor value is: 10

math.ceil(x)
This method returns the ceil value of the x. It returns the greater than or equal value
to x.

1. import math
2. number = math.ceil(10.25201)
3. print("The floor value is:",number)

Output:

The floor value is: 11

math.fabs(x)
This method returns the absolute value of x.

import math
number = math.fabs(10.001)
print("The floor absolute is:",number)
Output:
The absolute value is: 10.001
math.factorial()
This method returns the factorial of the given number x. If x is not integral, it raises
a ValueError.

Example

1. import math
2. number = math.factorial(7)
3. print("The factorial of number:",number)

Output:
The factorial of number: 5040

math.modf(x)
This method returns the fractional and integer parts of x. It carries the sign of x is float.

Example

1. import math
2. number = math.modf(44.5)
3. print("The modf of number:",number)
Output:
The modf of number: (0.5, 44.0)
Python provides the several math modules which can perform the complex task in single-line
of code. In this tutorial, we have discussed a few important math modules.

Python Random module


The Python random module functions depend on a pseudo-random number
generator function random(), which generates the float number between 0.0 and 1.0.

There are different types of functions used in a random module which is given below:

random.random()
This function generates a random float number between 0.0 and 1.0.

random.randint()
This function returns a random integer between the specified integers.
random.choice()
This function returns a randomly selected element from a non-empty sequence.

Example

1. # importing "random" module.


2. import random
3. # We are using the choice() function to generate a random number from
4. # the given list of numbers.
5. print ("The random number from list is : ",end="")
6. print (random.choice([50, 41, 84, 40, 31]))

Output:
The random number from list is: 84

random.shuffle()
This function randomly reorders the elements in the list.

random.randrange(beg,end,step)
This function is used to generate a number within the range specified in its argument.
It accepts three arguments, beginning number, last number, and step, which is used
to skip a number in the range. Consider the following example.

1. # We are using randrange() function to generate in range from 100


2. # to 500. The last parameter 10 is step size to skip
3. # ten numbers when selecting.
4. import random
5. print ("A random number from range is : ",end="")
6. print (random.randrange(100, 500, 10))

Output:
A random number from range is : 290

random.seed()
This function is used to apply on the particular random number with the seed
argument. It returns the mapper value. Consider the following example.

1. # importing "random" module.


2. import random
3. # using random() to generate a random number
4. # between 0 and 1
5. print("The random number between 0 and 1 is : ", end="")
6. print(random.random())
7. # using seed() to seed a random number
8. random.seed(4)

Output:
The random number between 0 and 1 is : 0.4405576668981033

Python Packages
We usually organize our files in different folders and subfolders based on some criteria,
so that they can be managed easily and efficiently. For example, we keep all our games
in a Games folder and we can even subcategorize according to the genre of the game
or something like this. The same analogy is followed by the Python package.
A Python module may contain several classes, functions, variables, etc. whereas a
Python package can contains several module. In simpler terms a package is folder that
contains various modules as files.

Creating Package
Let’s create a package named mypckg that will contain two modules mod1 and
mod2. To create this module follow the below steps –
 Create a folder named mypckg.
 Inside this folder create an empty Python file i.e. __init__.py
 Then create two modules mod1 and mod2 in this folder.

Mod1.py

def gfg():
print("Welcome to GFG")

Mod2.py

def sum(a, b):


return a+b

The hierarchy of the our package looks like this –

mypckg
|
|
---__init__.py
|
|
---mod1.py
|
|
---mod2.py
Understanding __init__.py
__init__.py helps the Python interpreter to recognise the folder as package. It also
specifies the resources to be imported from the modules. If the __init__.py is empty
this means that all the functions of the modules will be imported. We can also specify
the functions from each module to be made available.
For example, we can also create the __init__.py file for the above module as –

__init__.py

from .mod1 import gfg


from .mod2 import sum

This __init__.py will only allow the gfg and sum functions from the mod1 and mod2
modules to be imported.
Import Modules from a Package
We can import these modules using the from…import statement and the dot(.)
operator.
Syntax:

import package_name.module_name

Example: Import Module from package

We will import the modules from the above created package and will use the
functions inside those modules.

from mypckg import mod1


from mypckg import mod2

mod1.gfg()
res = mod2.sum(1, 2)
print(res)
Output:

Welcome to GFG
3
We can also import the specific function also using the same syntax.

Example: Import Specific function from the module

from mypckg.mod1 import gfg


from mypckg.mod2 import sum

gfg()
res = sum(1, 2)
print(res)

Output:
Welcome to GFG
3

What is Composition (Has-A Relation)?


It is one of the fundamental concepts of Object-Oriented Programming. In
this concept, we will describe a class that references to one or more objects
of other classes as an Instance variable. Here, by using the class name or by
creating the object we can access the members of one class inside another
class. It enables creating complex types by combining objects of different
classes. It means that a class Composite can contain an object of another
class Component. This type of relationship is known as Has-A Relation.
In the above figure Classes are represented as boxes with the class
name Composite and Component representing Has-A relation between
both of them.

Syntax

class A :

# variables of class A
# methods of class A
...
...

class B :
# by using "obj" we can access member's of class A.
obj = A()

# variables of class B
# methods of class B

...
...

Example :

class Component:

# composite class constructor


def __init__(self):
print('Component class object created...')

# composite class instance method


def m1(self):
print('Component class m1() method executed...')

class Composite:

# composite class constructor


def __init__(self):

# creating object of component class


self.obj1 = Component()

print('Composite class object also created...')

# composite class instance method


def m2(self):

print('Composite class m2() method executed...')

# calling m1() method of component class


self.obj1.m1()

# creating object of composite class


obj2 = Composite()

# calling m2() method of composite class


obj2.m2()
Output
Component class object created...
Composite class object also created...
Composite class m2() method executed...
Component class m1() method executed...
Explanation:
 In the above example, we created two
classes Composite and Component to show the Has-A Relation among
them.
 In the Component class, we have one constructor and an instance
method m1().
 Similarly, in Composite class, we have one constructor in which we
created an object of Component Class. Whenever we create an object
of Composite Class, the object of the Component class is automatically
created.
 Now in m2() method of Composite class we are calling m1() method
of Component Class using instance variable obj1 in which reference
of Component Class is stored.
 Now, whenever we call m2() method of Composite
Class, automatically m1() method of Component Class will be called.

Source distribution and built distribution in python


Python is all about Distribution. It can be defined as the collection of files that
together allows to build, package and distribute a module. Once a
distribution exists in a system, it can easily be installed. Also, it can be
shared with PyPI(Python package index) community so that other people can
use your distribution.
To make it more clear consider Anaconda, which is an open-source
distribution of python and R programming language. It contains python,
various libraries(numpy, pandas, matplotlib tec), IDE’s (like Spyder, Jupyter
Notebook) and package manager conda as well as pip inside it, which
enables a user to use the resources for various machine learning tasks,
without downloading them explicitly.
There are two types of distribution in python:
1. Source distribution(sdist)– It contains setup.py (which contains
information about module/metadata), the source files of module/script
(.py files or .c/.cpp for binary modules), data files, etc. The result is an
archive that can then be used to recompile everything on any platform like
linux, windows, and mac.
2. Built distribution(bdist)– It creates distribution which
includes .pyc files(python bytecode), .so/.dll/.dylib for binary
modules, .exe if using py2exe(extension of python, which can be used to
convert scripts to exe form on windows, and can be used without
installation of python) on Windows, data files… but no setup.py. The
result is an archive that is specific to a platform (for example linux-
x86_64) and to a version of Python. That can be installed and then used
directly by extracting it into the root of your filesystem (executables are in
/usr/bin (or equivalent), data files in /usr/share, modules in
/usr/lib/pythonX.X/site-packages/…).

setup.py
setup.py is a python file, which usually tells the system that, the
module/package you are about to install has been packaged and distributed
using Distutils, which is the standard for distribution of python modules. It is
the most important file. It’s the file where various aspects of your project are
configured. The primary feature of setup.py is that it contains a
global setup() function. The keyword arguments to this function are how
specific details of your project are defined.
Making a basic setup.py file.
1. # import setup function from
2. # python distribution utilities
3. from distutils.core import setup
4.
5. # Calling the setup function
6. setup(
7. name = 'nesters',
8. version = '1.0.0',
9. py_modules = ['addition'],
10. author ='a geek',
11. author_email = 'ageek@gmail.com',
12. url = 'https;//ageek.com',
13. description = 'a simple program to add two numbers',
14. keywords='adds two numbers',
15. )

Let us see what different arguments of setup function do:


 name: It is the name of the project. The package will be listed by this
name on PyPI.
 version: It is a string which can specify the current version of the project.
It is totally your choice how you want to set the scheme of the series of
versions (‘1.0’ or ‘0.1’ or even ‘0.0.1’ can also be used). This version is
displayed on PyPI for each release if the project is published. Every-time
a new version is uploaded, you will have to change this argument as well.
 description: A short description about the package. Long description
argument can be used for long descriptions.
 url: A homepage URL for the project. This makes it easier for people to
follow or contribute to the project.
 author, author_email: Details about the author.
 license: specify the type of license which is used.
 classifiers: It is a list of strings which can specify more details about the
project like its development status, topic, license and supported python
versions for the project.
 install_requires: It can be used to specify what third-party libraries your
package needs to run. These dependencies will be installed by pip when
someone installs your package.
 keywords: List keywords to describe the project.
Let’s create an addition.py file that contains the code for the addition of two
numbers. Create this file in notepad and save it as addition.py.
def addition():
n = 5
print("addition of two numbers")
while(n>= 0):
a, b = input("enter two numbers: ").split()
try:
value1 = int(a)
value2 = int(b)
break
except e:
print("re enter numbers" )
sum = value1 + value2
print("sum of two numbers is :", sum)

Making a Source distribution:


 To make a source distribution, firstly make a folder and copy setup.py and
addition.py scripts into that folder(let’s name it as nester). Then open
terminal and change the current directory to the directory of the folder for
example: if it is in the desktop – C:\Users\HP PC\Desktop\nester.
 Lastly type setup.py sdist. This will make a source distribution.
After the execution of the following command, a dist folder which will contain
a nester1-1.1.0.tar file in it and a MANIFEST FILE which contains the list of
python(.py) files built by the sdist command, will be formed in the same
source folder(nester).
While creating a source distribution many formats can be specified using --
format option.
For example:

python setup.py sdist --formats=gztar,zip

Different formats are:

Format Description

zip zip file (.zip)

gztar gzip’ed tar file (.tar.gz)

bztar bzip2’ed tar file (.tar.bz2)

xztar xz’ed tar file (.tar.xz)

ztar compressed tar file (.tar.Z)

tar tar file (.tar)

Making a built distribution:


 Repeat step 1 from Source distribution.
 Lastly type setup.py bdist. This will create a built distribution.
After the execution of the following command, two folders will be created :
1. dist – which contains the “nester1-1.1.0.win-amd64” in winRarZip archive
format and on extracting the zip file, an “addition.pyc” file will be found in
__pycache__ folder, which is the compiled(byte code) version of your
“addition.py” file, specific to the system.
2. build – which contains library folder and “addition.py” file inside it.
While creating a built distribution many formats can be specified using --
format option.
For example:
python setup.py bdist --format=zip
Different formats are:

Format Description

zip zip file (.zip)

gztar compressed tar file (.tar.Z)

ztar bzip2’ed tar file (.tar.bz2)

tar tar file (.tar)

rpm RPM

pkgtool Solaris pkgtool

sdux Solaris pkgtool

wininst self-extracting ZIP file for Windows

msi Microsoft Installer

Source :

1. https://www.geeksforgeeks.org/python-programming-language/?ref=shm
2. https://www.javatpoint.com/python-tutorial

You might also like