if statement

A statement that runs a block of code only when a condition holds, optionally with an else block for when it does not.

In more detail

Most languages add further cases with else if or elif. In Python the condition is an expression judged true or false and the block is indented. In shell scripts the condition is a command judged by its exit status, and fi closes the block. The shape is the same whether the block has one statement or many.

Examples

if grep -q bash poem.txt; then echo "found it"; fi
if weight > 50:
    print("Extra charge")
else:
    print("OK")

Related terms

Taught in

References

Certification courses