Brief introduction
In the program we've seen so far, there's always a series of statements that Python faithfully executes them in their order. What if you want to change the order in which the statement flows are executed? For example, you want the program to make decisions that do different things according to different situations, such as "Good Morning" or "evening" according to time.
As you may have guessed, this is achieved through a control flow statement. There are three kinds of control flow statements--if, for, and while in Python.
If statement
If statements are used to verify a condition, and if the condition is true, we run a statement (called a if-block), otherwise we process another statement (called a else-block). else clauses are optional.
Use the IF statement
Example 6.1 using the IF statement
#!/usr/bin/python
# Filename: if.py
number = 23
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.' # New block starts here
print "(but you do not win any prizes!)" # New block ends here
elif guess < number:
print 'No, it is a little higher than that' # Another block
# You can do whatever you want in a block ...
else:
print 'No, it is a little lower than that'
# you must have guess > number to reach here
print 'Done'
# This last statement is always executed, after the if statement is executed
(source file: code/if.py)
Output
$ python if.py
Enter an integer : 50
No, it is a little lower than that
Done
$ python if.py
Enter an integer : 22
No, it is a little higher than that
Done
$ python if.py
Enter an integer : 23
Congratulations, you guessed it.
(but you do not win any prizes!)
Done
How it works