If-Statements
If-statements let you change the flow of control in a Python program. Essentially, they let you write programs that can decide, while the programming is running, whether or not to run one block of code or another. Almost all nontrivial programs use one or more if-statements, so they are important to understand.
If/else-statements
Suppose you are writing a password-checking program. You ask users to enter their password, and if it is correct, you log them in to their account. If it is not correct, then you tell them they’ve entered the wrong password. A simple version of that program is this:
# password1.py pwd = input('What is the password? ') if pwd == 'apple': # note use of == # instead of = print('Logging on ...') else: print('Incorrect password.') print('All done!')
It’s pretty easy to read this program: If the string that pwd labels is 'apple', then a login message is printed. But if pwd is anything other than 'apple', the message incorrect password is printed.
An if-statement always begins with the keyword if. It is then (always) followed by a Boolean expression called the if-condition, or just condition for short. After the if-condition comes a colon (:). As we will see, Python uses the : token to mark the end of conditions in if-statements, loops, and functions.
Everything from the if to the : is referred to as the if-statement header. If the condition in the header evaluates to True, then the statement print('Logging on ...') is immediately executed, and print('Incorrect password.') is skipped and never executed.
If the condition in the header evaluates to False, then print('Logging on ...') is skipped, and only the statement print('Incorrect password.') is executed.
In all cases, the final print('All done!') statement is executed.
The general structure of an if/else-statement is shown in Figure 4.1.
Figure 4.1 This flow chart shows the general format and behavior of an if/else-statement. The code blocks can consist of any number of Python statements (even other if-statements!).