Unit 2 Python Programming Diploma-1
Unit 2 Python Programming Diploma-1
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
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.
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
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
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 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:
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 [].
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
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.
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
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.
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
#Output:
The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings.
Iteration The for loop is used to iterate over the list for i in l1:
print(i)
elements.
Output
1
2
3
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.
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
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.
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.
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.
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.
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
1 cmp(tuple1, It compares two tuples and returns true if tuple1 is greater than
tuple2) tuple2 otherwise false.
1 The literal syntax of list is shown by the The literal syntax of the tuple is shown by the
[]. ().
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.
Syntax:
In the above dictionary Dict, The keys Name and Age are the string that is an
immutable object.
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:
{}
However, the values can be accessed in the dictionary by using the keys as keys are
unique in the dictionary.
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.
Note: If the key-value already present in the dictionary, the value gets updated.
Otherwise, the new keys added in the dictionary.
Example - 1:
Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}
Example - 2:
Empty Dictionary:
{}
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.
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)
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
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.
Example 4
#for loop to print the items of the dictionary by using items() method.
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.
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.
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.
SN Method Description
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.
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
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.
Here, we need to include this module into our main module to call the method
displayMsg() defined in the module named 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.
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.
Consider the following module named as calculation which contains three functions
as summation, multiplication, and divide.
calculation.py:
Main.py:
Output:
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.
Output:
Enter a?10
Enter b?20
Sum = 30
Euler's number(e): It is defined as the base of the natural logarithmic, and its value is
2.718281828459045.
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:
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.
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
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.
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.
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
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
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
We will import the modules from the above created package and will use the
functions inside those modules.
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.
gfg()
res = sum(1, 2)
print(res)
Output:
Welcome to GFG
3
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:
class Composite:
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. )
Format Description
Format Description
rpm RPM
Source :
1. https://www.geeksforgeeks.org/python-programming-language/?ref=shm
2. https://www.javatpoint.com/python-tutorial