if statement in python


  • The boolean expression after the if statement is called the condition.
  • We end the if statement with a colon character (:) and the line(s) after the if statement are indented.
  • If the logical condition is true, then the indented statement gets executed. If the logical condition is false, the indented statement is skipped.
  • An if statement consists of a boolean expression followed by one or more statements. Python uses the keyword if to execute a set of command lines or one command line when logical condition is true. It has only one option.
  • There is no limit on the number of statements that can appear in the body, but there must be at least one.
  • Occasionally, it is useful to have a body with no statements (usually as a place holder for code you haven’t written yet).
  • In that case, you can use the pass statement, which does nothing.

Syntax

    if expression:
       statement(s)

Flow Diagram

    if statement in python language

Example

    If you enter an if statement in the Python interpreter, the prompt will change from three chevrons to three dots to indicate you are in the middle of a block of statements, as shown below:

    >>> x = 3
    >>> if x < 10:
         print('Small')
    

Output

    Small