⁉️What is an if statement?

Conditional execution.

As it stands right now, we've seen Python as a series of statements that we execute one after another. However, we may wish to, on occasion, conditionally execute a piece of code. For example, if a variable a is set to 1, we want to print "Hello!", print "World!" if it is set to 2, or print "Bye" otherwise. We can do so through if statements.

if (a == 1):
    print("Hello!")
elif (a == 2):
    print("World!")
else:
    print("Bye")

In an if-else block, Python will only ever execute one suite of statements.

Something fascinating happens in if-statements. Not only does Python not run the statements for which the condition is not True, it does not even execute them β€”Β errors are ignored. Consider the following:

a = 1
if (a == 1):
    print("Hello!")
else:
    print(1/0)

This code does not error, because Python never ends up reading the else-block β€”Β the condition is True, and the if suite is executed instead.

Evaluating if Statement Conditions

In our section on Data Types, we had talked about truth-y and false-y values. If conditions basd on such values check for their truthiness or falsiness by the same design. For example

if a:
    print("Hello")
else:
    print("World")

Setting a=1 would print Hello, while setting a=0 would print World.

Last updated