What is the correct syntax for else if in Python?

I’m a new Python programmer transitioning from version 2.6.4 to 3.1.1, and I’ve hit a small snag understanding the else if Python syntax.

I tried using else if like I would in other languages, but the interpreter throws a syntax error after the if.

Here’s my function:

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

I’m guessing this isn’t the correct else if Python approach.

What am I missing here, and how should conditional branching be written properly in Python 3?

In Python, the else if you’re used to from other languages like C++ or JavaScript is actually written as a single word: elif.

It’s one of those Python-specific keywords that throws off folks transitioning from other languages.

So your function should look like this:

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

Just remember that elif replaces both else and if, you don’t need both separately.

Once you start using it, it feels pretty natural in Pythonic flow.

What tripped me up early on was that Python isn’t just syntactically different, it intentionally avoids certain language constructs to stay clean and readable.

elif is Python’s way of chaining conditions, and unlike other languages, indentation is mandatory.

So even a perfect elif can fail if the spacing is off.

Here’s a corrected example with the structure and spacing Python expects:

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

Watch out for things like mixing tabs and spaces, that’s a sneaky cause of errors in conditionals.

Another thing that might help if you’re debugging a syntax error after transitioning from 2.x is checking your actual runtime version.

Sometimes you think you’re running 3.1.1, but the system defaults to 2.6 or an older Python binary.

Run python --version or python3 --version to double-check.

Assuming it’s Python 3, using elif is the only valid way to handle multiple branches:

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

It’s clean, no parentheses needed, and once you get used to elif, it’s one less thing to type compared to other languages.