Decision making one of the fundamentals operations in programming languages and applications. We mostly use decisions to implements applications logic. The primary mechanism for decisions in Python is
if..elif..else keywords. We can simple call them
if-else . In this tutorial we will look different aspects and usage examples of
If is used to check whether given condition is true and run some code. So we need some condition and some code block. The syntax of if is like below.
if CONDITION CODE_BLOCK
Now we can understand if with an example better. In this example we check if 0 is less than 10 .
if( 0 < 10 ): print("0 is less than 10")
Because given condition returned
True the code block executed and printed.
If we want to check multiple conditions in a single step and run code block accordingly we can use
If-Elif statement. We can provide multiple conditions like below.
if CONDITION: CODE_BLOCK elif CONDITION: CODE_BLOCK ... elif CONDITION: CODE_BLOCK
We can understand if-elif with an example where we check 3 conditions.
a= 7 if ( a > 10 ): print("$a is greater than 10") elif (a > 0): print("$a is between 10 and 0") elif (a <0): print("$a is lower than 0")
First elif is executed and related text printed.
As we have seen previous parts we can define limitless conditions and code blocks. There is a special conditions which is triggered when none of the previous conditions are met. We call this as
else and put at the end of the
if-elif code block.
Else do not need any specific condition.
In this example we can guess the given number with
a= -7 if ( a > 10 ): print("$a is greater than 10") elif (a >= 0): print("$a is between 10 and 0") else: print("$a is lower than 0")
Providing Multiple Conditions
Up to now we have defined single conditions in order to check. We can also use complex or multiple conditions in a single keyword. We generally use
( ) to group multiple or complex conditions. All inner conditions are computed and at the end single boolean value true or false returned.
(1 < 10 and 10 > 1) (1 < 10 and 10 != 10) (1 < 10 or 10 != 10)