Using the if-else Structure


Using the if-else Structure

Sometimes you'll want your program to "make a choice" based on a condition: do one thing if the condition is true, do something else if it's false. The if-else structure gives you that power.

Introducing the Granted or Denied Program

The program Password did a good job welcoming a user who entered the correct password, but it didn't do anything if the wrong password was entered. Program Granted or Denied solves this problem by using the if-else structure. Figures 3.5 and 3.6 show off the new and improved version.

click to expand
Figure 3.5: The correct password grants the user access, just like before.

click to expand
Figure 3.6: Now, an incorrect password generates the stinging "Denied" message.

Here is the code for Granted or Denied:

 # Granted or Denied # Demonstrates the if-else 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" else:     print "Access Denied" raw_input("\n\nPress the enter key to exit.") 

Examining the else Statement

I only made one change from the Password program. I added an else clause to create an if-else structure:

 if password == "secret":     print "Access Granted" else:     print "Access Denied" 

If the value of password is equal to "secret", the program prints Access Granted, just like before. But now, thanks to the else statement, the program prints Access Denied otherwise.

In an if-else structure, you're guaranteed that exactly one of the code blocks will execute. If the condition is true, then the block immediately following the condition is executed. If the condition is false, then the block immediately after the else is executed.

You can create an else clause immediately following the if block with else, followed by a colon, followed by a block of statements. The else statement must be in the same block as its corresponding if. That is, the else and if must be indented the same amount; otherwise, your program will generate a nasty error.




Python Programming for the Absolute Beginner
Python Programming for the Absolute Beginner, 3rd Edition
ISBN: 1435455002
EAN: 2147483647
Year: 2003
Pages: 194

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net