Eliminate code redundancy in a while loop

3

In this example:

. Ask for today's date via a form.

. Check if it was typed in dd / mm / yyyy format.

. Compare with the current system date

from datetime import date

def verificacaoData():
  dataForm = input('Digite a data atual no padrão dd/mm/aaaa: ')
  while True:
    if date.today().strftime("%d/%m/%Y") != dataForm:
      print('Data informada difere da data atual.')
      dataForm = input('Digite a data atual no padrão dd/mm/aaaa: ')
    else:
      print('Correto! Datas conferem!')
      break

verificacaoData()

Is there any other way to do this code avoiding the redundancy of the line below?

dataForm = input('Digite a data atual no padrão dd/mm/aaaa: ')

See working at Repl.it

    
asked by anonymous 21.11.2017 / 16:28

1 answer

3

So?

from datetime import date

def verificacaoData():
  while True:
    dataForm = input('Digite a data atual no padrão dd/mm/aaaa: ')
    if date.today().strftime("%d/%m/%Y") != dataForm:
      print('Data informada difere da data atual.')
    else:
      print('Correto! Datas conferem!')
      return

verificacaoData()

See working in ideone (change the date of the last entry to today's date). Also I put GitHub for future reference .

It's very simple, make the code to run only once, then you decide everything that needs to be repeated in a certain condition, then encapsulate everything that needs to be repeated in the loop.

The original written form is not only redundant, it misrepresents the flow because it asks for something after it needs to be used. It works because it's a loophole and has been asked before, but it's hard to understand.

    
21.11.2017 / 16:31