-4

the return from this code (date) is 'none' if an invalid entry is provided, then a valid entry is given. However if a valid entry is given first time, the correct return for date is given. Any tips on how I can solve it?

def getDate():
    date = input("Please enter the date in DD/MM/YYYY format: ")
    try:
        strptime(date, "%d/%m/%Y")
        return date
    except:
        print ("Invalid Date, please enter again")
        getDate()
  • 2
    1. You don't return anything in the `except` case. 2. [Don't use bare `except`](http://blog.codekills.net/2011/09/29/the-evils-of--except--/). 3. Don't use recursion for this - see http://stackoverflow.com/q/23294658/3001761 – jonrsharpe Jan 03 '16 at 12:32
  • You can make it work by changing the last line in the `except` clause to `return getDate()`. But you shouldn't use recursion, as jonrsharpe points out, to perform retries; use a loop instead. – mhawke Jan 03 '16 at 12:40
  • The reason for closing this question seems completely wrong. It _can_ be reproduced and it is (probably) not a typo. – mhawke Jan 03 '16 at 12:59

1 Answers1

3

Since there are so many erroneous answers being posted to this question I feel compelled to add another. Adding return getDate() in the except clause will make it work as you hope:

def getDate():
    date = input("Please enter the date in DD/MM/YYYY format: ")
    try:
        strptime(date, "%d/%m/%Y")
        return date
    except:
        print ("Invalid Date, please enter again")
        return getDate()

However, handling retries with recursion is not ideal. Use a loop instead:

from time import strptime

def getDate():
    while True:
        date = input("Please enter the date in DD/MM/YYYY format: ")
        try:
            strptime(date, "%d/%m/%Y")
            return date
        except ValueError:
            print ("Invalid Date, please enter again")
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • 1
    Don't you need to `return strptime(date, "%d/%m/%Y")` rather than `return date`? – Jamie Bull Jan 03 '16 at 12:53
  • 2
    Nope. The `strptime` call is just to ensure that `date` is a valid (proper format) date string. – TigerhawkT3 Jan 03 '16 at 12:54
  • 1
    @JamieBull: why? `strptime()` is being used only to validate the user entered string, and the function returns the string, not whatever object `strptime()` returns (a `time.struct_time` in my case). – mhawke Jan 03 '16 at 12:56
  • By the way, I would put the `return date` in an `else`. – TigerhawkT3 Jan 03 '16 at 12:57
  • 1
    @TigerhawkT3: why? Does it make a difference in this case? – mhawke Jan 03 '16 at 13:00
  • I don't expect `return date` to throw a `ValueError`, no, but it's a good practice, and I think it clarifies the algorithm ("try this, if it fails do this, if it succeeds do that"). – TigerhawkT3 Jan 03 '16 at 13:04