Menu
Home
Log in / Register

 
Home arrow Computer Science arrow Python Programming Fundamentals
< Prev   CONTENTS   Next >

2 Decision Making

In this chapter we explore how to make choices in our programs. Decision making is valuable when something we want to do depends on some user input or some other value that is not known when we write our program. This is quite often the case and Python, along with all interesting programming languages, has the ability to compare values and then take one action or another depending on that outcome.

For instance, you might write a program that reads data from a file and takes one action or another based on the data it read. Or, a program might get some input from a user and then take one of several actions based on that input.

To make a choice in Python you write an if statement. An if statement takes one of two forms. It may be just an if statement. In this case, if the condition evaluates to true then it will evaluate the then statements. If the condition is not true the computer will skip to the statements after the if statement.

< statements before if statement > if < condition >:

< then statements >

< statements after if statement >

Figure 2.1 depicts this graphically. An if statement evaluates the conditional expression and then goes to one of two places depending on the outcome. Notice the indentation in the if statement above. The indentation indicates the then statements are part of the if statement. Indentation is very important in Python. Indentation determines the control flow of the program. Figure 2.1 graphically depicts this as well. If the condition evaluates to true, a detour is taken to execute the then statements before continuing on after the if statement.

Generally, we want to know if some value in our program is equal to, greater, or less than another value. The comparison operators, or relational operators, in Python allow us to compare two values. Any value in your program, usually a variable, can be compared with another value to see how the two values relate to each other.

Figure 2.2 lists the operators you can use to compare two values. Each of these operators is written between the two values or variables you want to compare. They evaluate to either true or false depending on the two values. When the condition

Fig. 2.1 If statement

Operator

Condition

<

Less Than

>

Greater Than

<=

Less Than or Equal to

>=

Greater Than or Equal to

==

Equal to

!=

Not Equal to

Fig. 2.2 Relational operators

evaluates to true, the then statements are executed. Otherwise, the then statements

are skipped.

Example 2.1 An if statement is best described by giving an example. Assumewe want to see if a number entered by a user is divisible by 7.We can write theprogram pictured in Fig. 2.3 to decide this. The program gets some input fromthe user. Remember that input reads a string from the user. The int converts thestring to an integer. Then, the num variable is checked to see if it is divisible by7. The % is called the modulo or just the mod operator. It gives us the remainderafter dividing by the divisor (i.e. 7 in this case). If the remainder after dividingby 7 is 0 then the number entered by the user is divisible by 7.

An important feature of a debugger is the ability to step over our code and watch the computer execute each statement. This is called stepping over or stepping into our

Fig. 2.3 Stepping into and over

code. Figure 2.3 depicts how this is done. For now stepping into and stepping over code do relatively the same thing. To begin stepping through a program you press the Step Into button. Once the program is started, you press the Step Over button to avoid jumping to other code that your program might call. Stepping into and over code can be very useful in understanding exactly what your program is doing.

Practice 2.1 Write a short program that asks the user to enter the name ofa month. If the user enters “December” your program should print “MerryChristmas!”. No matter what you enter, your program should print “Have aHappy New Year!” just before the program terminates. Then, use Step Into andStep Over to execute each statement that you wrote. Run your program at leasttwice to see how it behaves when you enter “December” and how it behaveswhen you enter something else.

Sometimes, you may want your program to do one thing if a condition is true and something else if a condition is false. Notice that the if statement does something only when the condition evaluates to true and does not do anything otherwise. If you want one thing to happen when a condition is true and another to happen if the condition is false then you need to use an if-else statement. An if-else statement adds a keyword of else to do something when the condition evaluates to false. An if-else statement looks like this.

< statements before if statement > if < condition >:

< then statements > else :

< else statements >

< statements after if statement >

If the condition evaluates to true, the then statements are executed. Otherwise, the else statements are executed. Figure 2.4 depicts this graphically. The control of your program branches to one of two locations, the then statements or the else statements depending on the outcome of the condition.

Again, indentation is very important. The else keyword must line up with the if statement to be properly paired with the if statement by Python. If you don't line up the if and the else in exactly the same columns, Python will not know that the if and the else go together. In addition, the else is only paired with the closest if that is in the same column. Both the then statements and the else statements must be indented and must be indented the same amount. Python is very picky about indentation because indentation in Python determines the flow of control in the program.

In the case of the if-else statement, either the then statements or the else statements will be executed. This is in contrast to the if statement that is described in Fig. 2.1. When learning about if statements this seems to be where some folks get stuck. The statements that are conditionally executed are those statements that are indented under the if or the else.

In either case, after executing the if or the if-else statement control proceeds to the next statement after the if or if-else. The statement after the if-else statement is the next line of the program that is indented the same amount as the if and the else.

Fig. 2.4 If-else statement

Example 2.2 Consider a program that finds the maximum of two integers. Thelast line before the if-else statement is the y = assignment statement. The firstline after the if-else statement is the print(“Done.”) statement.

1 x = i n t ( i n p u t ("Please enter an integer:"))

2 y = i n t ( i n p u t ("Please enter another integer:"))

3 i f x > y:

4 p r i n t (x,"is greater than",y)

5 e l s e :

6 p r i n t (y,"is greater than or equal to",x)

7 p r i n t ("Done.")

Practice 2.2 Modify the program from practice Problem 2.1 to print “MerryChristmas!” if the month is December and “You'll have to wait” otherwise. Itshould still print “Have a Happy New Year!” in either case as the last line ofoutput. Then run the program at least twice using step into and over to see howit behaves when “December” is entered and how the program behaves whenanything else is entered.

 
Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >
 
Subjects
Accounting
Business & Finance
Communication
Computer Science
Economics
Education
Engineering
Environment
Geography
Health
History
Language & Literature
Law
Management
Marketing
Philosophy
Political science
Psychology
Religion
Sociology
Travel