What is the correct syntax for 'else if'?

user269857 picture user269857 · Mar 7, 2010 · Viewed 339.7k times · Source

I'm a new Python programmer who is making the leap from 2.6.4 to 3.1.1. Everything has gone fine until I tried to use the 'else if' statement. The interpreter gives me a syntax error after the 'if' in 'else if' for a reason I can't seem to figure out.

def function(a):
    if a == '1':
        print ('1a')
    else if a == '2'
        print ('2a')
    else print ('3a')

function(input('input:'))

I'm probably missing something very simple; however, I haven't been able to find the answer on my own.

Answer

Lyndon White picture Lyndon White · Mar 7, 2010

In python "else if" is spelled "elif".
Also, you need a colon after the elif and the else.

Simple answer to a simple question. I had the same problem, when I first started (in the last couple of weeks).

So your code should read:

def function(a):
    if a == '1':
        print('1a')
    elif a == '2':
        print('2a')
    else:
        print('3a')

function(input('input:'))