Search code examples
pythonexceptionprintingexcept

How can I use the Except Exception in Python?


I need to make a code that doesn't give me an error, I want a print to try again for example.

I learn in other topics, but I don't understand anything about that. I have this code:

def conversor(anosluz):
    try:
        km = float(anosluz * (9.459 * 10**12)) 
        return km
    except Exception, e:
        print 'Ooops! O valor que inseriste nao e o correcto, tenta de novo.', e


if __name__=='__main__':
    anosluz = input('Insira a distancia em anos luz: ')
    resultado = conversor(anosluz)
    print resultado

Solution

  • Divide your code into input/output and calculation:

    def conversor(anosluz):
        # just convert the given anosluz into km
        km = anosluz * (9.459 * 10**12) 
        return km
    
    
    if __name__=='__main__':
        while True:
            # repeat until *break*
            anosluz = raw_input('Insira a distancia em anos luz: ')
            try:
                resultado = conversor(float(anosluz))
            except ValueError, e:
                # oh, conversor raised an exception
                print 'Ooops! O valor que inseriste nao e o correcto, tenta de novo.', e
            else:
                # no exception, print result and exit
                print resultado
                break