I'm a beginner in Python currently self-learning via the book "How to Think like a Computer Scientist" From an exercise from the book on Chained Conditionals, Syntax taught was:
def function(x,y)
if ..:
print ".."
elif..:
print ".."
else:
print".."
However, when I tried this to find out if its legal, it worked:
def function (x,y)
if ..:
print ".."
if ..:
print ".."
Is the latter a correct syntax? Or is it not even considered a chained conditional? I would like to find out that even if this is legal in Python, is it a "good way" to write the code?
All kind help is sincerely appreciated.
Though your second example is working, it is not the same thing as the first example. In the second, every if
condition will be evaluated, regardless of whether or not a previous one was true and executed. In the chained if/elif
example, the whole thing is treated as a unit and only the first matched condition will be executed.
# An if/elif chain
a = 2
b = 3
if a == 2:
print "a is 2"
elif b == 3:
print "b is 3"
else:
print "whatever"
# prints only
"a is 2"
# even though the b condition is also true.
# Sequential if statements, not chained
a = 2
b = 3
if a == 2:
print "a is 2"
if b == 3:
print "b is 3"
# prints both
"a is 2"
"b is 3"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With