Conditional Statements

  • Decision making statements in programming languages decides the direction of flow of program execution.
  • Decision making statements available in python are also known as if..else statment

Version of If ..else statment

  • if statement
  • if..else statements
  • nested if statements
  • if-elif ladder
  • Short Hand if statement
  • Short Hand if-else statement

If statement

  • It is used to decide whether a certain statement or block of statements will be executed or not.
if condition:

  # Statements to execute if

  # condition is true

If- Else

The else statement with if statement to execute a block of code when the condition is false.

if (condition):

  # Executes this block if

  # condition is true

else:

  # Executes this block if

  # condition is false

Nested-If

Python allows us to nest if statements within if statements.

if (condition1):

  # Executes when condition1 is true

   if (condition2):

    # Executes when condition2 is true

If-elif-else ladder

  • The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed.
  • If none of the conditions is true, then the final else statement will be executed.
if (condition):

  statement

elif (condition):

  statement . .

else: statement

Short Hand if statement

Syntax:

if condition: statement

The statement can be put on the same line as the if statement.

Short Hand if-else statement

Syntax:

statement_True if condition else statement_False

This can be used to write the if-else statements in a single line.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *