FTB01 – Conditional Logic

Previous – Variables and Functions

One of the greatest capabilities of programming languages is the ability to do conditional logic. A definition of this is simple;

if (something is true)
   do something
else
   do something else

Yes – it is really that simple, of course it can be more and more complex as the logic necessary to make decisions becomes more and more complex. There are 2 things to think about here (1) the syntax of the if and else and (2) the syntax of the something is true portion. So lets start easy.

x = 1
y = 1

if (x > 0):
    if (y > 0):         
        print("Northeast Quadrant")
    else:        
        print("Southeast Quadrant")
else:
    if (y > 0):
        print("Northwest Quadrant")
    else:
        print("Southwest Quadrant")

Here is some code for a simple logic to determine if a point is in a specific quadrant. Notice that it does contain a second embedded if/else statement. The first if determines if x is positive or negative and that will determine east or west of the origin. The embedded if statement compares the y values and determines north (y > 0 ) or south (y < 0). With the values 1,1 it should be (and is) in the Northeast Quadrant.

The other part of the conditional logic is within the if statement – the condition, again we will look at this with code. This code will do exactly the same thing as the previous code. Note that the if statement now must process a condition an another condition.

if((x > 0) and (y > 0)):
    print("Northeast Quadrant")
if((x > 0) and (y < 0)):
    print("Southeast Quadrant")
if((x < 0) and (y > 0)):
    print("Northwest Quadrant")
if((x < 0) and (y < 0)):
    print("Southwest Quadrant")

Another useful construct is the elif, which basically means else if. here is an example of this. In the previous examples we did not handle the x = 0 or the y = 0 cases, here we do using an elif.

if (x > 0):
    if (y > 0):         
        print("Northeast Quadrant")
    elif (y == 0):
        print("East on Equator")
    else:        
        print("Southeast Quadrant")
else:
    if (y > 0):
        print("Northwest Quadrant")
    elif (y == 0):
        print ("West on Equator")
    else:
        print("Southwest Quadrant")

As you can see handling conditional logic is rather easy and powerful. Additional resources are included here if you need more help.

Programiz Python Tutorials – https://www.programiz.com/python-programming/if-elif-else

Next: