Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

An

Industrial Training Report on


PYTHON
At
Aryan Infomatrix Pvt. Ltd, Jaipur

Submitted in partial fulfillment of the requirements


for the award of the degree of

Bachelor of Technology In
Computer Engineering

(Session 2023-24)

Submitted to: Submitted by:

Mr. Rohit SinghRajput Ashutosh


Upaddhyay
Assistant Professor PCE20CCS033
(Coordinators- Industrial Training) Semester:7CS-A

DEPARTMENT OF COMPUTER
ENGINEERING POORNIMA COLLEGE OF
ENGINEERING, JAIPUR RAJASTHAN
TECHNICAL UNIVERSITY, KOTA
OCTOBER, 2023
DECLARATION

I hereby declare that the work which is being presented in the Industrial Training report
titled Python in partial fulfillment for the award of the Degree of Bachelor of
Technology in Computer Engineering and submitted to the Department of Computer
Engineering, Poornima College of Engineering, Jaipur, is an authentic record of my
own work carried out at Aryan Infomatrix Pvt. Ltd. during the session 2023-24.
I have not submitted the matter presented in this report anywhere for the award of any
other Degree.

Signature of the Student


Name: AtharavPorwal
Reg. No.: PCE20CCS033
Place: Jaipur
Date: 30/10/2023

i
ii
DEPARTMENT OF COMPUTER ENGINEERING
Date: 30/10/2023

CERTIFICATE

This is to certify that Industrial Training report Python developer has been

submitted by Ashutosh Upaddhyay, PCE20CCS033 in partial fulfillment

for the award of the Degree of Bachelor of Technology in Computer

Engineering during the session 2022-23. The industrial training work is

found satisfactoryand approved for submission.

Mr. Rohit SinghRajput Dr. Nikita Jain


Assistant Professor Head of Department
Coordinators- Industrial Training Department of Computer
Engineering

iii
ACKNOWLEDGEMENT

I would like to convey my profound sense of reverence and admiration to my


supervisor Ashwani Prajapati, Python and Unity Developer, for his intense concern,
attention, priceless direction, guidance and encouragement throughout this
internship.

I extend my heartiest gratitude to Mr. Rohit Singh Rajput, Coordinator-Industrial


Training, who extended their cooperation to steer the topic towards its successful
completion.

My special heartfelt gratitude goes to Dr. Nikita Jain, Deputy Head (Academics),
Department of Computer Engineering, Poornima College of Engineering, for
unvarying support, guidance and motivation during the course of this research.

I am grateful to Dr. Mahesh Bundele, Director, Poornima College of Engineering for


his helping attitude with a keen interest in completing this training work in time.

I would like to express my deep sense of gratitude towards management of Poornima


College of Engineering including Dr. S. M. Seth, Chairman Emeritus, Poornima
Group and former Director NIH, Roorkee, Shri Shashikant Singhi, Chairman,
Poornima Group, Mr. M. K.M. Shah, Director Admin & Finance, Poornima Group
and Ar. Rahul Singhi, Director Poornima Group for establishment of institute and
providing facilities my studies.

I am deeply thankful to my parents and all other family members for their blessings
and inspiration. At last, but not least I would like to give special thanks to God who
enabled me to complete my training work on time.

Ashutosh Upaddhyay(PCE20CCS033)

iv
TABLE OF CONTENTS

PARTICULARS PAGE NO.

Title Page 0
Declaration i
Training Certificate from Company ii
Certificate by the Department iii
Acknowledgment iv
Table of Contents v-vi
List of Tables vii
List of Figures viii
Abstract 9
Chapter 1: Introduction 10-12
1.1 About company 10
1.2 Training Platform 11
1.3 Training Starting Date 11
1.4 Training Ending Date 11
1.5 Total Training Duration 11
1.6 Date of Certification 12
1.7 Conclusion 12

v
Chapter 2: Python 13-22
2.1 Introduction 13
2.2 Scripting Language 14
2.3 Object Oriented Programming 14
2.4 History 14-15
2.5 Operators in Python 16
2.6 Types of Operators in Python 16-22

Chapter 3: Collection in Python 23-27


3.1 Scalar Data Types in Python 23-25
3.2 Sequence Data Types 25-27
Chapter 4: Conditionals and Loops in Python 28-35
4.1 Introduction 28
4.2 If Statement 28
4.3 If Else Statement 29
4.4 Elif Statement 29-30
4.7 Python Loops 30-32
4.8 Loops Control Statement 33-35
Chapter 5: Functions in Python 36-38
5.1 Introduction 36
5.2 Calling a Function 36-37
5.3 Function Arguments 37
5.4 The return Statement 38
Chapter 6:Chatbot 38-43
6.1 Types of chatbot 38
6.2 Chatbot in today’s generation
39-40
6.3 Chatterbot library
6.4 How to make a chatbot in python?
40-41
42-43
References 44

vi
LIST OF TABLES

Table No. Title Page No.


Table-1 Python Arithmetic Operators
10
Table-2 Python Comparison Operators
11
Table-3 Python Assignment Operators
12
Table-4 Python Bitwise Operators
13
Table-5 Python Logical Operators
13
Table-6 Python Membership Operators
14
Table-7 Python Operators Precedence
15
Table-8 Loop Type & Description
26
Table-9 Control Statement & Description
38

vii
LIST OF FIGURES

Figure Figure Descriptions Page No.


No.

Fig.-1 Focused Area of Company (RAMS) 2

Fig.-2 Basic Information about Company 3

Fig.-3 Picture Inside Company 4

Fig.-4 Picture Inside Company 5

Fig.-5 Company’s Website 5

Fig.-6 Python Operators 10

Fig.-7 Data Types in Python 16

Fig.-8 Loops Flow 25

viii
ABSTRACT

The objective of the practical training is to learn something about industries practically
and to be familiar with a working style of a technical worker to adjust according to
industrial environment. This report deals with the equipment’s their general operating
principle.

Python, an interpreted language which was developed by Guido Van Rossum came
into implementation in1989.The language supports both object oriented and procedure
oriented approach. Python is designed to be a highly extensible language. Python
works on the principle of ―there is only one obvious way to do a task‖ rather than
―there is more than one way to solve a particular problem‖. Python is very easy to
learn and implement. The simpler syntax, uncomplicated semantics and approach with
which Python has been developed makes it easier to learn. A large number of python
implementation and extensions have been developed since its inception.

Training Cover provides both three weeks as well as three months industrial training in
Python.

Python is divided into two parts as ―Core Python and ―Advance Python.
Accordingly, all the basic and advanced topics are discussed in both of the modules.

1
CHAPTER 1
INTRODUCTION

1.1 Introduction of Company:


Aryan Infomatrix Pvt. Ltd. is privately held, government registered software
development organization based in India with a global customer footprint. We have a
team of 50 + People spawning at Jaipur in India. Our team comprises of young and
highly motivated professionals. We design, develop, test and deliver amazing games
and apps for the mobile platform.
Aryan Infomatrix Pvt. Ltd.. is a Jaipur based IT enterprise, offering tech solutions to
grow instantly. We are pioneer to offer customized solutions according to your
requirements. We have started revolutionizing the globe in 2013 and from the time, we
have grown significantly by showing our potential towards excellence. We have a
dedicated team of 50+ who always passionate to perform and believe in quality
deliverance all the time. In the era of digitalization, be ahead and hire specialized
developers from us and get one of the best customized solutions for your business at
an affordable price.

Fig.-1

2
Fig.-2

1.1.1 Training Technology and Platform:


I got the training there on Python. I have worked on Jupytor Notebook and PyCharm
as well to some extent.

1.2 PYTHON
I got the training there on Python. Python is a widely used high-level, general-purpose,
interpreted, dynamic programming language. Its design philosophy emphasizes code
readability, and its syntax allows programmers to express concepts in fewer lines of
code than would be possible in languages such as C++ or Java. The language provides
constructs intended to enable clear programs on both a small and large scale. Python
supports multiple programming paradigms, including object-oriented, imperative and
functional programming or procedural styles. It features a dynamic type system and
automatic memory management and has a large and comprehensive standard library.
3
Python interpreters are available for installation on many operating systems, allowing
Python code execution on a wide variety of systems.
1.2.1 Training Starting Date:
It was a good experience to work there along with the Aryan Infomatrix team. I
reported there on 1st August, 2023.
1.2.2 Training Ending Date:
My Training there at Aryan Infomatrix Pvt. Ltd. Formally got completed after a
fortnight on 15th Spetember 2023.
1.2.3 Total Training Duration:
My training was originally for a fortnight but on my request they extended it to 45 days.
1.2.4 Date of Certification:
I got my training certificate on 30th of September 2023 although in digital format.

1.2.5 Conclusion
This was my first training as an Engineering Student that too in the time of Pandemic,
but I enjoyed working with the Aryan Infomatrix Pvt. Ltd teams and being there. The
people are very much cooperative and helpful. Apart from my technical learning on
Python, I also get to learn may other behavioral things of a corporate life, the schedule,
and the meetings. I also got to know about different things. I had some knowledge
about DB tool SALSFORCE and Virtual Reality as well. So, from my perspective it
was overall a fruitful trip to the Corporate Life.

4
Chapter 2
PYTHON

2.1 Introduction
Python is a widely used high-level, general-purpose, interpreted, dynamic
programming language. Its design philosophy emphasizes code readability, and its
syntax allows programmers to express concepts in fewer lines of code than would be
possible in languages such as C++ or Java. The language provides constructs intended
to enable clear programs on both a small and large scale. Python supports multiple
programming paradigms, including object-oriented, imperative and functional
programming or procedural styles. It features a dynamic type system and automatic
memory management and has a large and comprehensive standard library. Python
interpreters are available for installation on many operating systems, allowing Python
code execution on a wide variety of systems.
2.2 Scripting Language
A scripting or script language is a programming language that supports scripts,
programs written for a special run-time environment that automate the execution of
tasks that could alternatively be executed one-by-one by a human operator. Scripting
languages are often interpreted (rather than compiled). Primitives are usually the
elementary tasks or API calls, and the language allows them to be combined into more
complex programs.
2.3 Object Oriented Programming Language
Object-oriented programming (OOP) is a programming paradigm based on the concept
of "objects", which may contain data, in the form of fields, often known as attributes;
and code, in the form of procedures, often known as methods. A distinguishing feature
of objects is that an object's procedures can access and often modify the data fields of
the object with which they are associated (objects have a notion of "this" or "self"). In
5
OO programming, computer.

Programs are designed by making them out of objects that interact with one another.
There is significant diversity in object oriented programming, but most popular
languages are class- based, meaning that objects are instances of classes, which
typically also determines their type.
2.4 History
Python was conceived in the late 1980s, and its implementation was started in
December 1989 by Guido van Rossum at CWI in the Netherlands as a successor to the
ABC language (itself inspired by SETL) capable of exception handling and interfacing
with the Amoeba operating system. Van Rossum is Python's principal author, and his
continuing central role in deciding the direction of Python is reflected in the title given
to him by the Python community, benevolent dictator for life (BDFL).
• Python Features
• Python Features #Easy-to-learn Python has few keywords, simple structure,
and a clearly defined syntax. This allows the student to pick up the language
quickly.
• Easy-to-read Python code is more clearly defined and visible to the eyes.
• Easy-to-maintain Python's source code is fairly easy-to-maintain
• A broad standard library Python's bulk of the library is very portable and
crossplatform compatible on UNIX, Windows, and Macintosh.
• Interactive Mode Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
• Portable Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
• Extendable You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more

6
efficient.
• Databases Python provides interfaces to all major commercial databases.
• GUI Programming Python supports GUI applications that can be created
and ported to many system calls, libraries and windows systems, such as
Windows MFC, Macintosh, and the X Window ...
• Scalable Python provides a better structure and support for large programs
than shell scripting.

Apart from the above-mentioned features, Python has a big list of good features, few are
listed below −

• It supports functional and structured programming methods as well as


OOP.
• It can be used as a scripting language or can be compiled to byte-code
for building large applications.
• It provides very high-level dynamic data types and supports dynamic type
checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and
Java.
2.5 What are operators in python?
Operators are special symbols in Python that carry out arithmetic or logical
computation. The value that the operator operates on is called the operand.
For example:
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator.
2.6 Types of Operators
Python language supports the following types of operators.
• Arithmetic Operators
• Comparison (Relational) Operators
7
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators

• Identity Operators
Fig.-6
Let us have a look on all operators one by one.
2.6.1 Python Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then –
Operator Description Example
+ Addition Adds values on either side of the a + b = 30
operator.
Subtracts right hand operand from left
- Subtraction hand operand. a – b = -10
* Multiplication Multiplies values on either side of the a * b = 200
operator
Divides left hand operand by right
/ Division hand operand b/a=2
Divides left hand operand by right hand
% Modulus b%a=0
operand and returns remainder
Performs exponential (power) a**b =10 to
** Exponent
calculation on operators the power
20
8
2.6.2 Python Comparison Operators
These operators compare the values on either sides of them and decide the relation
among them. They are also called Relational operators.

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example


If the values of two operands are equal,
== (a == b) is not
then the condition becomes true. true.
If values of two operands are not equal,
!= (a != b) is true.
then condition becomes true.
(a <> b) is true.
If values of two operands are not equal,
<> This is similar to
then condition becomes true.
!= operator.
If the value of left operand is greater
> than the value of right operand, then (a > b) is not true.
condition becomes true.
If the value of left operand is less than
< the value of right operand, then (a < b) is true.
condition becomes true.
If the value of left operand is greater
>= than or equal to the value of right (a >= b) is not
operand, then condition becomes true. true.
If the value of left operand is less than
<= or equal to the value of right operand, (a <= b) is true.
then condition becomes true.
Table-2

2.6.3 Python Assignment Operators


Assume variable a holds 10 and variable b holds 20, then –

9
Operator Description Example
c=a+b
Assigns values from right side operands
= assigns value
to left side operand
of a + b into c

It adds right operand to the left operand c += a is


+= Add AND
and assign the result to left operand equivalent to
c=c+a

-= Subtract It subtracts right operand from the left c -= a is


AND operand and assign the result to left equivalent
operand to c = c - a

*= Multiply It multiplies right operand with the left c *= a is


AND operand and assign the result to left equivalent to
operand c=c*a

It divides left operand with the right c /= a is


/= Divide AND
operand and assign the result to left equivalent
operand to c = c / a
c %= a is
%= Modulus It takes modulus using two operands and
equivalent to c
AND assign the result to left operand
=c
%a
c **= a is
**= Exponent Performs exponential (power)
equivalent to c
AND calculation on operators and assign
=c
value to the left operand ** a

//= It performs floor division on operators c //= a is


Floor and assign value to the left operand equivalent
Divisio to c = c // a
n
Table-3
2.6.4 Python Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60;

10
and b = 13; Now in the binary format their values will be 0011 1100 and 0000 1101
respectively. Following table lists out the bitwise operators supported by Python
language with an example each in those, we use the above two variables (a and b) as
operands − a = 0011 1100 b = 0000 1101

a&b = 0000 1100


a|b = 0011 1101 a^b= 0011 0001
There are following Bitwise operators supported by Python language
Operator Description Example
Operator copies a bit to the result if it (a & b)
& Binary AND
exists in both operands (means
0000
1100)
(a | b) = 61
| Binary OR It copies a bit if it exists in either operand. (means
0011
1101)
(a ^ b) =
It copies the bit if it is set in one
^ Binary XOR 49 (means
operand but not both.
0011
0001)

(~a ) = -61
(means 1100
~ Binary Ones It is unary and has the effect of 'flipping' 0011 in 2's
Complement bits. complement
form due to a
signed binary
number.
a << 2 = 240
<< Binary The left operands value is moved left
(means 1111
Left by the number of bits specified by the
0000)
Shift right operand.

11
a >> 2 = 15
>> Binary The left operands value is moved right
(means 0000
Right by the number of bits specified by the
1111)
Shift right operand.
Table-4
2.6.5 Python Logical Operators
There are following logical operators supported by Python language. Assume variable
a holds 10 and variable b holds 20 then
Operator Description Example
and Logical If both the operands are true then
(a and b) is true.
AND condition becomes true.
If any of the two operands are non-zero
or Logical OR (a or b) is true.
then condition becomes true.
not Logical Not (a and b)
Used to reverse the logical state of its
NOT operand. is false.
Table-5

2.6.6 Python Membership Operators


Python‘s membership operators test for membership in a sequence, such as strings, lists,
or tuples. There are two membership operators as explained below –
Operator Description Example
x is y, here is
Evaluates to true if the variables on
results in 1 if
is either side of the operator point to the
id(x) equals
same object and false otherwise.
id(y).
x is not y, here
Evaluates to false if the variables on
is not results
is not either side of the operator point to the
in 1 if id(x) is
same object and true otherwise.
not equal to
id(y).
Table-6

12
2.7 Python Operators Precedence
The following table lists all operators from highest precedence to lowest.
Sr.No. Operator & Description
**
1 Exponentiation (raise to the power)
~+-
2 Complement, unary plus and minus (method names for
the last two are +@ and -@)
* / % //
3 Multiply, divide, modulo and floor division
+-
4 Addition and subtraction
>> <<
5
Right and left bitwise shift
&
6
Bitwise 'AND'

^|
7
Bitwise exclusive `OR' and regular `OR'
<= < > >=
8
Comparison operators
9 <> == !=
Equality operators
= %= /= //= -= += *= **=
10
Assignment operators
is is not
11
Identity operators
in not in
12
Membership operators
not or and
13
Logical operators

13
Table-7

In Python, operators are special symbols that designate that some sort of computation
should be performed.
Python supports the usual logical conditions from mathematics:

• Equals: a = = b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and
loops. We will see it in next chapter.

14
CHAPTER 3
COLLECTION IN PYTHON

Collections in python are basically container data types, namely list, sets, tuples
and dictionary. They have different characteristics based on the declaration and the
usage.

• A list is declared in square brackets, it is mutable, stores duplicate values and


elements can be accessed using indexes.
• A tuple is ordered and immutable in nature, although duplicate entries can be
there inside a tuple.
• A set is unordered and declared in square brackets. It is not indexed and does
not have duplicate entries as well.
• A dictionary has key value pairs and is mutable in nature. We use square
brackets to declare a dictionary.
These are the python‘s general purpose built-in container data types. But as we all
know, python always has a little something extra to offer. It comes with a python
module named collections which has specialized data structures.

15
Fig.-7
What is Data types in Python?
Data types are used in Python to classify a particular type of data. It is important
because the specific type of information you use will determine which values you can
assign and what you can do. Every Python value has a data type. In Python
programming, everything is an object, data types are classes, and variables are instance
(object) of these classes.
The instance () function is also used to check whether an object belongs to a specific
class. There are several data types in Python. Let‘s take a look at the data types in
Python.

3.1 Scalar Data Types in Python


Scalar data types store single numbers, Boolean, and character, while composite
types store multiple values, e.g., recording and collecting. In Python, the most
commonly used scalar types are:

3.1.1 Boolean Data Type


There are two built-in Boolean data types in Python: True or False, and the Python
type is Bool. These values are used in conditions, comparisons, and structures that
require the representation of truth or falsehood.
Note: The capital is ‗T‘ and ‗F.‘ True and false Booleans are not valid, and Python will
throw an error for them.
3.1.2 Number Data Types
Python has three numerical data types: integers, floats, and complex numbers fall into
the Python numbers category. They define as int, float, and complex classes in Python.
They are immutable data types, meaning that a new object changes the value of several
data types. Python can tell whether the number is an integer or float due to a decimal
point presence or absence. By its standard form a + bj, it recognizes a complex number.
Therefore a number should not be declared as a specific type.
16
3.2 Sequence Data Type in Python
A sequence is an ordered collection of similar or different types of data. The following
integrated sequence data types are available in Python:
3.2.1 Python List
An ordered list object is a collection of series of values. It is one of the most
commonly used and highly flexible data types in Python. Not all items in a list
of the same type. It is quite straightforward to declare a list. Comma-separated
items are included in brackets[].

a = [1, 1.1, 'Computers']

All lists in Python are zero-based indexed. When the member or the length of
a list is referenced, the number of list elements is always the number plus one.
3.2.2 Python Tuple
A tuple is an ordered sequence of items, like a list. The only difference is that
tuples are immutable. Tuples cannot be modified once they have been created.
Tuples are used to write protection data and are usually faster than lists since
they cannot dynamically change.
Tuples are defined by parenthesis () where commas separate items. t
= (Computers,'96', 1+4j)
We can use the slicing operator [] to extract items but we cannot change its value.
t = ('Computers',96,
1+4j)
print("t[1] = ", t[1])
print("t[0:3] = ",
t[0:3])

Here are some advantages of tuples over lists:


• Tuples have no append or extend method.
• Unable to remove elements from a tuple.
• Elements can be found in a tuple, as this does not change the tuple.
17
• The in-operator can also be used to check whether an element exists in the tuple.
• Tuples are faster than lists. When defining a constant set of values and

everything you ever do with it is to iterate through it, use a tuple rather than
a list.
• Your code becomes more secure if you 'write-protect' data that need not be
changed.
3.2.3 Python Strings:
String is sequence of Unicode characters. We can use single, double or triple
quotes to represent strings. Multi-line strings can be denoted using triple quotes,
‖‘ or ―‖‖.
str = "String is sequence of Unicode
characters"
print(str)
str = '''String is sequence of
Unicode characters'''
print(str)
Output:

Python can format multiple strings and numbers using a special syntax. The
string format is quickly covered here because it is often seen and the syntax must
recognize.
print "The item {} is repeated {} times".format(element,count))
The {} is a placeholder that is replaced by the element of the variables and count
in the final string—this compact syntax designed to keep the code readable and
compact.

3.2.4 Set Data Types in Python


Set is a mutable collection of unique items that is unordered. The set is defined

18
by values that are separated by a comma within { } braces. A set object has
appropriate methods to perform mathematical set operations such as union,
intersection, difference, etc.

3.2.5 Python Dictionary


Dictionary Dict () in Python is a list of Key: value pairs that are unordered. It is
a very powerful data type that contains much-associated information that can be
associated with keys. A dictionary‘s primary function is to extract a value based
on the key name. In contrast to lists in which index numbers use, dictionaries
allow you to access a key.
Dictionaries can also be used for sorting, iterating and comparing data.

3.2.6 Mutable and Immutable Types:


Data objects of the above types stores in a computer‘s memory for processing.
Some of these values can change during processing, but others‘ contents cannot
change once in the memory they are created.
Numbers, strings, and tuples are immutable, so their contents cannot change

19
after they are created.
Items in a list or dictionary object can be modified. It is possible to add, delete,
insert, and rearrange items in a list or dictionary. They are mutable objects.

20
CHAPTER 4
CONDITIONALS and LOOPS in PYTHON

4.1 What are conditionals in Python?


Conditional statements are also called decision-making statements. We use those
statements while we want to execute a block of code when the given condition is true or
false.

Type of condition statement in Python:

• If statement.
• If Else statement.
• Elif statement.
• Nested if statement.
• Nested if else statement.

4.1 If statement
A Python if statement evaluates whether a condition is equal to true or false. The
statement will execute a block of code if a specified condition is equal to true.
Otherwise, the block of code within the if statement is not executed.
Syntax
1. if(condition):
2. {
3. #if statement
4. }

Example

Program for if statement


1. a = 10
2. b = 20
3. if a<b:
4. print("a is less than b")

21
Output: a is less than b
4.2 If else statement
If else is a conditional statement. The statement itself says that if a given
condition is true or false. True means executing the ―if‖ statement to the
output. False means executing the
―else‖ statement to the output.
Syntax
1. if(condition):
2. {
3. # if statement
4. }
5. else:
6. {
7. # else statement
8. }

Example
Program for if else statement
1. a = 10
2. b = 20
3. if a==b:
4. print("a and b are equal")
5. else:
6. print("a and b are not equal")

Output: a and b are not equal

4.3 Elif statement


Elif is a shortcut of else if condition statements. In Python one or more
conditions are used in the elif statement.
Syntax
1. if(condition):
2. {
3. # if statement
4. } 22
5. elif(condition):
6. {
7. # elif statement
8. }
9. else:
10. {
11. # else statement
12. }

Example
Program for elif statement
1. a = 10
2. b = 10
3. if a < b:
4. print("a is greater than b")
5. elif a == b:
6. print("a and b are equal")
7. else:
8. print("b is greater than a")

Output: a and b are equal

4.4 Nested if statement


In python is using "if" statements inside other if statements it is called nested if
statement.

1. if(condition):
2. {
3. if(condition):
4. {
5. # if statement
6. }
7. }
Syntax

Example
Program for nested if statement
1. a= 1001
2. if a> 100:
3. print("Above 100")
4. if a > 1000:
5. print("and also 1000")
23
above

Output: Above 100


and also above 1000
4.5 Nested if else statement
In Python is using one ―if else‖ statement inside other if else statements it is
called nested if else statement.

1. if(condition):
2. {
3. if(condition):
4. {
5. #if statement
6. }
7. else:
8. {
9. #else statement
10. }
11. }
12. else:
13. {
14. #else statement
15. }
Syntax

Example
Program for nested if else statement

1. a=int(input("enter the a value"))#user give a value


2. if a> 100:
3. print("Above 100") 4. if a > 1000:
5. print("and also above 1000")
6. else:
7. print("and also below 1000")
8. else:
9. print("below 100")

Output: enter the value

24
>> 21
>> below 100
4.6 PYTHON-LOOPS
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you
need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times. The following diagram illustrates a loop statement −

Fig.-8
25
Python has two primitive loop commands:
• While loops
• For loops
Python programming language provides following types of loops to handle
looping requirements.
Sr.No. Loop Type & Description

while loop

1
Repeats a statement or group of statements while a given
condition is TRUE. It tests the condition before
executing the loop body.

for loop

2
Executes a sequence of statements multiple times and
abbreviates the code that manages the loop
variable.

nested loops

3
You can use one or more loop inside any another while,
for or do while loop.
Table-8
• For Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works

26
more like an iterator method as found in other object-orientated programming
languages.
Syntax

for <variable> in <sequence>:


# body_of_loop that has set of statements
# which requires repeated execution

Example

sum = 0 for val in


range(1, 6): sum
= sum + val
print(sum)

Output: 15

• While Loop
With the while loop we can execute a set of statements as long as a condition is
true.
Example

Print i as long as i is less than 6:


i = 1 while i < 6: print(i)
i += 1

Output: 1
2
3
4
5

27
4.7 Loop Control Statements
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope
are destroyed.
Python supports the following control statements. Click the following links to
check their detail.
Let us go through the loop control statements briefly
Sr.No. Control Statement & Description

break statement

1
Terminates the loop statement and transfers execution to the
statement immediately following the loop.

continue statement

2
Causes the loop to skip the remainder of its body and
immediately retest its condition prior to
reiterating.

pass statement

3
The pass statement in Python is used when a statement is
required syntactically but you do not want any command or
code to execute.
Table-9

28
CHAPTER 5
FUNCTIONS IN PYTHON

A function is a block of organized, reusable code that is used to perform a single,


related action. Functions provide better modularity for your application and a high
degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but
you can also create your own functions. These functions are called user-defined
functions.
5.1 Defining a Function
You can define functions to provide the required functionality. Here are simple
rules to define a function in Python.
• Function blocks begin with the keyword def followed by the
function name and parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these
parentheses. You can also define parameters inside these parentheses.
• The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing
back an expression to the caller. A return statement with no arguments is
the same as return None.
Syntax

def functionname( parameters ): "function_docstring" function_suite return


[expression] By default, parameters have a positional behavior and you need to
inform them in the same order that they were defined.
Example
29
The following function takes a string as input parameter and prints it on
standard screen. def printme( str ): "This prints a passed string into this
function" print str return
5.2 Calling a Function
Defining a function only gives it a name, specifies the parameters that are to
be included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it
from another function or directly from the Python prompt.
5.3 Function Arguments
You can call a function by using the following types of formal arguments −
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
5.3.1 Required arguments
Required arguments are the arguments passed to a function in correct positional
order. Here, the number of arguments in the function call should match exactly
with the function definition.
To call the function printme(), you definitely need to pass one argument,
otherwise it gives a syntax error.
5.3.2 Keyword arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter
name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with

30
parameters.
5.3.3 Default arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument.
5.3.4 Variable-length arguments
You may need to process a function for more arguments than you specified while
defining the function. These arguments are called variable-length arguments and
are not named in the function definition, unlike required and default arguments.
Syntax for a function with non- keyword variable arguments is this −

def functionname([formal_args,] *var_args_tuple ): "function_docstring"


function_suite return [expression]

An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional
arguments are specified during the function call.
5.4 The return Statement
The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return None.
All the above examples are not returning any value. You can return a value
from a function as follows −
#!/usr/bin/python# Function definition is here
def sum( arg1, arg2 ): # Add both the parameters and return
them." total = arg1 + arg2 print "Inside the function : ",
total
return total;# Now you can call sum function total =
sum( 10, 20 );
print "Outside the function : ", total
When the above code is executed, it produces the following result − Inside
the function : 30Outside the function : 30
31
5.5 Scope of Variables:
All variables in a program may not be accessible at all locations in that program.
This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in Python −
• Global variables
• Local variables
5.5.1 Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope.
This means that local variables can be accessed only inside the function in which
they are declared, whereas global variables can be accessed throughout the
program body by all functions. When you call a function, the variables declared
inside it are brought into scope.

32
CHAPTER 6
CHATBOT

Nobody likes to be alone always, but sometimes loneliness could be a better medicine
to hunch the thirst for a peaceful environment. Even during such lonely quarantines,
we may ignore humans but not humanoids. Yes, if you have guessed this article for a
chatbot, then you have cracked it right. We won’t require 6000 lines of code to create
a chatbot but just a six-letter word “Python” is enough. Let us have a quick glance at
Python’s ChatterBot to create our bot. ChatterBot is a Python library built based on
machine learning with an inbuilt conversational dialog flow and training engine. The
bot created using this library will get trained automatically with the response it gets
from the user.

Benefits of using Chatbots


• 24×7 availability.
• Instant answers to queries.
• Support multi-language to enhance businesses.
• Simple and Easy to Use UI to engage more customers.
• Cost effective and user interactive.
• Avoid communication with call agents thereby reducing the time consuming
tasks.
• Understand the Customer behavior
• Increase sales of business by offering promo codes or gifts.

Types of Chatbots
Chatbots deliver instantly by understanding the user requests with pre-defined rules and
AI based chatbots. There are two types of chatbots.

33
• Rule Based Chatbots: This type of chatbots answer the customer queries using
the pre- defined rules. These bots answer common queries such as hours of
operation of business, addresses, phone numbers and tracking status.
• Conversational AI Chatbots: This type of chatbots using Natural language
Processing(NLP) to understand the context and intent of a user input before
providing the response. These Bots train themselves as per the user inputs and
more they learn, more they become user interactive.

Chatbot in Today’s Generation


Today, we have smart AI-powered Chatbots that use natural language processing
(NLP) to understand human commands (text and voice) and learn from experience.
Chatbots have become a staple customer interaction tool for companies and brands that
have an active online presence (website and social network platforms).

Chatbots using python are a nifty tool since they facilitate instant messaging between
the brand and the customer. Think about Apple’s Siri, Amazon’s Alexa, and Microsoft’s
Cortana. Aren’t these just wonderful? Aren’t you already curious to learn how to make
a chatbot in Python?

Chatbots using python are a nifty tool since they facilitate instant messaging between
the brand and the customer. Think about Apple’s Siri, Amazon’s Alexa, and Microsoft’s
Cortana. Aren’t these just wonderful? Aren’t you already curious to learn how to make
a chatbot in Python?

Although chatbot in python has already begun to dominate the tech scene at present,
Gartner predicts that by 2020, chatbots will handle nearly 85% of the customer-brand
interactions.
34
In light of the increasing popularity and adoption of chatbots in the industry, you can
increase your market value by learning how to make a chatbot in Python – one of the
most extensively used programming languages in the world.
ChatterBot Library
ChatterBot is a Python library that is designed to deliver automated responses to user
inputs. It makes use of a combination of ML algorithms to generate many different types
of responses. This feature allows developers to build chatbots using python that can
converse with humans and deliver appropriate and relevant responses. Not just that,
the ML algorithms help the bot to improve its performance with experience.

Another excellent feature of ChatterBot is its language independence. The library is


designed in a way that makes it possible to train your bot in multiple programming
languages.

How does ChatterBot function?


When a user enters a specific input in the chatbot (developed on ChatterBot), the bot
saves the input along with the response, for future use. This data (of collected
experiences) allows the chatbot to generate automated responses each time a new input
is fed into it.

The program chooses the most-fitting response from the closest statement that matches
the input, and then delivers a response from the already known selection of statements
and responses. Over time, as the chatbot engages in more interactions, the accuracy of
response improves. You may create your own chatbot project to understand the details
of this technology.

35
How To Make A Chatbot In Python?
To build a chatbot in Python, you have to import all the necessary packages and
initialize the variables you want to use in your chatbot project. Also, remember that
when working with text data, you need to perform data preprocessing on your dataset
before designing an ML model.

1 Prepare the Dependencies


The first step in creating a chatbot in Python with the ChatterBot library is
to install the library in your system. It is best if you create and use a new
Python virtual environment for the installation. To do so, you have to write
and execute this command in your Python terminal:

2 Import Classes
Importing classes is the second step in the Python chatbot creation process. All
you need to do is import two classes – ChatBot from chatterbot and ListTrainer
from chatterbot.trainers. To do this, you can execute the following command:

3. Create and train the Chatbot


This is the third step on creating chatbot in python. The chatbot you are creating
will be an instance of the class “ChatBot.” After creating a new ChatterBot
instance, you can train the bot to improve its performance. Training ensures that
the bot has enough knowledge to get started with specific responses to specific
inputs. You have to execute the following command

36
Since you have to provide a list of responses, you can do it by specifying the lists of
strings that can be later used to train your Python chatbot, and find the best match for
each query. Here’s an example of responses we can train the chatbot using python to
learn:

• Communicate with the Python Chatbot


To interact with the Python chatbot, we can use the .get_response() function. This is
how it looks while communicating:

37
38
sReferences

• https://www.tutorialspoint.com/python/index.htm
• https://www.w3schools.com/python/default.asp
• https://www.jupternotebook.org/
• https://www.coursera.org/in
• https://www.python.org/
• Python: The Complete Reference by TMH Publication
• Python Programming |A modular approach by Pearson
Publication

39

You might also like