Python if Statement
Python if Statement
The Python if statement can execute either a simple or compound statement depending on the result of the expression. An if statement consists of a conditional expression followed by a code block of one or more statements. A conditional expression results in either true or false.
if Statement Syntax
The general syntax of the Python if statement is as follows:
if conditional_expression:
statement(s)
The program evaluates the conditional_expression and will execute statement(s) only if the expression evaluates to True. If the conditional_expression is False, the statement(s) is not executed. Python interprets non-zero values as True. None and 0 are interpreted as False.
In Python, code indentation is mandatory. The indented statement always marks the beginning of a block, and the unindented statement marks the closing of a block. Therefore, the body of the if statement is indicated by the indentation. The body starts with an indentation, and the first unindented line marks the end.
Example
An example of an if statement is used to determine whether a number is even.
# Python program using if statement # Python Tutorials - www.TestingDocs.com number = input('Enter a number:') number = int(number) if number % 2 == 0: print('Inside if block') print('The given number is even') print('Outside if block')
In the example, number%2 ==0 is the logical conditional expression. The body of the if statement is executed only if this expression is evaluated as True.
For instance, when the user enters 18, the expression is true, and then the indented statement under if gets executed.
Enter a number: 18
Inside if block
The given number is even
Outside if block
When the user enters 71, the logical expression is false, and then the indented if block will not be executed.
Enter a number:71
Outside if block
Note that the unindented print() statement falls outside of the if code block. Hence, it is executed regardless of the conditional expression. The control reaches this statement regardless of the if block execution.
—
Python Tutorials
Python Tutorial on this website can be found at:
More information on Python is available at the official website: