Error fetching string inside another string in python

0

I'm doing some testing and the code seems to be correct logically, but when I use an example: "What day is today?" as self.frase it only returns me the first if (of the hours) if I put it as self.frase="What day of the week is it today?" the same error happens, where am I going wrong?

def about_time(self):
    temp_atual = datetime.datetime.now()
    if 'são' or 'sao' in self.frase:
        print("Agora são " + str(temp_atual.hour) + " horas, " + str(temp_atual.minute) + " minutos e " + str(temp_atual.second) + " segundos.")
    elif 'dia' and 'hoje' in self.frase:
        print("Hoje é dia " + str(temp_atual.day) + "/" + str(temp_atual.month) + "/" + str(temp_atual.year))
    elif 'dia da semana' in self.frase:
        dia = temp_atual.isoweekday()
        if dia == 1:
            dia = "segunda-feira"
        if dia == 2:
            dia = "terça-feira"
        if dia == 3:
            dia = "quarta-feira"
        if dia == 4:
            dia = "quinta-feira"
        if dia == 5:
            dia = "sexta-feira"
        if dia == 6:
            dia = "sábado"
        if dia == 7:
            dia = "domingo"
        print("Hoje é " + dia)
    
asked by anonymous 09.07.2018 / 02:33

3 answers

2

Your ifs are incorrect, and and or are logical operators , they are not part of in , so this is wrong:

if 'são' or 'sao' in self.frase

Should be:

if 'são' in self.frase or 'sao' in self.frase

This is also wrong

if 'dia' and 'hoje' in self.frase:

should be

if 'dia' in self.frase and 'hoje' in self.frase:

Each or or and separate instructions for logical operations, ie they do not work within in , but rather "in reverse", so the use is this:

if <instrução> or <outra instrução>:

In each of these statements you can use == , != , is , is not , but they are part instructions, so in your first if it's as if you were doing this: p>

if ('são') or ('sao' in self.frase)

First check if 'são' if it failed would check 'sao' in self.frase , as 'são' always goes in if , so even if the phrase was different it would come in anyway, because 'são' was not being compared to anything .

    
09.07.2018 / 05:33
2

I gave a small refactor to your code:

def about_time(self):
    temp_atual = datetime.datetime.now()
    if any(_ in self.frase for _ in ('sao', 'são')):
        print(temp_atual.strftime("Agora são %H horas, %M minutos e %S segundos."))
    elif 'dia' in self.frase:
      if 'hoje' in self.frase:
        print(temp_atual.strftime("Hoje é dia %d/%m/%Y"))
      elif 'semana' in self.frase:
        dia = [None, 'segunda-feira', 'terça-feira',
        'quarta-feira', 'quinta-feira', 'sexta-feira',
        'sábado', 'domingo'][temp_atual.isoweekday()]
        print("Hoje é " + dia)

Since isoweekday() returns a value between 1 and 7, I put a None in the list at index 0, but, it could be anything ... Here we access the list of days by index (1 to 7, remember?), Which could also be written as a dictionary:

dia = {i: dia for i, dia in enumerate(['segunda-feira', 'terça-feira',
                                       'quarta-feira', 'quinta-feira', 
                                       'sexta-feira', 'sábado', 'domingo'], start=1)}.get(temp_atual.isoweekday())

Any of these ways saves us from that giant block of ifs/elifs .

I also recommend taking a look at the strftime() method of the datetime object, making it easier to handle strings and dates.

Edit: Adding the explanation of the any() function to the PO request

The function any() gets an iterable and returns True if any element of that iterable is equivalent to True , in case:

(_ in self.frase for _ in ('sao', 'são'))
# é parecido a:
compares = []
for palavra in ('sao', 'são'):
  if palavra == self.frase:
    compares.append(True)
  else:
    compares.append(False)

the iterable would be a generator of 2 elements ('sao', 'são') compared to self.frase , if we consider self.frase = 'teste' the generator would be similar to: (False, False) since neither of the 2 words is equal to self.frase , and as < strong> none element is equal to True , we do not enter if .

There is also a similar function, all() , the difference being all() only returns True if all elements equivalent to True .

    
09.07.2018 / 21:32
-2
    import datetime

def about_time(message):
    temp_atual = datetime.datetime.now()
    if 'são' or 'sao' in message:
        print("Agora são " + str(temp_atual.hour) + " horas, " + str(temp_atual.minute) + " minutos e " + str(temp_atual.second) + " segundos.")
        if 'dia' and 'hoje' in message:
            print("Hoje é dia " + str(temp_atual.day) + "/" + str(temp_atual.month) + "/" + str(temp_atual.year))
            if 'dia da semana' in message:
                dia = temp_atual.isoweekday()
                if dia == 1:
                    dia = "segunda-feira"
                if dia == 2:
                    dia = "terça-feira"
                if dia == 3:
                    dia = "quarta-feira"
                if dia == 4:
                    dia = "quinta-feira"
                if dia == 5:
                    dia = "sexta-feira"
                if dia == 6:
                    dia = "sábado"
                if dia == 7:
                    dia = "domingo"
                print("Hoje é " + dia)
about_time('Que dia é hoje?')

OUTPUT:

Agora são 0 horas, 18 minutos e 45 segundos.
Hoje é dia 9/7/2018
    
09.07.2018 / 05:19