Difference between multiple if's and elif's?

PythonIf Statement

Python Problem Overview


In python, is there a difference between say:

if text == 'sometext':
    print(text)
if text == 'nottext':
    print("notanytext")

and

 if text == 'sometext':
        print(text)
 elif text == 'nottext':
        print("notanytext")

Just wondering if multiple ifs could cause any unwanted problems and if it would be better practice to use elifs.

Python Solutions


Solution 1 - Python

Multiple if's means your code would go and check all the if conditions, where as in case of elif, if one if condition satisfies it would not check other conditions..

Solution 2 - Python

An other easy way to see the difference between the use of if and elif is this example here:

def analyzeAge( age ):
   if age < 21:
       print "You are a child"
   if age >= 21: #Greater than or equal to
       print "You are an adult"
   else:   #Handle all cases where 'age' is negative 
       print "The age must be a positive integer!"

analyzeAge( 18 )  #Calling the function
>You are a child
>The age must be a positive integer!

Here you can see that when 18 is used as input the answer is (surprisingly) 2 sentences. That is wrong. It should only be the first sentence.

That is because BOTH if statements are being evaluated. The computer sees them as two separate statements:

  • The first one is true for 18 and so "You are a child" is printed.
  • The second if statement is false and therefore the else part is executed printing "The age must be a positive integer".

The elif fixes this and makes the two if statements 'stick together' as one:

def analyzeAge( age ):
   if age < 21:
       print "You are a child"
   elif age > 21:
       print "You are an adult"
   else:   #Handle all cases where 'age' is negative 
       print "The age must be a positive integer!"

analyzeAge( 18 )  #Calling the function
>You are a child

Edit: corrected spelling

Solution 3 - Python

def multipleif(text):
    if text == 'sometext':
        print(text)
    if text == 'nottext':
        print("notanytext")

def eliftest(text):
    if text == 'sometext':
        print(text)
    elif text == 'nottext':
        print("notanytext")

text = "sometext"

timeit multipleif(text)
100000 loops, best of 3: 5.22 us per loop

timeit eliftest(text)
100000 loops, best of 3: 5.13 us per loop

You can see that elif is slightly faster. This would be more apparent if there were more ifs and more elifs.

Solution 4 - Python

Here's another way of thinking about this:

Let's say you have two specific conditions that an if/else catchall structure will not suffice:

Example:

I have a 3 X 3 tic-tac-toe board and I want to print the coordinates of both diagonals and not the rest of the squares.

Tic-Tac-Toe Coordinate System

I decide to use and if/elif structure instead...

for row in range(3):
    for col in range(3):
        if row == col:
            print('diagonal1', '(%s, %s)' % (i, j))
        elif col == 2 - row:
            print('\t' * 6 + 'diagonal2', '(%s, %s)' % (i, j))

The output is:

diagonal1 (0, 0)
						diagonal2 (0, 2)
diagonal1 (1, 1)
						diagonal2 (2, 0)
diagonal1 (2, 2)

But wait! I wanted to include all three coordinates of diagonal2 since (1, 1) is part of diagonal 2 as well.

The 'elif' caused a dependency with the 'if' so that if the original 'if' was satisfied the 'elif' will not initiate even if the 'elif' logic satisfied the condition as well.

Let's change the second 'elif' to an 'if' instead.

for row in range(3):
    for col in range(3):
        if row == col:
            print('diagonal1', '(%s, %s)' % (i, j))
        if col == 2 - row:
            print('\t' * 6 + 'diagonal2', '(%s, %s)' % (i, j))

I now get the output that I wanted because the two 'if' statements are mutually exclusive.

diagonal1 (0, 0)
						diagonal2 (0, 2)
diagonal1 (1, 1)
						diagonal2 (1, 1)
						diagonal2 (2, 0)
diagonal1 (2, 2)

Ultimately knowing what kind or result you want to achieve will determine what type of conditional relationship/structure you code.

Solution 5 - Python

elif is just a fancy way of expressing else: if,

Multiple ifs execute multiple branches after testing, while the elifs are mutually exclusivly, execute acutally one branch after testing.

Take user2333594's examples

	def analyzeAge( age ):
	   if age < 21:
	       print "You are a child"
	   elif age > 21:
	       print "You are an adult"
	   else:   #Handle all cases were 'age' is negative 
	       print "The age must be a positive integer!"

could be rephrased as:

	def analyzeAge( age ):
	   if age < 21:
	       print "You are a child"
	   else:
			 if age > 21:
	             print "You are an adult"
		     else:   #Handle all cases were 'age' is negative 
		         print "The age must be a positive integer!"

The other example could be :

def analyzeAge( age ):
	   if age < 21:
	       print "You are a child"
       else: pass #the if end
	   if age > 21:
	       print "You are an adult"
	   else:   #Handle all cases were 'age' is negative 
	       print "The age must be a positive integer!"

Solution 6 - Python

In your above example there are differences, because your second code has indented the elif, it would be actually inside the if block, and is a syntactically and logically incorrect in this example.

Python uses line indentions to define code blocks (most C like languages use {} to enclose a block of code, but python uses line indentions), so when you are coding, you should consider the indentions seriously.

your sample 1:

if text == 'sometext':
    print(text)
elif text == 'nottext':
    print("notanytext")

both if and elif are indented the same, so they are related to the same logic. your second example:

if text == 'sometext':
    print(text)
    elif text == 'nottext':
        print("notanytext")

elif is indented more than if, before another block encloses it, so it is considered inside the if block. and since inside the if there is no other nested if, the elif is being considered as a syntax error by Python interpreter.

Solution 7 - Python

When you use multiple if, your code will go back in every if statement to check the whether the expression suits your condition. Sometimes, there are instances of sending many results for a single expression which you will not even expect. But using elif terminates the process when the expression suits any of your condition.

Solution 8 - Python

Here's how I break down control flow statements:


# if: unaffected by preceding control statements
def if_example():
	if True:
		print('hey')
	if True:
		print('hi')  # will execute *even* if previous statements execute

will print hey and hi


# elif: affected by preceding control statements
def elif_example():
	if False:
		print('hey')
	elif True:
		print('hi')  # will execute *only* if previous statement *do not*

will print hi only because the preceding statement evaluated to False


# else: affected by preceding control statements
def else_example():
	if False:
		print('hey')
	elif False:
		print('hi')
	else:
		print('hello')  # will execute *only* if *all* previous statements *do not*

will print hello because all preceding statements failed to execute

Solution 9 - Python

In the case of:

if text == 'sometext':
  print(text)
if text == 'nottext':
  print("notanytext")

All the if statements at the same indentation level are executed even if only the first if statement is True.

In the case of:

 if text == 'sometext':
        print(text)
 elif text == 'nottext':
        print("notanytext")

When an if statement is True, the preceding statements are omitted/ not-executed.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBilljkView Question on Stackoverflow
Solution 1 - PythonavasalView Answer on Stackoverflow
Solution 2 - PythonPeloView Answer on Stackoverflow
Solution 3 - PythonyrekkehsView Answer on Stackoverflow
Solution 4 - PythonMikeView Answer on Stackoverflow
Solution 5 - PythonAbstProcDoView Answer on Stackoverflow
Solution 6 - PythonfarzadView Answer on Stackoverflow
Solution 7 - PythonHarish RSView Answer on Stackoverflow
Solution 8 - PythonZach ValentaView Answer on Stackoverflow
Solution 9 - PythonSujithView Answer on Stackoverflow