Simple-if Statement In Python


Simple-if Statement

In order to write useful programs, we almost always need the ability to check conditions and change the behaviour of the program accordingly. Selection or Conditional statements give us this ability. The simplest form is the if statement:

General syntax of if statement

 STATEMENT(S) # executed if condition evaluates to True

Here, the program evaluates the TEST EXPRESSION and will execute statement(s) only if the text expression is True. If the text expression is False, the statement(s) is not executed.

A few important things to note about if statements:

1. The colon (:) is significant and required. It separates the header of the compound statement from the body.

2. The line after the colon must be indented. It is standard in Python to use four spaces for indenting.

3. All lines indented the same amount after the colon will be executed whenever the BOOLEAN_EXPRESSION is true.

4. Python interprets non-zero values as True. None and 0 are interpreted as False.

if Statement Flowchart


 mark = 102
 if mark >= 100:
     print(mark, " is a Not a valid mark.")
 print("This is always printed.")


 102  is a Not a valid mark.
 This is always printed.

The boolean expression after the if statement (here mark>=100)is called the condition. If it is true, then all the indented statements get executed.

There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven’t written yet). In that case, you can use the pass statement, which does nothing.

Read Also: