View Single Post
Old 2019-11-24, 01:49   #11
Dylan14's Avatar
Mar 2017

2×33×11 Posts
Default If/else, part 2: the elif command

In the last section, we learned about the if command and the else command. This allowed us to run a piece of code if a logical expression was true, and another thing if it was false. Now suppose instead we want to have more than two code snippets (for example, one if a logical expression is true, another one if that logical statement is false, but a second logical statement is true, and a third if both logical statements are false). We can do this by using the elif command.

The elif statement:

The elif statement works very much like the if statement. The statement has the following syntax:

There is a few things to keep in mind when you use the elif command:

1. There must be an if statement prior to the first invocation of the elif statement. If you don't do this, or you have a bare elif statement, you will get a SyntaxError.
2. You can have as many elif statements as you want. You have to make sure that each of these have the same indent level as the if statement that precedes all of the them, or you will get a SyntaxError.
3. If there is a else statement, it must be after all elif statements.
4. The same syntax that applies for if and else applies for the elif statement.

Putting it all together:

With the if, else and elif statements, we can build the most general if statement that we can make in Python. This works as follows:

     #code to run if expr1 is true
     #code to run if expr1 is false, but expr2 is true
     #code to run if expr1 and expr2 are false, but expr3 is true
     #code to run if expr1, expr2, ..., exprnminus1 are false, but exprn is true
     #code to run if all n expressions are false
Again, note the indentations.
With this construct, we can build recursion relations(*), or complex checks.

#code to check the sign of a number
num = input("Enter an integer: ")
if(int(num) > 0):
  print(str(num) + " is positive")
elif(int(num) == 0):
  print(str(num) + " is zero")
  print(str(num) + " is negative")
This code uses if, elif and else to test whether an integer is positive, negative or zero.
It's important to try limiting cases: try the following inputs:
2 (positive)
0 (zero)
-167 (negative)
b (an error should occur)

(*) Recursion relations can be defined in functions. We will cover these in a future section of the guide.
Dylan14 is offline