What is elif in Java

4. Control structures¶

4.1.1. If, elif, else¶

The simplest way of differentiating between cases is the instruction. It looks like this:

ifCondition: # statement header statement # | ... # | Statement body statement # |

This consists of one

  • Statement header that contains a condition and a
  • Statement body (code block) which is executed depending on the result of the condition.

In other words, IF condition is met, then do what it says in the instruction body. E.g.

ifx <1: print "x less than 1"

comment

  • The instruction header ends with a.
  • The instruction body is indented!
  • The same indentation as that means the statement is outside the statement body!

The figure if statement graphically shows this as a flow chart.

if statement graphically

If you want to check another condition (if the first was), you use an - statement.

ifCondition1: # Check condition 1 statement # | ... # | if condition 1 true instruction # | elif condition 2: # check condition 2 instruction # | ... # | if Bed 2 true statement # |

Example:

ifx <1: print "x less than 1" elifx == 1: print "x equals 1"

If an instruction is to be executed if neither of the two conditions apply, an instruction is used.

ifCondition1: # Check condition 1 statement # | ... # | if condition 1 true instruction # | elif condition 2: # check condition 2 instruction # | ... # | if Bed 2 true statement # | else: # else statement # | ... # | if Bed 1 and 2 False Statement # |

Example:

ifx <1: print "x less than 1" elifx == 1: print "x equals 1" else: print "x is greater than 1"

This type of case distinction can also be used to implement control structures (such as in Java or C ++). Example ():

The illustration of the if-elif-else statement shows this as a flow chart.

if-elif-else statement graphically

ifcolor == "red": print "color red" eliffarbe == "blue": print "color blue" eliffarbe == "yellow": print "color yellow" else: print "color", color, "not known!"

The most common uses are - constructs (IF - then - ELSE):

ifCondition: # Check BedAnweisung # | ... # | if TrueInstruction # | else: # ElseInstruction # | ... # | if Bed False statement # |

Note

If possible, always add loops! This makes programming errors easier to spot.