0

Im just sitting for 10 minutes staring at a simple piece of code, which I have copied from a guide and I can't understand why I am getting an error.

def transformation(x):
    date_format = "%d/%m/%Y"
    try:
        a = dt.date(int(x[6:10]), int(x[3:5]), int(x[0:2]))
    else:
        a = dt.datetime.strptime(x, date_format)
    finally: 
        return a
  File "<ipython-input-91-f1f6fe70d542>", line 5
    else:
       ^
SyntaxError: invalid syntax

Maybe this is just me... Whats wrong? After adding except:

def transformation(x):
    date_format = "%d/%m/%Y"
    try:
        a = dt.date(int(x[6:10]), int(x[3:5]), int(x[0:2]))
    except pass 
    else:
        a = dt.datetime.strptime(x, date_format)
    finally: 
        return a
File "<ipython-input-93-c2285c857574>", line 5
    except pass 
              ^
SyntaxError: invalid syntax

2 Answers2

3

You need an except clause to use else:

The try ... except statement has an optional else clause, which, when present, must follow all except clauses [Emphasis mine]

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0

I just saw it from the python document page, so I'm just gonna quote what it says to you:

The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:

 for arg in sys.argv[1:]:
        try:
            f = open(arg, 'r')
        except IOError:
            print('cannot open', arg)
        else:
            print(arg, 'has', len(f.readlines()), 'lines')
            f.close()
Christian Dean
  • 22,138
  • 7
  • 54
  • 87