Back

Simple Chatbot

The code is a simple conversational script that interacts with a user by asking for their name, age, and favorite color, then responds with personalized messages.

Code Block

This script begins by prompting the user for their name and greets them using the provided name. It then asks the user for their age, converts the input into an integer, and calculates the difference between the user's age and the bot's age (which is hardcoded as 3 years old). The script informs the user how much older they are than the bot. Finally, the bot asks for the user's favorite color and responds with a friendly message that acknowledges the user's input.

Check out the Code

Code Analysis

Input Validation:

  • The code assumes that the user will input a valid integer for age. If a non-integer input is provided, it will cause a ValueError. Adding a try-except block can handle this gracefully.

while True:
   age_input = input("How old are you? ")
   try:
       age = int(age_input)
       break
   except ValueError:
       print("Please enter a valid number for your age.")

Code Reusability:

  • Instead of directly embedding logic in the script, consider modularizing the code into functions. This approach improves readability and allows for easier maintenance or expansion.

def get_user_name():
   return input("Hello! What is your name? ")

def get_user_age():
   while True:
       age_input = input("How old are you? ")
       try:
           return int(age_input)
       except ValueError:
           print("Please enter a valid number for your age.")

def get_favorite_color():
   return input("What's your favorite color? ")

def main():
   name = get_user_name()
   print(f"Nice to meet you, {name}. I am Mimo!")
   
   age = get_user_age()
   bot_age = 3
   age_difference = age - bot_age
   print(f"You are {age_difference} years older than me. I'm only {bot_age} years old!")
   
   color = get_favorite_color()
   print(f"Oh, {color} is a beautiful color!")

if __name__ == "__main__":
   main()

Expandability:

  • The script can be easily extended to include more interactions, making it more engaging. For instance, you could ask about hobbies or favorite movies and respond with fun facts.

Internationalization:

  • If you plan to use this in a multi-language environment, consider using a dictionary for phrases and messages. This approach will make it easier to translate the script into other languages without changing the core logic.

Data Storage for Future Use:

  • If this interaction is part of a larger application, consider storing the user data (name, age, favorite color) in a database or a file for future interactions.