ComenzarEmpieza gratis

Añadir variedad

Puede resultar un poco aburrido escuchar siempre las mismas respuestas. En este ejercicio, vas a añadir un poco de variedad. Si le preguntas a tu bot cómo se siente, la probabilidad de que responda "oh I'm great!" o "I'm very sad today" debe ser la misma.

Aquí usarás el módulo random —en concreto random.choice(ls)—, que selecciona aleatoriamente un elemento de una lista ls.

Ya tienes definido un diccionario llamado responses, que asigna a cada mensaje una lista de posibles respuestas.

Este ejercicio forma parte del curso

Creación de chatbots en Python

Ver curso

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

# Import the random module
____

name = "Greg"
weather = "cloudy"

# Define a dictionary containing a list of responses for each message
responses = {
  "what's your name?": [
      "my name is {0}".format(name),
      "they call me {0}".format(name),
      "I go by {0}".format(name)
   ],
  "what's today's weather?": [
      "the weather is {0}".format(weather),
      "it's {0} today".format(weather)
    ],
  "default": ["default message"]
}

# Use random.choice() to choose a matching response
def respond(message):
    # Check if the message is in the responses
    if message in responses:
        # Return a random matching response
        bot_message = ____(____[____])
    else:
        # Return a random "default" response
        bot_message = ____.____(____["____"])
    return bot_message
Editar y ejecutar código