Reputation: 10686
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 if
s could cause any unwanted problems and if it would be better practice to use elif
s.
Upvotes: 122
Views: 130338
Reputation: 818
An other easy way to see the difference between the use of if and elif is this example here:
# According to the UN Convention of the Rights of the Child
ADULT_AGE = 18
def analyze_age(age):
if age < ADULT_AGE and age > 0:
print("You are a child")
if age >= ADULT_AGE:
print("You are an adult")
else:
print("The age must be a positive integer!")
analyze_age(16)
>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 elif fixes this and makes the two if statements 'stick together' as one:
def analyze_age(age):
if age < ADULT_AGE and age > 0:
print("You are a child")
elif age >= ADULT_AGE:
print("You are an adult")
else:
print("The age must be a positive integer!")
analyze_age(16)
>You are a child
Upvotes: 71
Reputation: 11
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.
Upvotes: 1
Reputation: 1879
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
Upvotes: 1
Reputation: 71
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.
Upvotes: 3
Reputation: 797
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.
Upvotes: 17
Reputation: 22083
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!"
Upvotes: 5
Reputation: 341
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.
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.
Upvotes: 7
Reputation: 8855
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.
Upvotes: 3
Reputation: 14854
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..
Upvotes: 185