Sunday, June 30, 2019

if, if..else, if..elif..else

When you need to execute code if and only if a certain condition is met then you can use the if statement. If statements can be very simple or very complex.

if

In it's simplest form an if statement in python looks like if a == b: <<statement>>

if a == b: a = 100
One liner if statements are sometimes pointed at as not pythonic due to readability. But I believe this is unfounded when the statement is very short.

Indentation is very important when writing structures such as if statements in python. If we expand the above statement to two lines the if statement only executes lines that are indented.

if a == b: 
  a = 100
  b = 0
  c = random(1,0)
d = 1 #always executes 

if..else

You can also use the keyword else that will only execute if the condition in the conditional expression is false. You can only have one else in an if statement. The following example will always print hello because the condition is the literal value True.


if False:
  pass
else:
  print("Hello")
The pass keyword in python just tells python to do nothing. Many programming languages allow you to write a comment or simply leave a blank line but python requires an empty if to at least have pass statement in its body.

You can put several if statements together if you have multiple conditions and statements to run.

if s == "Hello":
  print("World")

if s2 == "":
  print("The string is empty")

if s3 == "abc"
  print("I know my abcs")

if..elif..else

If you want to check multiple conditions but only if the previous condition(s) are false then use the if..elif structure. The following example is very similar to the above series of if statements but each condition is only evaluated if the previous condition is false.

if s == "Hello":
  print("World")
elif s2 == "":
  print("The string is empty")
elif s3 == "abc":
  print("I know my abcs")
The keyword elif just means else if. The makers of python just wanted to save three stroke on a keyboard!

The else statement must go at the end of this series of statements. It will be executed if all if and elif conditions are false. For example:

if s == "Hello":
  print("World")
elif s2 == "":
  print("The string is empty")
elif s3 == "abc":
  print("I know my abcs")
else:
  print("Nothing else was true!")

Backwards If Statements

You can also put an if statement proceeding another statement in python. Unlike the first example this version of a one liner if statement is considered good form and is very useful when converting raw data into something readable. The else is required in this case because otherwise the variable has no assignment if the condition is false.


s = "Not Entered" if s == "" else s
Notice that you don't need the colon (:) in this statement

You may be tempted to add an elif to the above example but it will not work. The elif statement doesn't apply to this if structure.


#This will not run. The elif keyword is not valid here
s = "Not Entered if s == "" elif s == "*" "Err" else s

Nested If Statements

In python, and in most modern programming languages for that matter, you can nest or place if statements within if statements for more complex conditions.

a = 1
b = 1
c = 1
d = 1
if a == b:
  if a == c:
    if a == d:
      print("a b c and d are all equal")
else:
  print("a is not equal to b")

The above example is pretty lengthy and is for demonstration purposes. It can be written instead, without nested if statements, as:

a = b = c = d = 1
if a == b == c == d:
   print("a b c and d are all equal")
else:
   print("a is not equal to b")

You can also nest if, if..elif..else statements inside of the else and elif statement bodies like this:


a = b = c = d = 10
if a == b:
  if a == c:
    pass
  elif a == d:
    pass
elif a == 0:
  if a != 1:
    pass
  else:
    print("Hello!")
else:
  print("Hello")

Nesting if statements too deep can lead to unreadable code. Sometimes it is the best solution to the problem but I find that is very rare. It is not often that I need to nest an if statement more than two levels deep in any programming language.

COBOL programs are notorious for having a "dangling if" problem. Reading deeply nested if statements in COBOL is very difficult because its hard to tell, in a very nested if structure, what if statement goes to what else or else if. Python doesn't have this problem because it uses indentation. You can easily see what if, elif, and if statements go together because they are on the same column.

No comments:

Post a Comment

nonlocal keyword

The nonlocal keyword is used to allow an inner function to access variables defined in an outer function. Without using the nonlocal keywo...