if statement in python

The "If" statement in Python provides conditional flow of statements in a python program."If"consists one if suit, multiple elif suits and one else suit.

If Updated 28 Sep 2016 1 min read

Overview

The "if" statement is an essential control flow statment in any programming language.
The "if" statement executes one of the blocks of python code based on a logical value,either
True or False, returned from a Python Expression. Hence, the "if" statment is a conditional statement.

##

Flowchart diagram for Python if Statement

Syntax of an "if" statment in Python

python
if <expression>:

        Python Statement 1

        Python Statement 2

        .

        .

        .

        Python Statement n

    elif  <expression>:

        Python Statement 1

        Python Statement 2

        .

        .

        .

        Python Statement n

    else:

        Python Statement 1

        Python Statement 2

        .

        .

        .

        Python Statement n

Semantics of an "if" statment in Python

  • One whole block of "if" statement can consist of
  • One "if" suit
  • Multiple suits of "elif" statements ("elif" stands for "else if" in Python Programming Language)
  • One "else" suit
  • Only one of the suits, either an "if" suit or an "elif" suit or an "else" suit will be executed, based on the boolean result of the expression provided.
  • Python does not provide a switch-case block like the ones found in other programming languages.
  • The "if" statement in the Python Programming Language also works similar to a ternary operator in other programming languages.
  • The expression in the "if" statement can not be an assignment statment. Python really keeps things very simple, as defined in one of the language goals.

Example - Python "if" statement

python
AnyInteger = input("Enter a Value:")

            if AnyInteger%2 == 0 :

                print("Integer entered is an even number")

            else

                print("Integer entered is an odd number")