Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Syntax for Chained Conditionals

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.

like image 409
Jason HJH. Avatar asked May 03 '12 14:05

Jason HJH.


1 Answers

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.

For example:

# 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.

However

# 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"
like image 151
Michael Berkowski Avatar answered Nov 07 '22 03:11

Michael Berkowski