Python else/elif syntax error

  • Python
  • Thread starter clope023
  • Start date
  • #1
clope023
992
130
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,415
687
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
clope023
992
130
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!
 

Suggested for: Python else/elif syntax error

  • Last Post
Replies
1
Views
1K
Python Python Errors
  • Last Post
Replies
7
Views
1K
  • Last Post
Replies
9
Views
3K
  • Last Post
Replies
3
Views
2K
  • Last Post
Replies
8
Views
3K
Replies
2
Views
821
  • Last Post
Replies
22
Views
4K
Replies
18
Views
1K
  • Last Post
Replies
2
Views
641
  • Last Post
Replies
5
Views
5K
Top