Python - Statement if Statements

General Format

The Python if statement is like most procedural languages.

It takes the form of an if test, followed by one or more optional elif ("else if") tests and a final optional else block.

The tests and the else part each have an associated block of nested statements.

The general form of an if statement looks like this:

if test1:                 # if test 
    statements1           # Associated block 
elif test2:               # Optional elifs 
    statements2 
else:                     # Optional else 
    statements3 

Basic Examples

All parts are optional, except the initial if test and its associated statements.

Thus, in the simplest case, the other parts are omitted:

if 1: 
    print('true') 

To handle a false result, code the else:

Demo

if not 1: 
    print('true') 
else: # from  w  w  w  . jav  a  2 s.  com
    print('false')

Result

Related Topics