We use the if
statement to check if a
condition is True
and if it is
True
, we run a corresponding set of steps which are
specified in a separate block. A block of
statements is specified using indentation, that is, using spaces or
tabs.
Let us consider an example.
Example 6.1. if statement
#!/usr/bin/env python # Filename: if1.py age = 22 # mention your age here if age >= 18: # notice the colon print 'You are old enough to vote now!' # use tabs or 4 spaces for indentation
In this example, we are printing a message about whether the user is eligible to vote or not, depending on his/her age. Here, we assume that you need to be 18 years old to vote for an election.
The if statement starts with the if
keyword followed by a condition. In this case, the condition is
whether the user's age is greater than or equal to 18. The
condition is followed by a colon at the end of the line followed
by a block of statements.
Notice that the new block of statements is marked using indentation. Indentation means making use of whitespace. Remember that we have already discussed how to use indentation (hint: 4 spaces or tabs).
This new block is also called the if
clause
since this block is executed only if the
condition is True
. In our if clause, we have a
simple message to indicate that you are legal to vote.
In case, the condition is False
,
currently our program does not do anything. To indicate that the
user will not be able to vote, we can use an else
clause:
Example 6.2. if-else statement
#!/usr/bin/env python # Filename: if2.py age = 17 # mention your age here if age >= 18: # notice the colon print 'You are old enough to vote now!' # use tabs or 4 spaces for indentation else: print 'Sorry, you are not old enough to vote'
$ python if2.py Sorry, you are not old enough to vote
The else
clause is part of the
if
statement and it can have a corresponding block of
statements that will be executed if the if
condition is False
.