297

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.

Paul Turner
  • 38,949
  • 15
  • 102
  • 166

6 Answers6

455

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:'))
Frames Catherine White
  • 27,368
  • 21
  • 87
  • 137
  • 12
    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: http://docs.python.org/3.1/ the important links are Tutorial: http://docs.python.org/3.1/tutorial/index.html Language reference: http://docs.python.org/3.1/reference/index.html Library refernce: http://docs.python.org/3.1/library/index.html – Frames Catherine White Mar 07 '10 at 10:37
  • 1
    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. – Nate Glenn Oct 06 '15 at 23:54
  • 1
    @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 ` vs. `#else ` would've complicated a syntax that was intended to be bog-simple. – FeRD May 30 '18 at 19:46
  • 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. – thebiggestlebowski May 23 '21 at 09:30
21

Do you mean elif?

Nick Presta
  • 28,134
  • 6
  • 57
  • 76
13
def function(a):
    if a == '1':
        print ('1a')
    elif a == '2':
        print ('2a')
    else:
        print ('3a')
Tom
  • 21,468
  • 6
  • 39
  • 44
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()
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • 1
    You can, but please do not do this. A dictionary is not a good replacement for an `elif`. – S.Lott Mar 07 '10 at 05:09
  • @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. – ghostdog74 Mar 07 '10 at 05:27
  • 1
    @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 `exec`ing them. Is this good practice? Can you name an example? – msw Mar 07 '10 at 05:35
  • @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 `` is `do_foo`, you can even build the dict on the fly when the app starts up. – John Machin Mar 07 '10 at 06:52
  • 1
    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")`` – codeape May 31 '13 at 10:19
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".

Frames Catherine White
  • 27,368
  • 21
  • 87
  • 137
Winston C. Yang
  • 1,497
  • 2
  • 18
  • 27
  • 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 – Dan D. Aug 26 '10 at 14:07
  • 2
    should be `('1', '2')`, the op is using strings – priestc Dec 20 '11 at 16:23
3
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.

MilkyWay90
  • 2,023
  • 1
  • 9
  • 21