Python - If Statement

> Procedural Languages > Python > Python - Grammar (Package | Module)

1 - About

3 - Example

if x < 0:
    x = 0
    print 'Negative changed to zero'
elif x == 0:
    print 'Zero'
elif x == 1:
    print 'Single'
else:
    print 'More'

4 - Example 2

The block of code in Python is indented with 4 spaces. See Python Grammar - Code Block

Syntax:

if expression1:
    code block line 1 if the expression1 is true
    code block line 2 if the expression1 is true
elif expression2:
    code block line 1 if the expression2 is true
    code block line 2 if the expression2 is true
else:
    code block line 2 if expression1 and expression2 are false
    code block line 2 if expression1 and expression2 are false

Example:

if "Nico" <> "Gerard":
    print "Nico isn't Gerard!"

Nested if/else:

if condition:
    if other_condition:
        # Do something
    else:
        # Do something else!
else:
    # Do yet another thing
Advertising

5 - Documentation / Reference