-2
def ask():
    while True:
        try:
            num = int(input("Enter an integer:"))
        except:  
            print('Not a number, please try again')
        continue
        else:
            print('Thats a valid number!')
            break
        finally:
            print('All done')

I get this error-I checked and rechecked indentaion, but still not working

File "<ipython-input-46-ff8c841c59c4>", line 8
    else:
       ^
SyntaxError: invalid syntax
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Check the indentation again. `else` is invalid following `continue`. – wjandrea Aug 20 '20 at 01:53
  • BTW welcome to SO! Check out the [tour]. In the future, you need to provide a [mre]. In this case, the function and loop are irrelevant to the problem, so it would help to remove it, to make the problem more obvious to you and us. Also BTW, a [bare `except` is bad practice](https://stackoverflow.com/q/54948548/4518341). use the specific exception you're expecting, `ValueError`. – wjandrea Aug 20 '20 at 01:59

2 Answers2

0

your else statement is not needed here :) try this:

def ask(): 
    while True: 
        try: 
            num = int(input("Enter an integer:")) 
            print('Thats a valid number!') 
            break 
        except:
            print('Not a number, please try again') 
            continue 
        finally: 
            print('All done')
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Zugzwang
  • 28
  • 1
  • It's not necessary, but it is better practice because you should put as little as possible in a `try` statement. Also, this doesn't address what caused the syntax error. – wjandrea Aug 20 '20 at 01:57
0

Your syntax is wrong

def ask(): 
    while True: 
        try: 
            num = int(input("Enter an integer:")) 
        except ValueError:
            print('Not a number, please try again') 
            continue 
        except: 
            print('Thats a valid number!') 
            break 
        finally: 
            print('All done')
none
  • 111
  • 1
  • 8
  • It would help to explain *how* it's wrong, and what you fixed. I notice you also added `except ValueError`, and that definitely needs an explanation cause it's not part of the problem. You can use this snippet if you'd like: ``a [bare `except` is bad practice](https://stackoverflow.com/q/54948548/4518341). use the specific exception you're expecting, `ValueError`.`` – wjandrea Aug 20 '20 at 02:05