Python syntax for encoded conventions

I am starting to study in Python now through the book “How to Think Like a Computer Scientist” From an exercise from a book on encoded conventions, the syntax taught is:

 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 the correct syntax? Or is it not even considered conditional? I would like to know that even if it is legal in Python, is it a “good way” to write code?

Any help is truly appreciated.

+5
source share
2 answers

, , . if , . if/elif , .

:

# 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"
+12

. ( ) if .

, print, print.

+4

All Articles