Python Forum

Full Version: What is causing the syntax error?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Just started using python a few seconds ago...
   
    n = int(input("Enter a number: "))   

    if n % 2 == 0:
	    print (n, " is an even number")
	else:
		
SyntaxError: invalid syntax
The Else statement is highlighted but I'm not sure what's wrong.
Hello and welcome to Python!
What is wrong in your case is the "empty" else.

If you don't require else clause, you don't need to write it. If you want to have the else clause, but without any action to be done, you should write "pass" keyword in it, like this:

n = int(input("Enter a number: "))   
 
if n % 2 == 0:
    print (n, " is an even number")
else:
    pass
Is that your full code? I'm not getting a SyntaxError, but I am getting other errors because there is nothing after the else.
(Sep-12-2017, 01:06 PM)Mr_Keystrokes Wrote: [ -> ]if n % 2 == 0:
print (n, " is an even number")
else:

SyntaxError: invalid syntax
[/python]


So you don't want to do anything inside else:.then just don't write else. Only if statement will do just fine.

There are some times when syntactically a statement is required but no execution is needed.
For that, you can use pass keyword.

    n = int(input("Enter a number: "))   
 
    if n % 2 == 0:
        print (n, " is an even number")
    else:
        pass
As soon as I type in 'else:' and then press enter to go into the new line it pops up with invalid syntax.
In the following line I would like to write:

print (n, " is an odd number")
I am writing this in Python shell.

Strange, it seems to be working now that I pasted the full answer into the shell. Whereas before, when I tried to write the else statement it wouldn't allow me to go the next line and it highlighted the else function and indicated a syntax error.

Thank you guys for the pointers!
The error could be on a line above this block of code. It's indented so I presume that this is not all the code.