Python Forum
What is causing the syntax error? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: What is causing the syntax error? (/thread-4902.html)



What is causing the syntax error? - Mr_Keystrokes - Sep-12-2017

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.


RE: What is causing the syntax error? - j.crater - Sep-12-2017

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



RE: What is causing the syntax error? - ichabod801 - Sep-12-2017

Is that your full code? I'm not getting a SyntaxError, but I am getting other errors because there is nothing after the else.


RE: What is causing the syntax error? - hbknjr - Sep-12-2017

(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



RE: What is causing the syntax error? - Mr_Keystrokes - Sep-12-2017

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!


RE: What is causing the syntax error? - wavic - Sep-12-2017

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.