Conditions in Python

                           If....else...

Decision making is important part of programming. We come across many situations where we have to choose something during coding like whether it will print success or failure, something like that. Like other programming language, in Python also we have If...else conditions. If true then this else that. 
By using If..else we only select the block of code we want to execute. We can also use nested if...else. In nesed if...else we have multiple if..else conditions inside the former conditions which we will see in example.
Syntax : if condition:
            statements
       else:
            statements

E.g.  x = 10
    if x <= 10:
        print("x is low.")
    else:
        print("x is high.")

    output : x is low

In above example as we can see that we have used identation which represents the particular block of code. 
E.g. (nested if...else) 
        x = 5
    y = 10
    if x < 5:
        print("can not proceed futher")
    else:
        if y < 5:
            print("Sorry we are over here.")
        else:
            print("Success!")
        
        output : Success!

This above example shows that we have used multiple if...else inside each other incresing the depth of condition checking.
We check the condition in if block otherwise we execute the else part, means we do not check the condition in else block. You can assume of else block as the final executing part if no condition satisfies. What if we have multiple conditions to check? Well we deinitley not use if one after other.
We have another keyword to use i.e. elif. elif represents that if above condition not satifies then try this one.
E.g.  marks = 70
    if marks > 90:
        print("A grade")
    elif marks < 90 and marks >70:
        print("B grade")
    else:
        print("C grade")

        output : C grade

and is the logical operator which checks the both conditions and if both are true then it returns true else false. or is the logical operator which checks the both condition if anyone is true it return true.

If we do not have anything to execute in the block then we can simply put the pass keyword there. Think of it as a placeholder.
E.g.  x = 0:
    if x < 0:
        pass
    else:
        print("0 or greater.")
    
    output : 0 or greater.

We can also use if...else in shorthand manner, means in a single line.
E.g.  x = 50
    print("Fail") if x < 70 else print("Pass")

        output : Fail

Comments

Popular posts from this blog

Loops in Python

Python OOPs

Regular Expressions