In this section, we are going to learn how to use
if statements to affect the way our code runs in Python. Let's
write a program to check if a number is positive or negative to see
this in action:
number = int(input("Enter a number: "))
First, we can use an if statement to check if a number is positive. To
start an if statement, we use the Python keyword if
. After
that, we include the condition that we learned about last
time. In this case, our condition will be something like
number > 0
, because all positive numbers are larger
than 0. After the condition, we always have to put a colon to indicate
the end of the line. On the next lines, we put whatever we want to
happen if the condition is true, making sure to indent each
line. Here, if the condition is True
, we want to inform
the user that their number is positive:
number = int(input("Enter a number: "))
if number > 0:
print(f"{number} is positive")
Notice that if we enter a number that is greater than 0, the condition
is True
, and the line is printed to the console. But if we
enter a number less than 0, the condition is False
, the
computer skips over everything in the if statement, and nothing gets
printed to the console.
Now, let's also tell the user if their number is negative. To do that,
we can add on an elif
statement to our if statement.
elif
is short for "else if", and this section acts just
like our original if
section, except the computer only
looks at it if the condition in the if statement is False
.
Otherwise, the computer skips right over it. So if
number > 0
is False
, we can then check if
number < 0
and inform the user that their number is
negative:
number = int(input("Enter a number: "))
if number > 0:
print(f"{number} is positive")
elif number < 0:
print(f"{number} is negative")
Now if we test this again, we see we get proper outputs for both
positive and negative numbers, but nothing for 0, which is neither
positive nor negative. We can use one last tool to include it in our
if
block.
The else
statement is a final catch-all section of an
if
block. It doesn't have any conditions, and it only gets
run if all the other sections fail. In our case, we know that if a
number is not positive and is not negative, it must be 0. So if an
input fails our first two conditions, it has to be 0. Let's add one
final update to our code to reflect this new information:
number = int(input("Enter a number: "))
if number > 0:
print(f"{number} is positive")
elif number < 0:
print(f"{number} is negative")
else:
print("0 is not positive or negative")
A few reminders about if statements:
-
An if statement must start with the keyword
if
, and
can have exactly one only.
-
You can have as many
elif
sections as you want after
an if statement.
-
There can be one
else
section only, and it must be at
the very end of the if statement.
-
Always put a colon at the end of the statement, and indent
everything inside the body.