Conditional Statements


  Conditional Statements

        Conditional statements help in making a decision based on certain conditions. These conditions are specified by a set of conditional statements having Boolean expressions which are evaluated to true or false. In programming languages most of the time we have to control the flow of the execution of your program, you want to execute some set of statements only if the given condition is satisfied and a different set of statements when it is not satisfied. Which we also call it as control statements or decision making statements.

We use this statements when we want to execute a block of code when the given condition is true or false.

In Python, we use different types of conditional statements :

  1. If statements
  2. If-else statements
  3. Nested-if statements
  4. Elif statement


If statements

    If statement is one of the most commonly used conditional statement in most of the programming languages. An if statement consists of a Boolean expression followed by one or more statements. It decides whether certain statement need to be executed or not. If statements checks for a given condition, if the condition is true,then the set of code present inside the if black will be executed.
 
The if condition evaluates a Boolean expression and executes the block of code only when the boolean expression becomes True.

Syntax :

 if(Conditional expression): 
            statement(s) to execute            #Execute if the condition is true
    
If keyword and the conditional expression is ended with a colon. Conditional expression returns a Boolean value means True or False. If the resulting value is True then the statement is executed,which is mentioned below the if condition with a tabspace (this Indentation is very important).

Flow Chart :


If you observe the flow chart,first controller will come to an if condition. if it is true, then the statements will be executed otherwise the code present outside the block will be executed.

Example :

Value=100

if(value=100):

     print("value of expression is 100")

print("good bye!")

Output :

value of expression is 100

good bye!

Short hand if :

      If you have only one statement to execute you can put it on the same line as the if statement.

Example :

if (a>b): print("a is greater than b")








No comments:

Post a Comment