311

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.

3
  • 3
    I don't think this works in 2.6.4. Commented Mar 7, 2010 at 5:38
  • 2
    Indeed, this element of Python syntax and semantics did not change between these versions. Possibly never at all. Commented Mar 7, 2010 at 7:56
  • You can start with a good tutorial on if/else in python: dreamsyssoft.com/python-scripting-tutorial/ifelse-tutorial.php Commented Jan 10, 2013 at 14:05

6 Answers 6

473

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:'))
Sign up to request clarification or add additional context in comments.

5 Comments

no worries, we all have to learn sometime. I find it weird that python places such an elphisise on readbility and then goes and use elkif instead of else it. I suggest keeping the python API manual open at all times: docs.python.org/3.1 the important links are Tutorial: docs.python.org/3.1/tutorial/index.html Language reference: docs.python.org/3.1/reference/index.html Library refernce: docs.python.org/3.1/library/index.html
Perl uses the same keyword, and the rationale for it was to prevent accidents where you forget to finish writing a previous else statement and you start writing another if statement. Apparently that was a common problem while writing C code.
@NateGlenn Perl actually uses elsif, I guess Python had to be that one character more efficient. "Elif" seems to have originated with the C preprocessor, which used #elif long before Python AFAICT. Obviously, in that context having a single-token directive is valuable, since parsing #else if <code> vs. #else <code that could theoretically even be an if statement> would've complicated a syntax that was intended to be bog-simple.
I executed the example. The conditional syntax is correct, but the program doesn't work because the input is parsed to an "int" instead of a "char". If you enter "1" then it prints "3a". This is because the int 1 != char 1. Please fix your example program since it's very confusing to a beginner if they actually run it.
One reason very old languages use this distinct syntax instead of "else if" is that the "else if" introduces a grammar ambiguity. Old parser generators were hard to teach about what to do for ambiguities, so we avoided them. Now, of course, flying cars...
21

Do you mean elif?

Comments

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

Comments

10

since olden times, the correct syntax for if/else if in Python is elif. By the way, you can use dictionary if you have alot of if/else.eg

d={"1":"1a","2":"2a"}
if not a in d: print("3a")
else: print (d[a])

For msw, example of executing functions using dictionary.

def print_one(arg=None):
    print "one"

def print_two(num):
    print "two %s" % num

execfunctions = { 1 : (print_one, ['**arg'] ) , 2 : (print_two , ['**arg'] )}
try:
    execfunctions[1][0]()
except KeyError,e:
    print "Invalid option: ",e

try:
    execfunctions[2][0]("test")
except KeyError,e:
    print "Invalid option: ",e
else:
    sys.exit()

5 Comments

You can, but please do not do this. A dictionary is not a good replacement for an elif.
@s.lott, OP's case is simple. If he has to check for many values of a, a dictionary is neater. you might make it a habit not to use it, but i have been using it and i like this approach better than coding many if/else. heck, i even use dictionary to execute functions.
@ghostdog: I know that you can use dictionaries to execute functions but the idea scares me like computed gotos or pasting Tcl strings together and execing them. Is this good practice? Can you name an example?
@msw: It's very good practice. Example: you are reading an XML stream not for some simple scraping exercise but one where you need to do different processing for different element tags e.g. an Excel 2007 spreadsheet file is a zip of multiple XML documents, some very complex. You have a separate method for each tag. You dispatch via a dictionary. Nothing to be scared of. If the method for handling <foo> is do_foo, you can even build the dict on the fly when the app starts up.
Note that the dictionary has a .get method that lets you specify a default value. Your first example can be written as print d.get(a, "3a")
5
def function(a):
    if a == '1':
        print ('1a')
    else if a == '2'
        print ('2a')
    else print ('3a')

Should be corrected to:

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

As you can see, else if should be changed to elif, there should be colons after '2' and else, there should be a new line after the else statement, and close the space between print and the parentheses.

Comments

4

Here is a little refactoring of your function (it does not use "else" or "elif"):

def function(a):
    if a not in (1, 2):
        a = 3
    print(str(a) + "a")

@ghostdog74: Python 3 requires parentheses for "print".

2 Comments

python 3 replaced python 2's print statement with a function thus the required parentheses, and if you've going to so that you might as well just use sys.stdout.write
should be ('1', '2'), the op is using strings