Felipe
Felipe

Reputation: 140

New to Exceptions

I'm trying to use the exceptions, but I got an error

import sys

while True:
        try:
            horas = int(input("¿Cuántas horas trabajó por semana? "))
            except TypeError as exception:
                print("Solo números enteros")
                return horas
except TypeError, e:
         ^
SyntaxError: invalid syntax

Upvotes: 0

Views: 69

Answers (2)

rdas
rdas

Reputation: 21275

Fix the indentation

import sys


def get_horas():
    while True: 
         try: 
             horas = int(input("¿Cuántas horas trabajó por semana? ")) 
             return horas
         except TypeError as exception: 
             print("Solo números enteros")          

get_horas()

Upvotes: 1

Andrew Euredjian
Andrew Euredjian

Reputation: 106

The issue you're having is improper indentation. The try and except statements need to be at the same indentation level. Also, your return statement should only be inside the try statement. If an exception occurs, the variable horas will not be initialized and therefore would throw a different error. You also don't want your return statement to be called until a user successfully inputs the correct type, so you shouldn't place the return statement after the try/except statement

Here is an example of how to fix your current code:

import sys

while True: 
     try: 
         horas = int(input("¿Cuántas horas trabajó por semana? ")) 
         return horas
     except TypeError as e: 
         print("Solo números enteros")

Upvotes: 2

Related Questions