Eliminate code redundancy in a while loop

Asked

Viewed 84 times

3

In this example:

. Request today’s date via a form.

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

. Compare to 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 make this code avoiding the redundancy of the line below?

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

See working on Repl.it

1 answer

3


Thus?

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 on ideone (change the date of the last entry to today’s date). And in the repl it.. Also put on the 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 given condition, then encapsulate everything that needs to be repeated in the loop.

The originally 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 bond and it’s been asked before, but it’s hard to understand.

  • Interesting! Always found the return would only work by returning the value of, for example, a variable. return media

Browser other questions tagged

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