Conditional statments are a large part of writing computer programs and switches. You want to take some sort of input, evaluate it, then take some action based on what the input was. The decision you make about what to do is called a conditional statement.
The first conditional statement we will look at is an if statement as shown below.
x=1 if x>2: print "Higher" if x<2: print “Lower"
The above script gives X a value of 1. It then evaluates X and prints Higher if X is larger than 2. There is then a second if statementevaluating if X is less than 2. It will then print Lower if X is less than 2.
Right away, you can see that this is not the most efficient method. We can improve it a bit by adding an else statement:
x=1 if x>2: print "Higher" Else: print “Lower"
The above script will evaluate X and print Higher if x is larger than 2. In all other cases, it will print Lower. This works except, what if X is equal to 2? It will then print Lower. But that is not an accurate depiction of X.
In our third example, we are adding the ElseIf evaluator. This lets you add a third scenario when doing your evaluation:
x=2 if x>2: print "Higher" elif x==2: print "Equal" else: print "Lower"
In the above example, if X =2, it will print Equal. If X is larger than 2, it will print Higher, and if X is lower than 2, it will print Lower. We have now accounted for all states of X.
In our last example of an If statememt, we will check if X is greater than or Equal to 2:
x=2 if x>=2: print “Equal or Greater” else: print “Less than"
In the above scenario, if X is greater than or equal to 2, it will print “Equal or Greater”. Otherwise it will print “less than”.