My function only returns None

Asked

Viewed 102 times

0

I was creating/trying to create a python chat bot, so far so good. But when I use my function that returns the robot’s answer it returns None! I don’t know how to fix...

def responder(conversa1, posicao): #conversa1 significa o que o usuário digitou. A posição esta definida como 1 por padrão 
   a = open('conversas.txt', 'r')
   for linha in a.readlines():
      if conversa1 == linha:
        resultado = linha
        res = resultado.split('= ')[posicao].strip('\n')
        return res

Important to say that the answers are saved in a txt file

oi=  oi tudo bem?
ola= ola para voce tambem
tudo bem?= tudo bem sim, e voce?
tudo= que legal

NOTE: no if I tried to replace "==" with "in" but when I do this it shows the wrong robot’s answer, I don’t know why.

2 answers

0

The indentation of your code is wrong. The IF It should be inside your go. The None was being returned because the IF had never been executed. In case the IN would only work if your line was of the type LISTA, what is not, if you are comparing two strings the correct is to use ==.

def responder(conversa1, posicao):
   a = open('conversas.txt', 'r')
   for linha in a.readlines():
       if conversa1 == linha:
         resultado = linha
         res = resultado.split('= ')[posicao].strip('\n')
         return res
    return 'conversa1 nao eh igual a linha'
  • Hi, I just did that (put if inside the for) in my code and the error persists

  • out of the place a Return 'conversa1 is different from line'

  • @Rcoletto changed the answer to Voce test again.

  • I just put the Return 'conversa1 is not equal to the line' and now it just returns me this.

  • Exactly the problem is in IF conversa1 == line, use a Debugger tool to see the values of each variable and you will see that they really are different.

  • What do I do in this case? I debug the code but it wouldn’t solve right?

Show 1 more comment

0

Here’s the solution and with context manager. The problem was in this if if conversa1 == line.strip(' n'):

def responder(conversa1, posicao):
   with open('conversas.txt', 'r') as a:    
     for linha in a.readlines():
         if conversa1 == linha.strip('\n'):
           resultado = linha
           res = resultado.split('= ')[posicao].strip('\n')
           return res
   return 'conversa1 nao eh igual a linha'
  • I just read the article you put up there and I still couldn’t solve the problem.

  • The link is about context management, open disk files, for example. My response function, you tested?

  • I tested and still giving problem

  • Make it clear or explain well, based on your source file, and by the input phrase what the expected result is.

  • That is, what is in your file and what input you are testing and what should be the result.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.