Annie the Chatbot — #LearningPythonThroughProject : Series 4

Amina Mardiyyah Rufai
11 min readAug 5, 2020

--

Welcome to the fourth series! We are gradually making progress.If you are yet to see previous series, the links have been included at the end of the article.

In this series, we are going to build a fascinating project. We will be building a simple ‘Chatbot’ in Python.

Chatbots have become such an important tool in recent times. It is used in businesses to help bridge the gap between business owners and customers, it is integrated into websites, used as personal assistants to help create schedules, manage daily routines, for personalized web search, weather updates et cetera. One way or the other, you must have come across this tool. You might have communicated with one without realizing it.

You will find it as a pop-up chat-box in websites, in your mobile devices as Google assistant, or Microsoft Cortana, Siri, Amazon Alexa et cetera. Wouldn’t it be great to be able to build one of your own?

A Chatbot is an intelligent computer program that simulates human conversations. It is capable of communicating and performing actions similar to a human. It could be in form of text or voices(Virtual Assistants).

In this project, the chatbot will be created using Python’s “Control Statements”. In the previous project, we explored one type of Flow control statements — ‘the iterative while loop statement’. For this project, we will be exploring the ‘Conditional Statements(‘if-else-elif’)
Let’s dive right in:

BUILDING A SIMPLE CHATBOT IN PYTHON

STEPS:

  • Open any text editor of choice(Default Python Idle was used here)
  • Create a new python file and save it as ‘chatbot.py’.
  • Initiate a ‘Welcome message’ by the chatbot using the print statement. Also, request for the user’s name using the input statement, and create a greeting statement. You can give the Chatbot a name. I will call mine ‘Annie’.
Annie’s introduction
  • Next, a first conversation with the chatbot will be initiated. This is broken down into three(3) steps. So ideally, what is the first thing you do when you meet someone? A regular conversation would go, ‘Hello! How are you?’, or any of the other variations right?. The chatbot would need to do just the same, after all the aim is to simulate human conversations right? Great!

— First, a ‘feelings’ variable will be created using the input statement.

— Next, a Python list will be created(Do not worry about this, I will explain its function shortly. The ‘List Data Structure’ will be used to store a range of possible responses by the user.

— Then, a condition will be initiated using the conditional ‘if-else’ statements. This is so as to check if the user’s input is in the initial stored responses, if otherwise, the chatbot will probe further.

Annie’s conversation about feelings
  • Let’s make this more exciting. Let’s add other conversations. For the next conversation, Annie will ask the user for their age and try to place them in a category(Teenager, Adult, or Elderly). This will also be done using the ‘conditional statements’.
Annie’s conversation on Age
  • Next, add a conversation on a conversation on continents. We will be using a lot of the conditional statements today, and writing more lines of code. However, once the program gets running, the rush of excitement you feel seeing the program work will be worth all the effort. Stay tuned!
Conversation on continents
  • Let’s add one more conversation and that’s it.
Conversation on Current Year
  • Finally, Annie says goodbye to the user.
Ending Conversation

Whoa! That was sure a lot of code. It’s time to get the program running and appreciate all the sweat.

  • Save and run the program.

Amazing right?

Now let’s explain the concepts.

PYTHON CONCEPTS USED

  1. The print statement
  2. The input statement
  3. Variable definition(name,feelings,responses,reason,userAge,world,continent,year)
  4. Data Structures(List and Tuple)
  5. Conditional Statements(If-Else-Elif)
  6. Identity Operators(in)
  7. More use of comparison operators(>, , ≤, ==)

Some of these concepts have already been explained in previous series. I will move straight to new ones introduced for this project.

  • Data Structures: A Data Structure is a way of storing a collection of or different data types. It can contain one or more Data types such as strings, floats, integers et cetera. Data Structures allow storage of information in Python for easy access. One can relate a data structure to a backpack, where you store different types of items(laptop, Lunchpack, notepad, pen, hairclip, perfume et cetera). There are four common Data structures in Python: The List, Tuple, Set, and Dictionary. While List and Dictionary are categorized as ‘mutable Data structures(contents can be changed), Sets and Tuples are immutable Data Structures(Cannot be altered once initiated).

Data structures are more powerful than data types or variables in Python. For a data type, we have just one unique set at a time(a string or an integer or a float) e.g x = ‘Hello World!’, whereas for a data structure, we can store different data types in one unique set and easily access it whenever needed. Take a look at the example below:

A dictionary

The image above shows an example of one type of Data structure in Python — ‘a Dictionary’. Notice it contains different data types: strings, floats, boolean, and integers. See how easy it is to store so much information in one? Now let’s try to access a piece of information from it.

Accessing a piece of stored information from a dictionary

Amazing right!

HOLD ON!! What did you first think about when I mentioned the “Dictionary”. Did you think about a regular dictionary we all use to search for words and meanings? Well, they are not exactly the same but very similar.
The Dictionary serves somewhat like a “Map for words”, right?

You know how you search for words in a regular Dictionary, and you get the part of speech, meanings, and pronunciation??
Well, a Python Dictionary serves a similar purpose. It stores information like a map, and this information can further be accessed using keys or key-values(just like you need keys to read and understand Maps).

In Python, a Dictionary is created using curly braces {}, Just as seen in the example above. Information is stored using the format of key and value
The Dictionary is a Mutable Data Structure(can be changed), just like the List.
However, Unlike the Lists and Tuples where items are accessed using the index position, Items are accessed in the Dictionary using the ‘Keyname’.
Each Item has a Key and a Value and items are separated with a comma.

For a better understanding of how to use this Data structure, look up the links included at the end of the article.

So in the project earlier, we explored the use of a List and a Tuple.

Lists in Python are defined using the square brackets [], and a comma separating the items.
They are Mutable(Changeable) Data Structures because elements can be added and deleted. The ‘responses’ variable in the project was created using the List Data structure.

Tuples in Python are defined using the circle brackets/Parentheses () and a comma separating the items. It is an immutable Data Structure in Python. Immutable means it cannot be changed or altered after initiation. Unlike the lists, elements can neither be added nor deleted. The ‘world’ variable in the project was created using a Tuple.

These Data Structures each have their unique methods, refer to the links below for in-depth understanding.

  • Conditional Statements: So in the previous project, we talked about how computers need instructions for a decision-making process, just like humans do. However, for computers, these instructions need to be translated in a special way for the task to be carried out. Conditional Statements are the tools used in programming to effectively translate instructions to computers for ease of decision making. In Python, Conditional Statements are also referred to as ‘Conditionals’.There are basically three(3) types:
     — if Statements(using the if keyword)
     — else Statements(using the else keyword)
     — if -else or Nested elif(short for else-if or if-else)Statements (using multiple ifs and else, or simply using the elif keyword).

Conditional Statements are used hand-in-hand with comparison operators(>,<,,,==) as well as identity operators(in, is).

So how do the Conditional statements work?

The ‘if’ statement is the simplest form of decision making in python. Here, instruction is given as to what specific action to take in a given state.
Instruction is given to the computer on what to do in a specific situation.
If or when the condition is true, the action is taken. Otherwise(else), it is not taken or another action is carried out.

Remember, in the previous project I mentioned how ‘Flow Control Statements’ are generally “Blocks of Code” in Python. A keyword to show the initiation of the block of code, a condition(using either of identity or comparison operators), a semicolon ‘:’, and finally, actions to be carried out if the condition is True or False. So since codes are executed line by line(a line at a time), the computer checks for the validity of the ‘if’ block, if True, it terminates and exits the block of code, if False, it moves on to the ‘else’ block or ‘elif’ block if there are any.

Picture your log-on screen that comes up when you turn on your PC or wake it up. Under the user icon, you find the password box. To access your desktop you have to enter the correct password, otherwise(else), you remain locked out. This can be represented by a simple statement;
“ If the password is correct, allow access, else, stay locked.”

or

“ If the password is correct, allow access, elif ask for guess login details, else stay locked.”

The ‘else’ or following ‘elif’ block will only work if and only when the condition for the ‘if’ block is false. Similarly, in a case of multiple elifs blocks, the condition for the if block is checked first, if false, then it moves on to the next elif, if True, it terminates, otherwise, it moves on to the next elif blocks, and the else block will only get executed when the condition for the if block and all preceding elifs are False.

In Summary,

“if condition 1 is met:
do action 1
else if, if condition 2 is met instead:
do action 2
else if, if condition 3 is met instead:
do action 3
else, if none of the above conditions are met:
do this action”

This explains the execution of code when we created these in the Project:

  • Identity Operators and Logical Operators: So far, in previous projects, we have explored the use of different types of operators in Python: ‘The Arithmetic and Comparison Operators’.

The identity operators are used to determine membership in python. Whether an item, a variable or a data type belongs to a certain class or not. In Python, keywords ‘in’ , ‘not in’, ‘is’ and ‘is not’ are called identity operators. While ‘is’ is used to check if two items belong to the same class(not necessarily equality), ‘in’ is used to check for membership.

In this Project, the ‘in’ identity operator was used to validate and create conditions using conditional statements. For example, it was used to check if the entered response by the user is ‘contained’ or is a member of the predefined responses.

Logical Operators are used to connect two conditions together in Python. They are also called ‘Boolean Operators/Expressions’.

“Do not confuse them with Boolean data types though. Though they work together they are different”

There are three(3) types in Python:

  1. and
  2. or
  3. not

The ‘and’ operator is used to validate two conditions, i.e both conditions must be correct for it to return ‘True’, otherwise, it returns ‘False’.

The ‘or’ operator is used to validate only one condition i.e as long as one condition is True, it will return True.

The ‘not’ operator negates a returned value. For example, if a condition was created using the ‘or’ operator, and the condition should ideally return a True value, adding the ‘not’ operator reverses the output and it returns False instead.

In this project, we only explored the use of the ‘and’ operator. It was used in connecting two conditions together.

This is the end of another exciting series. Thank you for tuning in once again. The link to code has been shared below, alongside other exercises(expense.py, dictionary.py, evenodd.py ) I think you will find quite useful.

The links to the previous series have also been shared below. Also reference the resources below.

Thank you once again!

CONNECT ON SOCIAL MEDIA

Twitter: @diyyah92

LinkedIn: www.linkedin.com/in/aminah-mardiyyah-rufa-i

--

--

Amina Mardiyyah Rufai
Amina Mardiyyah Rufai

Written by Amina Mardiyyah Rufai

Machine Learning Engineer @ EMBL-EBI | Machine Learning Researcher | Previously, intern @Idiap.ch, @epfl.ch | MSC Machine Intelligence from AIMS-AMMI Senegal;

No responses yet