Python - If Statement

Card Puncher Data Processing

About

Grammar - If Statement in Python

See also: Python - Control flow (Comparator, Boolean Operator and Conditional Statement)

Example

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

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

Documentation / Reference





Discover More
Card Puncher Data Processing
Python - Control flow (Comparator, Boolean Operator and Conditional Statement)

in Python Equal to (==) Not equal to (!=) Less than (<) Less than or equal to (<=) Greater than (>) Greater than or equal to (>=) In (for a string or a list) Comparisons generate...



Share this page:
Follow us:
Task Runner