Conditionals
Conditionals are statements that do different things under different conditions. For example, you might want your program to do one thing for even numbers, and a different thing for odd numbers. We use if
, elif
(short for “else if”), and else
to outline the conditions and the code that should run for
each condition.
For each if
and elif
line, we write a condition using comparison:
- equal to:
==
- not equal to:
!=
- less than, less than or equal to:
<
,<=
- greater than, greater than or equal to:
>
,>=
is
/is not
,is in
/is not in
The else
catches anything that doesn’t get caught by the if
/elif
statements.
Pay attention to the colons :
and the indentation in the conditional at left. These are both important! You’ll get a syntax error if you leave them out. Syntax means the rules about structure and formatting, and a syntax error means you’ve broken one of those rules!
An if
is the only necessary part of a conditional: you can have as many elif
s as you want, or none at all, and you can put an else
at the end or not.