Branching is a fundamental part of computer programming. It basically means making a decision to take one path or another. Through the if structure, your programs can branch to a section of code or just skip it, all based on how you've set things up.
The Password program uses the if structure to simulate the login procedure of a highly secure computer server. The program grants the user access if he or she enters the right password. Figures 3.3 and 3.4 show a few sample runs.
Figure 3.3: Ha, you'll never crack the code.
Figure 3.4: Guess I should have picked a better password than "secret".
Here is the program code for Password:
# Password # Demonstrates the if structure # Michael Dawson - 12/29/02 print "Welcome to System Security Inc." print "— where security is our middle name\n" password = raw_input("Enter your password: ") if password == "secret": print "Access Granted" raw_input("\n\nPress the enter key to exit.")
While the program Password does a good job of demonstrating the if structure, it's not a good example of how to implement computer security. In fact, anyone could simply examine the source code and discover the "secret" password.
To create a password validation system, a programmer would most likely use some form of cryptography. Cryptography, an ancient idea that dates back thousands of years, is used to encode information so that only the intended recipients can understand it. Cryptography is an entire field unto itself and some computer scientists devote their careers to it.
The key to program Password is the if structure:
if password == "secret": print "Access Granted"
The if structure is pretty straightforward. You can probably figure out what's happening just by reading the code. If password is equal to "secret", then "Access Granted" is printed and the program continues to the next statement. But, if it isn't equal to "secret", the program does not print the message and continues directly to the next statement following the if structure.
All if structures have a condition. A condition is just an expression that is either true or false. You're already familiar with conditions. They're pretty common in daily life. In fact, almost any statement you make could be viewed as a condition. For example, the statement "It's 100 degrees outside." could be treated as a condition. It's either true or false.
In the Password program, the condition used in the if structure is password == "secret". It means that password is equal to "secret". This condition evaluates to either true or false, depending on the value of password. If the value of password is equal to "secret", then the condition is true. Otherwise, the condition is false.
Conditions are often created by comparing values. You can compare values using comparison operators. You've already seen one comparison operator by way of the Password program. It's the equal-to comparison operator, written as ==.
TRAP | The equal-to comparison operator is two equal signs in a row. Using just one equal sign in a condition will result in a syntax error, because one equal sign represents the assignment operator. So, password = "secret" is an assignment statement. It assigns a value. And password == "secret" is a condition. It evaluates to either true or false. Even though the assignment operator and the equal-to operator look similar, they are two different things. |
In addition to equal-to, there are other comparison operators. Table 3.1 summarizes some useful ones.
Operator | Meaning | Sample Condition | Evaluates To |
---|---|---|---|
== | equal to | 5 == 5 | True |
!= | not equal to | 8 != 5 | True |
> | greater than | 3 > 10 | False |
< | less than | 5 < 8 | True |
>= | greater than or equal to | 5 >= 10 | False |
<= | less than or equal to | 5 <= 5 | True |
Using comparison operators, you can compare any values. If you compare strings, you get results based on alphabetical order. For example, "apple" < "orange" is true because "apple" is alphabetically less than "orange" (it comes before it in the dictionary).
Python allows you to compare any values you like, regardless of their type. But just because you can doesn't mean you should. When using comparison operators, it's best to "compare apples to apples and oranges to oranges" and only compare values of the same type, because even though you can create the condition "orange" < 2, it doesn't really make much sense. (If you're curious, "orange" < 2 is false.)
You may have noticed that the second line of the if structure, print "AccessGranted", is indented. By indenting the line, it becomes a block. A block is one or more consecutive lines indented by the same amount. Indenting sets lines off not only visually, but logically too. Together, they form a single unit.
Blocks can be used, among other ways, as the last part of an if structure. They're the statement or group of statements that gets executed if the condition is true. In the Password program, the block is the single statement print "Access Granted".
Since blocks can be as many statements as you like, you could add a special welcome for users who enter the proper password by changing the block in the if structure like so:
if password == "secret": print "Access Granted" print "Welcome! You must be someone very important."
Now, users who correctly enter the secret password will see the Access Granted followed by Welcome! You must be someone very important. And if a user enters something besides secret, the user won't see either of the messages.
Indenting to create blocks is not optional. It's the only way to define a block. This is one of Python's more unique features. And believe it or not, it's one of it's most controversial.
If you've programmed in another language before, odds are, indenting was optional. You could have written every line of code flush left, if you wanted. But required indentation has its benefits. It makes for more consistent and readable code. After a short time, it'll become second nature.
If you haven't programmed before, don't worry about it. By indenting your code, you'll pick up a good programming habit without even realizing it.
HINT | There's passionate debate within the Python community about whether to use tabs or spaces (and if spaces, the number to use) for indentation. This is really a question of personal style. But there are two guidelines worth following. First, be consistent. If you indent blocks with two spaces, then always use two spaces. Second, don't mix spaces and tabs. Even though you can line up blocks using a combination of both, this can lead to big headaches later. Common indentation styles include one tab, or two spaces, or (the style the creator of Python uses) four spaces. The choice is yours. |
You've seen a full example of an if structure, but I want to leave the topic by summarizing how to build your own. You can construct an if structure by using if, followed by a condition, followed by a colon, followed by a block of one or more statements. If the condition evaluates to true, then the statements that make up the block are executed. If the condition evaluates to false, then the program moves on to the next statement after the if structure.