Python else/elif syntax error

  • Python
  • Thread starter clope023
  • Start date
  • #1
987
123

Main Question or Discussion Point

Hello, the title says it all; I am trying to teach myself Python using version 2.7.1 aka matplotlib or PYLAB via the MIT opencourseware as well as the tutorial from the site I downloaded it from; I am having a very frustrating time using it as system continues to return any variant of else statements as syntax errors.

An attempted example program is as follows:

x = 2

if (x/2)*2 == x:
... print 'Even'
... else: print 'Odd'
....
....
'Even'

This would be my expected output but, python continues to give me a syntax error whenever I use the else statement. I've tried it without the colons, I've tried added the else's command on another line, I've tried using the elif function and nothing works the editor contiues to give syntax errors.

I know I'm using the correct code as I am pulling several examples from the tutorial and they've all been correct except this one. Does python 2.7.1 not recognize else statements? Does anyone know if the syntax has changed? Does anyone know the correct syntax? Any and all help is greatly appreciated.
 
Last edited:

Answers and Replies

  • #2
D H
Staff Emeritus
Science Advisor
Insights Author
15,393
683
The else statement needs to be indented at the same level as the if, the else suite needs to be on a separate line (or lines), and this suite needs to be indented at the same at the same level as the if suite. e.g.

Code:
...
if (x/2)*2 == x:
   print 'Even'
else:
   print 'Odd'
...
 
  • #3
987
123
The else statement needs to be indented at the same level as the if, the else suite needs to be on a separate line (or lines), and this suite needs to be indented at the same at the same level as the if suite. e.g.

Code:
...
if (x/2)*2 == x:
   print 'Even'
else:
   print 'Odd'
...
Thanks very much!
 

Related Threads on Python else/elif syntax error

Replies
1
Views
896
  • Last Post
Replies
22
Views
4K
  • Last Post
Replies
7
Views
850
  • Last Post
Replies
9
Views
3K
  • Last Post
Replies
3
Views
2K
  • Last Post
Replies
8
Views
3K
Replies
18
Views
851
Replies
4
Views
799
Replies
5
Views
4K
Top