0

I am new to Python app development. I know about the Python exceptions, but when I use the except keyword it shows me SyntaxError. My code is

number = 1
try:
if(number == 1):
except ValueError:
print "yay"
else:

print "sucks"

When I use this code it gives me a syntax error when I add the except keyword. Since I'm new to Python I don't know why it's happening like this. I'm using Python 2.7.

Stedy
  • 7,359
  • 14
  • 57
  • 77

3 Answers3

6
number = 1
try:
    if(number == 1):
        print 'yay'
    else: 
        print 'sucks'
except ValueError:
    print 'Oops, something went wrong'

Follow this structure and you will be golden pony boy.

kindall
  • 178,883
  • 35
  • 278
  • 309
Bioto
  • 1,127
  • 8
  • 21
5

You cannot mix up Python statements like that.

try ... except is one compound statement; each of the two blocks contained (for the try and the except) need to be fully independent statements of their own. if ... else ... is also a compound statement, so it has to be entirely within either the try or the except block, or entirely outside of it.

This would work:

number = 1
try:
    if number == 1:
        print("yay")
    else:
        print("sucks")
except ValueError:
    pass

because now the whole of if .. else is inside the try block.

Not that you need to handle ValueError here, there is nothing in the code block that would throw the exception.

From the comments it is clear you are using Python 3 (and IDLE), so you want to use print() as a function.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • when i type except on python gui ..it still shows me syntax error – user3760836 Jun 20 '14 at 16:24
  • @user3760836: Then either you are doing something wrong, or your Python GUI is showing an error where there is none. Without seeing your exact GUI contents, that is impossible to tell, and way beyond the scope of what we can help you with. – Martijn Pieters Jun 20 '14 at 16:27
  • @user3760836: looks like you are seeing this: [Syntax error on print with Python 3](http://stackoverflow.com/q/826948) – Martijn Pieters Jun 20 '14 at 16:28
0

In Python 3.0 , print became a function, you need to include parenthesis as you must for other functions. So print var becomes print(var)

Since you're using Python3 try the following:

number = 1
try:
    if (number == 1):
         print ("yay")
    else:
        print ("other opts")
except ValueError:
     print ("Something went wrong")
Parker
  • 8,539
  • 10
  • 69
  • 98
Bala
  • 21
  • 2
  • can you take a screenshot? Also can you ensure that indents are specified properly. – Bala Jun 21 '14 at 06:16