Difference between multiple if's and elif's?
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..
If vs. Elif in Python, which is better?
example1
>>> def foo():
a = 10
if a == 10:
print("condition1")
elif a == 10:
print("condition2")
else:
print(0)
>>> foo()
condition1
>>>
elif is guaranteed not to run when if is true.
example2
def foo():
a = 10
if a == 10:
print("condition1")
if a == 10:
print("condition2")
else:
print(0)
>>> foo()
condition1
condition2
>>>
example3
modify if statement of example2.
if a == 10:
print("condition1")
return a
output
>>> foo()
condition1
10
So, in your case adding a return in first if statement has similar operation like an if-elif block. the (return a) is preventing the second if statement to be executed in example3.
Why use elif and else over multiple if statements?
Well, note that your solution is wrong, since it omits any case for speed
being 60. An if … elif … elif … else …
structure partitions the possibilities: Every possibility falls into one and only one case (or, if the else
is omitted, at most one case). If partitioning is desired, which it often is, a structure of if … if … if …
has two foibles:
- It is possible that multiple cases are executed, if the test conditions are not well designed. To separate the cases, some tests have to be repeated (sometimes in negative forms), as we see in the fact that your solution has to test
speeding <= 60
and60 < speeding
. - Often, in the
…
code in theif
cases, we change variables, sometimes variables that are used in the test conditions, and that can make subsequentif
tests evaluate to true even though we want them to be false. Theelif
construction avoids this.
Difference between Nested IF/ELSE and ELIF?
There is no logical difference. Prefer the second way, using elif
, it's more readable.
Note that at the abstract syntax level, they are exactly equivalent:
>>> s1 = """\
... if something:
... ...
... else:
... if other:
... ...
... else:
... ..."""
...
>>> s2 = """\
... if something:
... ...
... elif other:
... ...
... else:
... ..."""
...
>>> ast.dump(ast.parse(s1)) == ast.dump(ast.parse(s2))
True
Specifically, the elif
form is transformed into the nested if
form of flow control:
>>> ast.dump(ast.parse(s2))
"Module(body=[If(test=Name(id='something', ctx=Load()), body=[Expr(value=Ellipsis())], orelse=[If(test=Name(id='other', ctx=Load()), body=[Expr(value=Ellipsis())], orelse=[Expr(value=Ellipsis())])])])"
>>> # pip install astdump
>>> astdump.indented(s2)
Module
If
Name
Load
Expr
Ellipsis
If
Name
Load
Expr
Ellipsis
Expr
Ellipsis
Is there any difference between using multiple if statements and else if statements?
Yes, potentially. Consider this (C#, Java, whatever):
int x = GetValueFromSomewhere();
if (x == 0)
{
// Something
x = 1;
}
else if (x == 1)
{
// Something else...
}
vs this:
int x = GetValueFromSomewhere();
if (x == 0)
{
// Something
x = 1;
}
if (x == 1)
{
// Something else...
}
In the first case, only one of "Something" or "Something else..." will occur. In the second case, the side-effects of the first block make the condition in the second block true.
Then for another example, the conditions may not be mutually exclusive to start with:
int x = ...;
if (x < 10)
{
...
}
else if (x < 100)
{
...
}
else if (x < 1000)
{
...
}
If you get rid of the "else" here, then as soon as one condition has matched, the rest will too.
Difference between if statements and elif statements in this context?
Ex. 1.
For the first program: each if statement will be evaluated and if the
condition is met, then the block should be executed; if that is the
case then the result should be False.
This statement does not match what your code is actually doing.
print(is_stylish('chocolate', 'ochre'))
cannot return False
, your olny combinations for False
are:
pants_colour == 'chocolate' and shirt_colour == 'orhre' # !note: 'orhre' is not 'ochre'
pants_colour == 'chocolate' and shirt_colour == 'black'
So none of the conditions are met, function doesn't have any other return
, so it returns None.
Ex. 2.
For the second program: if the preceding condition is met then the
following statements would be skipped and lead to the result.
This is correct, in your case, it gets into elif pants_colour == 'blue' and shirt_colour == 'ochre'
and returns True.
Difference: the major difference between 2 examples, besides what you have already mentioned, is that in the example 2 you have else: return False
condition that will cover all the other cases, so if none of the conditions before else
are met, your function will return False, not None.
In the 1st example, if none of the conditions are met, it will just go through all the conditions, won't hit any, and will return None.
Related Topics
R Markdown: How to Make Rstudio Display Python Plots Inline Instead of in New Window
How to Add Sum to Zero Constraint to Glm in Python
R, Python: Install Packages on Rpy2
Fama MACbeth Regression in Python (Pandas or Statsmodels)
Plotting of 2D Data:Heatmap with Different Colormaps
R's Which() and Which.Min() Equivalent in Python
Combine a Folder of Text Files into a CSV with Each Content in a Cell
Install Rpy2 on Windows7 64Bit for Python 2.7
How to Implement R's P.Adjust in Python
Dealing with the Class Imbalance in Binary Classification
Numpy/Scipy Equivalent of R Ecdf(X)(X) Function
How to Get Access of Individual Trees of a Xgboost Model in Python /R
Optimizing for Accuracy Instead of Loss in Keras Model
Learning Python from Ruby; Differences and Similarities
What Is Ruby Equivalent of Python's 'S= "Hello, %S. Where Is %S" % ("John","Mary")'
Typeerror: Can't Use a String Pattern on a Bytes-Like Object in Re.Findall()