Conditions
if, elif and else, comparisons, and the remainder operator.
Choosing what to do
Until now every line always ran. With if, the program decides whether to run a block of code, based on a condition:
grade = int(input("What is the grade? "))
if grade >= 55:
print("You passed")
else:
print("Not this time")Notice two things: the colon at the end of the if line, and the indentation (four spaces) of the lines inside it. In Python indentation is part of the code: it marks what belongs to the condition.
Comparisons
A condition is an expression whose result is True or False:
| Sign | Meaning |
|---|---|
== | equal (two equals signs) |
!= | not equal |
<, > | less than, greater than |
<=, >= | less or equal, greater or equal |
More than two options
if grade >= 90:
print("Excellent")
elif grade >= 55:
print("Pass")
else:
print("Fail")Python checks the conditions in order and runs only the first one that holds. So a grade of 95 prints "Excellent", not "Pass" as well.
The remainder
The operator % gives the remainder of whole-number division. For any two integers and (with ) there is a quotient and a remainder such that
In Python a // b gives and a % b gives . For example 17 % 5 is 2. The most common use: an even number is one whose remainder when divided by 2 is 0.
n = int(input("A number: "))
if n % 2 == 0:
print("even")
else:
print("odd")