Think about as spoken. Let's say there's bucket of balls. You reach in and pull out a ball. if/else: # English: If the ball is yellow, say "yellow", otherwise say "not yellow" if ball.color == 'yellow': say('yellow') else: say('not yellow') if/elif/else: # English: If the ball is yellow, say "yellow". # Else, if the ball is red, say "red". # Else, if the ball is blue, say "blue". # Else, say "different color than expected" if ball.color == 'yellow': say('yellow') elif ball.color == 'red': say('red') elif ball.color == 'blue': say('blue') else: say('different color than expected') And, there are no dumb questions. Answer from totallygeek on reddit.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-if-else
Python If Else Statements - Conditional Statements - GeeksforGeeks
May 21, 2026 - Python · i = 10 if i == 10: if ... than 15 i is smaller than 12 too · The if-elif-else statement is used to check multiple conditions one by one....
🌐
DataCamp
datacamp.com › tutorial › elif-statements-python
elif Statements in Python: A Guide to Conditional Logic | DataCamp
June 25, 2020 - Conditional statements are one of the first real building blocks of programming logic in Python. ... if-elif-else lets you check multiple conditions in sequence, executing the block tied to the first one that's true.
Discussions

What is the difference between else and elif?
Think about as spoken. Let's say there's bucket of balls. You reach in and pull out a ball. if/else: # English: If the ball is yellow, say "yellow", otherwise say "not yellow" if ball.color == 'yellow': say('yellow') else: say('not yellow') if/elif/else: # English: If the ball is yellow, say "yellow". # Else, if the ball is red, say "red". # Else, if the ball is blue, say "blue". # Else, say "different color than expected" if ball.color == 'yellow': say('yellow') elif ball.color == 'red': say('red') elif ball.color == 'blue': say('blue') else: say('different color than expected') And, there are no dumb questions. More on reddit.com
🌐 r/learnpython
28
33
July 23, 2021
python - Most efficient way of making an if-elif-elif-else statement when the else is done the most? - Stack Overflow
Copymatt$ python Python 2.6.8 (unknown, Nov 26 2012, 10:25:03) [GCC 4.2.1 Compatible Apple Clang 3.0 (tags/Apple/clang-211.12)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> >>> from timeit import timeit >>> timeit(""" ... if something == 'this': pass ... elif something == 'that': pass ... elif something == 'there': pass ... else... More on stackoverflow.com
🌐 stackoverflow.com
Very Simple Calculator Help
But that shouldn't be an issue if the other operators work. I'm not sure why it only raises the error in divide so these suggestions are kinda hacky fixes. ... You might try specifying str(input()) to set the input as a string. ... I would think maybe an install or version issue but again, the others working rule that out. @fizzlesticks has more of a handle on python ... More on linustechtips.com
🌐 linustechtips.com
7
June 28, 2016
Is it bad practice to use else-if/elif instead of an else?
relation1 has no default return case if none of the if statements match (not speaking specifically about this exact code, just in general), whereas relation2 does. If you require a default return value, use the relation2 style. If you're only referring to this exact code, I would rewrite it to: def result(a, b): if (a == b): return "equal" else: return "higher" if (a > b) else "lower" More on reddit.com
🌐 r/learnprogramming
10
0
April 18, 2022
🌐
W3Schools
w3schools.com › python › python_if_else.asp
Python Else Statement
Note: The else statement must come last. You cannot have an elif after an else. ... number = 7 if number % 2 == 0: print("The number is even") else: print("The number is odd") Try it Yourself »
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-if-else
if, if-else, Nested if and if-elif Statements - Python
May 21, 2026 - Python · i = 10 if i == 10: if ... than 15 i is smaller than 12 too · The if-elif-else statement is used to check multiple conditions one by one....
🌐
W3Schools
w3schools.com › python › python_conditions.asp
Python If Statement
Python can evaluate many types of values as True or False in an if statement. Zero (0), empty strings (""), None, and empty collections are treated as False. Everything else is treated as True.
Find elsewhere
Top answer
1 of 9
125

The code...

options.get(something, doThisMostOfTheTime)()

...looks like it ought to be faster, but it's actually slower than the if ... elif ... else construct, because it has to call a function, which can be a significant performance overhead in a tight loop.

Consider these examples...

1.py

something = 'something'

for i in xrange(1000000):
    if something == 'this':
        the_thing = 1
    elif something == 'that':
        the_thing = 2
    elif something == 'there':
        the_thing = 3
    else:
        the_thing = 4

2.py

something = 'something'
options = {'this': 1, 'that': 2, 'there': 3}

for i in xrange(1000000):
    the_thing = options.get(something, 4)

3.py

something = 'something'
options = {'this': 1, 'that': 2, 'there': 3}

for i in xrange(1000000):
    if something in options:
        the_thing = options[something]
    else:
        the_thing = 4

4.py

from collections import defaultdict

something = 'something'
options = defaultdict(lambda: 4, {'this': 1, 'that': 2, 'there': 3})

for i in xrange(1000000):
    the_thing = options[something]

...and note the amount of CPU time they use...

1.py: 160ms
2.py: 170ms
3.py: 110ms
4.py: 100ms

...using the user time from time(1).

Option #4 does have the additional memory overhead of adding a new item for every distinct key miss, so if you're expecting an unbounded number of distinct key misses, I'd go with option #3, which is still a significant improvement on the original construct.

2 of 9
87

I'd create a dictionary :

options = {'this': doThis,'that' :doThat, 'there':doThere}

Now use just:

options.get(something, doThisMostOfTheTime)()

If something is not found in the options dict then dict.get will return the default value doThisMostOfTheTime

Some timing comparisons:

Script:

from random import shuffle
def doThis():pass
def doThat():pass
def doThere():pass
def doSomethingElse():pass
options = {'this':doThis, 'that':doThat, 'there':doThere}
lis = range(10**4) + options.keys()*100
shuffle(lis)

def get():
    for x in lis:
        options.get(x, doSomethingElse)()

def key_in_dic():
    for x in lis:
        if x in options:
            optionsx
        else:
            doSomethingElse()

def if_else():
    for x in lis:
        if x == 'this':
            doThis()
        elif x == 'that':
            doThat()
        elif x == 'there':
            doThere()
        else:
            doSomethingElse()

Results:

>>> from so import *
>>> %timeit get()
100 loops, best of 3: 5.06 ms per loop
>>> %timeit key_in_dic()
100 loops, best of 3: 3.55 ms per loop
>>> %timeit if_else()
100 loops, best of 3: 6.42 ms per loop

For 10**5 non-existent keys and 100 valid keys::

>>> %timeit get()
10 loops, best of 3: 84.4 ms per loop
>>> %timeit key_in_dic()
10 loops, best of 3: 50.4 ms per loop
>>> %timeit if_else()
10 loops, best of 3: 104 ms per loop

So, for a normal dictionary checking for the key using key in options is the most efficient way here:

if key in options:
   optionskey
else:
   doSomethingElse()
🌐
Nanyang Technological University
libguides.ntu.edu.sg › python › ifelifelse
1.13 Conditional statements (if-elif-else) - Python for Basic Data Analysis - LibGuides at Nanyang Technological University
x = 10 if x > 20: print("x is bigger than 10.") elif x = 20: print("x is equals to 20.") else: print("x is neither bigger than 10 or equal to 20.") ... 2. If-else - Assign -50 to y. If x is bigger than 0, print "x is a positive number".
🌐
Programiz
programiz.com › python-programming › if-elif-else
Python if, if...else Statement (With Examples)
Therefore, the statements inside the elif block is executed. In the above program, it is important to note that regardless the value of number variable, only one block of code will be executed. It is possible to include an if statement inside another if statement.
🌐
IDTech
idtech.com › blog › what-does-elif-mean-in-python
What Does "elif" Mean in Python? | Conditional Statement Examples
In Python, elif is short for "else if" and is used when the first if statement isn't true, but you want to check for another condition. Meaning, if statements …
🌐
PythonForBeginners.com
pythonforbeginners.com › home › python if…elif…else statement
Python If...Elif...Else Statement - PythonForBeginners.com
May 22, 2020 - x = raw_input("What is the time?") if x < 10: print "Good morning" elif x<12: print "Soon time for lunch" elif x<18: print "Good day" elif x<22: print "Good evening" else: print "Good night" You can also use it to control that only specified users can login to a system. # Allowed users to login allowed_users = ['bill', 'steve'] # Get the username from a prompt username = raw_input("What is your login? : ") # Control if the user belongs to allowed_users if username in allowed_users: print "Access granted" else: print "Access denied" To get an easy overview of Pythons if statement code block
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.14.6 documentation
There can be zero or more elif parts, and the else part is optional. The keyword ‘elif’ is short for ‘else if’, and is useful to avoid excessive indentation. An if … elif …
🌐
Godot Engine
docs.godotengine.org › en › stable › tutorials › scripting › gdscript › gdscript_basics.html
GDScript reference — Godot Engine (stable) documentation in English
GDScript is a high-level, object-oriented, imperative, and gradually typed programming language built for Godot. It uses an indentation-based syntax similar to languages like Python. Its goal is to...
🌐
Linus Tech Tips
linustechtips.com › software › programming
Very Simple Calculator Help - Programming - Linus Tech Tips
June 28, 2016 - number = int(input("What is your first number you want to work with??\n")) if(number%2>0): print("Your number is odd") else: print("Your number is even") number_2= int(input("What is another number you want to work with?\n")) if(number_2%2>0): ...
🌐
Kaggle
kaggle.com › code › ealtili › python-3-if-elif-else-statements
Python 3 - IF/ELIF/ELSE Statements | Kaggle
December 23, 2018 - Explore and run AI code with Kaggle Notebooks | Using data from No attached data sources
🌐
Great Learning
mygreatlearning.com › blog › it/software development › else if python: understanding the nested conditional statements
Else if Python: Understanding the Nested Conditional Statements
October 14, 2024 - In Python programming, the "else if" statement, often called "elif," is a conditional statement that allows you to specify multiple conditions to be evaluated sequentially.
🌐
Learn X in Y Minutes
learnxinyminutes.com › python
Learn Python in Y Minutes
Indentation is significant in Python! # Convention is to use four spaces, not tabs. # This prints "some_var is smaller than 10" if some_var > 10: print("some_var is totally bigger than 10.") elif some_var < 10: # This elif clause is optional. print("some_var is smaller than 10.") else: # This ...
🌐
Simplilearn
simplilearn.com › home › resources › software development › your ultimate python tutorial for beginners › python if-else statement: syntax and examples
If Else Statement in Python: Syntax and Examples Explained
1 week ago - The if-else statement is used to execute both the true part and the false part of a given condition. If the condition is true, the if block code is executed.
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
Google AI
ai.google.dev › gemini api › gemini thinking
Gemini thinking | Gemini API | Google AI for Developers
2 weeks ago - from google import genai client = genai.Client() interaction = client.interactions.create( model="gemini-3.6-flash", input="What is the sum of the first 50 prime numbers?", generation_config={ "thinking_summaries": "auto" } ) for step in interaction.steps: if step.type == "thought": print("Thought summary:") if step.summary: for content_block in step.summary: if content_block.type == "text": print(content_block.text) print() elif step.type == "model_output": for content_block in step.content: if content_block.type == "text": print("Answer:") print(content_block.text) print()
🌐
Tutorial Teacher
tutorialsteacher.com › python › python-if-elif
Python - if, else, elif conditions (With Examples)
The following example demonstrates if, elif, and else conditions. ... price = 50 if price &gt; 100: print("price is greater than 100") elif price == 100: print("price is 100") else price &lt; 100: print("price is less than 100")