βοΈ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.
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:
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
Setting a=1
would print Hello
, while setting a=0
would print World
.
Last updated