if
statements / conditionals / selection statements
An if
statement is a control structure that we use to create branches in our code. This means that our code can do one thing under certain circumstances and another thing under different circumstances.
control structure: a part of the language that allows us to dictate when and how (and how many times) certain pieces of code are run. We can consider functions to be one type of control structure. (Though they are so important that they just get to be called functions most of the time).
Let’s take a look at the syntax of an if
statement:
if logical_expression:
# do something
For instance, take a look at the code in the following cell.
# TODO: run this code!
# Under what circumstances is "big number" printed out?
# Answer:
number = int(input("number? "))
if number > 100:
print("big number")
print("done")
if
statements are like forks in the road for our code. If the logical expression evaluates to True
, the code within the statement (indented) will be run, otherwise it won’t be. When the code inside the statement finishes running, the program continues executing as normal from the end of the statement.
# TODO: write your own if statement here!