Create Account - Sign In
Browse - New Book - My Books - Sell - Groups - $19 ISBNs - Upload / Convert - Help - follow us!   


The function definition and the function call

These statements cause

the message function to

be created.

# This program demonstrates a function.

# First, we define a function named message.

def message():

print('I am Arthur,')

print('King of the Britons.')

# Call the message function.

message()

This statement calls

the message function,

causing it to execute.

Program 3-1 has only one function, but it is possible to define many functions in a program. In fact, it is common for a program to have a main function that is called when the program starts.

The main function then calls other functions in the program as they are needed. It is often said that the main function contains a program’s mainline logic, which is the overall logic of the program. Program 3-2 shows an example of a program with two functions: main and message.

Program 3-2

(two_functions.py)

1

# This program has two functions. First we

2

# define the main function.

3

def main():

4

print('I have a message for you.')

5

message()

6

print('Goodbye!')

7

8

# Next we define the message function.

9

def message():

10

print('I am Arthur,')

11

print('King of the Britons.')

12

13

# Call the main function.

14

main()

Program Output

I have a message for you.

I am Arthur,

King of the Britons.

Goodbye!

The definition of the main function appears in lines 3 through 6, and the definition of the message function appears in lines 9 through 11. The statement in line 14 calls the main function, as shown in Figure 3-3.

3.2 Defining and Calling a Function

87

The first statement in the main function calls the print function in line 4. It displays the string 'I have a message for you'. Then, the statement in line 5 calls the message function. This causes the interpreter to jump to the message function, as shown in Figure 3-4. After the statements in the message function have executed, the interpreter returns to the main function and resumes with the statement that immediately follows the function call. As shown in Figure 3-5, this is the statement that displays the string 'Goodbye!'.

Figure 3-3

Calling the main function

# This program has two functions. First we

# define the main function.

def main():

print('I have a message for you.')

message()

print('Goodbye!')

The interpreter jumps to

# Next we define the message function.

the main function and

def message():

begins executing the

print('I am Arthur,')

statements in its block.

print('King of the Britons.')

# Call the main function.

main()

Figure 3-4

Calling the message function

# This program has two functions. First we

# define the main function.

def main():

print('I have a message for you.')

message()

The interpreter jumps to

print('Goodbye!')

the message function and

begins executing the

# Next we define the message function.

statements in its block.

def message():

print('I am Arthur,')

print('King of the Britons.')

# Call the main function.

main()

Figure 3-5

The message function returns

# This program has two functions. First we

# define the main function.

def main():

print('I have a message for you.')

message()

print('Goodbye!')

When the message

function ends, the

# Next we define the message function.

interpreter jumps back to

def message():

the part of the program that

print('I am Arthur,')

called it, and resumes

print('King of the Britons.')

execution from that point.

# Call the main function.

main()

88

Chapter 3

Simple Functions

That is the end of the main function, so the function returns as shown in Figure 3-6. There are no more statements to execute, so the program ends.

Figure 3-6

The main function returns

# This program has two functions. First we

# define the main function.

def main():

print('I have a message for you.')

message()

print('Goodbye!')

# Next we define the message function.

When the main function

def message():

ends, the interpreter jumps

print('I am Arthur,')

back to the part of the

print('King of the Britons.')

program that called it. There

are no more statements, so

# Call the main function.

the program ends.

main()

N O T E : When a program calls a function, programmers commonly say that the control of the program transfers to that function. This simply means that the function takes control of the program’s execution.

Indentation in Python

In Python, each line in a block must be indented. As shown in Figure 3-7, the last indented line after a function header is the last line in the function’s block.

Figure 3-7

All of the statements in a block are indented

The last indented line is

the last line in the block.

def greeting():

print('Good morning!')

print('Today we will learn about functions.')

print('I will call the greeting function.')

These statements

greeting()

are not in the block.

When you indent the lines in a block, make sure each line begins with the same number of spaces. Otherwise an error will occur. For example, the following function definition will cause an error because the lines are all indented with different numbers of spaces.

def my_function():

print('And now for')

print('something completely')

print('different.')

3.3 Designing a Program to Use Functions

89

In an editor there are two ways to indent a line: (1) by pressing the Tab key at the beginning of the line, or (2) by using the spacebar to insert spaces at the beginning of the line.

You can use either tabs or spaces when indenting the lines in a block, but don’t use both.

Doing so may confuse the Python interpreter and cause an error.

IDLE, as well as most other Python editors, automatically indents the lines in a block.

When you type the colon at the end of a function header, all of the lines typed afterward will automatically be indented. After you have typed the last line of the block you press the Backspace key to get out of the automatic indentation.

T I P : Python programmers customarily use four spaces to indent the lines in a block. You can use any number of spaces you wish, as long as all the lines in the block are indented by the same amount.

N O T E : Blank lines that appear in a block are ignored.

Checkpoint

3.6

A function definition has what two parts?

3.7

What does the phrase “calling a function” mean?

3.8

When a function is executing, what happens when the end of the function’s block is reached?

3.9

Why must you indent the statements in a block?

3.3

Designing a Program to Use Functions

CONCEPT: Programmers commonly use a technique known as top-down design to break down an algorithm into functions.

Flowcharting a Program with Functions

In Chapter 2 we introduced flowcharts as a tool for designing programs. In a flowchart, a function call is shown with a rectangle that has vertical bars at each side, as shown in Figure 3-8. The name of the function that is being called is written on the symbol. The example shown in Figure 3-8 shows how we would represent a call to the message function.

Figure 3-8

Function call symbol

message( )

90

Chapter 3

Simple Functions

Programmers typically draw a separate flowchart for each function in a program. For example, Figure 3-9 shows how the main function and the message function in Program 3-2

would be flowcharted. When drawing a flowchart for a function, the starting terminal symbol usually shows the name of the function and the ending terminal symbol usually reads Return.

Figure 3-9

Flowchart for Program 3-2

main()

message()

Display 'I have a

Display 'I am Arthur'

message for you.'

Display 'King of the

message()

Britons'

Return

Display 'Goodbye!'

Return

Top-Down Design

In this section, we have discussed and demonstrated how functions work. You’ve seen how control of a program is transferred to a function when it is called, and then returns to the part of the program that called the function when the function ends. It is important that you understand these mechanical aspects of functions.

Just as important as understanding how functions work is understanding how to design a program that uses functions. Programmers commonly use a technique known as top-down design to break down an algorithm into functions. The process of top-down design is performed in the following manner:

• The overall task that the program is to perform is broken down into a series of subtasks.

• Each of the subtasks is examined to determine whether it can be further broken down into more subtasks. This step is repeated until no more subtasks can be identified.

• Once all of the subtasks have been identified, they are written in code.

3.3 Designing a Program to Use Functions

91

This process is called top-down design because the programmer begins by looking at the topmost level of tasks that must be performed, and then breaks down those tasks into lower levels of subtasks.

Hierarchy Charts

Flowcharts are good tools for graphically depicting the flow of logic inside a function, but they do not give a visual representation of the relationships between functions. Programmers commonly use hierarchy charts for this purpose. A hierarchy chart, which is also known as a structure chart, shows boxes that represent each function in a program. The boxes are connected in a way that illustrates the functions called by each function. Figure 3-10 shows an example of a hierarchy chart for a hypothetical pay calculating program.

Figure 3-10

A hierarchy chart

main()

get_input()

calc_gross_pay()

calc_overtime()

calc_withholdings()

calc_net_pay()

get_hours_worked()

get_hourly_rate()

calc_taxes()

calc_benefits()

The chart shown in Figure 3-9 shows the main function as the topmost function in the hierarchy. The main function calls five other functions: get_input, calc_gross_pay, calc_overtime, calc_withholdings, and calc_net_pay. The get_input function calls two additional functions: get_hours_worked and get_hourly_rate. The calc_withholdings function also calls two functions: calc_taxes and calc_benefits.

Notice that the hierarchy chart does not show the steps that are taken inside a function.

Because they do not reveal any details about how functions work, they do not replace flowcharts or pseudocode.

In the Spotlight:

Defining and Calling Functions

Professional Appliance Service, Inc. offers maintenance and repair services for household appliances. The owner wants to give each of the company’s service technicians a small handheld computer that displays step-by-step instructions for many of the repairs that 92

Chapter 3

Simple Functions

they perform. To see how this might work, the owner has asked you to develop a program that displays the following instructions for disassembling an Acme laundry dryer: Step 1: Unplug the dryer and move it away from the wall.

Step 2: Remove the six screws from the back of the dryer.

Step 3: Remove the dryer’s back panel.

Step 4: Pull the top of the dryer straight up.

During your interview with the owner, you determine that the program should display the steps one at a time. You decide that after each step is displayed, the user will be asked to press the Enter key to see the next step. Here is the algorithm in pseudocode: Display a starting message, explaining what the program does.

Ask the user to press Enter to see step 1.

Display the instructions for step 1.

Ask the user to press Enter to see the next step.

Display the instructions for step 2.

Ask the user to press Enter to see the next step.

Display the instructions for step 3.

Ask the user to press Enter to see the next step.

Display the instructions for step 4.

This algorithm lists the top level of tasks that the program needs to perform, and becomes the basis of the program’s main function. Figure 3-11 shows the program’s structure in a hierarchy chart.

Figure 3-11

Hierarchy chart for the program

main()

startup_message()

step1()

step2()

step3()

step4()

As you can see from the hierarchy chart, the main function will call several other functions.

Here are summaries of those functions:

• startup_message—This function will display the starting message that tells the technician what the program does.

• step1—This function will display the instructions for step 1.

• step2—This function will display the instructions for step 2.

• step3—This function will display the instructions for step 3.

• step4—This function will display the instructions for step 4.

Between calls to these functions, the main function will instruct the user to press a key to see the next step in the instructions. Program 3-3 shows the code for the program.

3.3 Designing a Program to Use Functions

93

Program 3-3

(acme_dryer.py)

1

# This program displays step-by-step instructions

2

# for disassembling an Acme dryer.

3 # The main function performs the program's main logic.

4 def main():

5 # Display the start-up message.

6 startup_message()

7 input('Press Enter to see Step 1.')

8 # Display step 1.

9 step1()

10 input('Press Enter to see Step 2.')

11 # Display step 2.

12 step2()

13 input('Press Enter to see Step 3.')

14 # Display step 3.

15 step3()

16 input('Press Enter to see Step 4.')

17 # Display step 4.

18 step4()

19

20 # The startup_message function displays the

21 # program's initial message on the screen.

22 def startup_message():

23 print('This program tells you how to')

24 print('disassemble an ACME laundry dryer.')

25 print('There are 4 steps in the process.')

26 print()

27

28 # The step1 function displays the instructions

29 # for step 1.

30 def step1():

31 print('Step 1: Unplug the dryer and')

32 print('move it away from the wall.')

33 print()

34

35 # The step2 function displays the instructions

36 # for step 2.

37 def step2():

38 print('Step 2: Remove the six screws')

39 print('from the back of the dryer.')

40 print()

41

42 # The step3 function displays the instructions

43 # for step 3.

44 def step3():

45 print('Step 3: Remove the back panel')

(program continues)

94

Chapter 3

Simple Functions

Program 3-3

(continued)

46 print('from the dryer.')

47 print()

48

49 # The step4 function displays the instructions

50 # for step 4.

51 def step4():

52 print('Step 4: Pull the top of the')

53 print('dryer straight up.')

54

55 # Call the main function to begin the program.

56 main()

Program Output

This program tells you how to

disassemble an ACME laundry dryer.

There are 4 steps in the process.

Press Enter to see Step 1. e

Step 1: Unplug the dryer and

move it away from the wall.

Press Enter to see Step 2. e

Step 2: Remove the six screws

from the back of the dryer.

Press Enter to see Step 3. e

Step 3: Remove the back panel

from the dryer.

Press Enter to see Step 4. e

Step 4: Pull the top of the

dryer straight up.

Pausing Execution Until the User Presses Enter

Sometimes you want a program to pause so the user can read information that has been displayed on the screen. When the user is ready for the program to continue execution, he or she presses the Enter key and the program resumes. In Python you can use the input function to cause a program to pause until the user presses the Enter key. Line 7 in Program 3-3 is an example:

input('Press Enter to see Step 1.')

This statement displays the prompt 'Press Enter to see Step 1.' and pauses until the user presses the Enter key. The program also uses this technique in lines 10, 13, and 16.

3.4 Local Variables

95

3.4

Local Variables

CONCEPT: A local variable is created inside a function and cannot be accessed by statements that are outside the function. Different functions can have local variables with the same names because the functions cannot see each other’s local variables.

Anytime you assign a value to a variable inside a function, you create a local variable. A local variable belongs to the function in which it is created, and only statements inside that function can access the variable. (The term local is meant to indicate that the variable can be used only locally, within the function in which it is created.) An error will occur if a statement in one function tries to access a local variable that belongs to another function. For example, look at Program 3-4.

Program 3-4

(bad_local.py)

1

# Definition of the main function.

2

def main():

3

get_name()

4

print('Hello', name) # This causes an error!

5

6

# Definition of the get_name function.

7

def get_name():

8

name = input('Enter your name: ')

9

10

# Call the main function.

11

main()

This program has two functions: main and get_name. In line 8 the name variable is assigned a value that is entered by the user. This statement is inside the get_name function, so the name variable is local to that function. This means that the name variable cannot be accessed by statements outside the get_name function.

The main function calls the get_name function in line 3. Then, the statement in line 4

tries to access the name variable. This results in an error because the name variable is local to the get_name function, and statements in the main function cannot access it.

Scope and Local Variables

A variable’s scope is the part of a program in which the variable may be accessed. A variable is visible only to statements in the variable’s scope. A local variable’s scope is the function in which the variable is created. As you saw demonstrated in Program 3-4, no statement outside the function may access the variable.

96

Chapter 3

Simple Functions

In addition, a local variable cannot be accessed by code that appears inside the function at a point before the variable has been created. For example, look at the following function.

It will cause an error because the print function tries to access the vall variable, but this statement appears before the vall variable has been created. Moving the assignment statement to a line before the print statement will fix this error.

def bad_function():

print('The value is', val) # This will cause an error!

vall = 99

Because a function’s local variables are hidden from other functions, the other functions may have their own local variables with the same name. For example, look at Program 3-5. In addition to the main function, this program has two other functions: texas and california. These two functions each have a local variable named birds.

Program 3-5

(birds.py)

1

# This program demonstrates two functions that

2

# have local variables with the same name.

3

4

def main():

5

# Call the texas function.

6

texas()

7

# Call the california function.

8

california()

9

10

# Definition of the texas function. It creates

11

# a local variable named birds.

12

def texas():

13

birds = 5000

14

print('texas has', birds, 'birds.')

15

16

# Definition of the california function. It also

17

# creates a local variable named birds.

18

def california():

19

birds = 8000

20

print('california has', birds, 'birds.')

21

22

# Call the main function.

23

main()

Program Output

texas has 5000 birds.

california has 8000 birds.

3.5 Passing Arguments to Functions

97

Although there are two separate variables named birds in this program, only one of them is visible at a time because they are in different functions. This is illustrated in Figure 3-12. When the texas function is executing, the birds variable that is created in line 13 is visible. When the california function is executing, the birds variable that is created in line 19 is visible.

Figure 3-12

Each function has its own birds variable

def texas():

birds = 5000

print('texas has', birds, 'birds.')

birds

5000

def california():

birds = 8000

print('california has', birds, 'birds.')

birds

8000

Checkpoint

3.10

What is a local variable? How is access to a local variable restricted?

3.11

What is a variable’s scope?

3.12

Is it permissible for a local variable in one function to have the same name as a local variable in a different function?

3.5

Passing Arguments to Functions

CONCEPT: An argument is any piece of data that is passed into a function when the function is called. A parameter is a variable that receives an argument that is passed into a function.

Sometimes it is useful not only to call a function, but also to send one or more pieces of VideoNote

data into the function. Pieces of data that are sent into a function are known as arguments.

Passing Arguments

to a Function

The function can use its arguments in calculations or other operations.

98

Chapter 3

Simple Functions

If you want a function to receive arguments when it is called, you must equip the function with one or more parameter variables. A parameter variable, often simply called a parameter, is a special variable that is assigned the value of an argument when a function is called. Here is an example of a function that has a parameter variable: def show_double(number):

result = number * 2

print(result)

This function’s name is show_double. Its purpose is to accept a number as an argument and display the value of that number doubled. Look at the function header and notice the word number that appear inside the parentheses. This is the name of a parameter variable.

This variable will be assigned the value of an argument when the function is called.

Program 3-6 demonstrates the function in a complete program.

Program 3-6

(pass_arg.py)

1

# This program demonstrates an argument being

2

# passed to a function.

3

4

def main():

5

value = 5

6

show_double(value)

7

8

# The show_double function accepts an argument

9

# and displays double its value.

10

def show_double(number):

11

result = number * 2

12

print(result)

13

14

# Call the main function.

15

main()

Program Output

10

When this program runs, the main function is called in line 15. Inside the main function, line 5 creates a local variable named value, assigned the value 5. Then the following statement in line 6 calls the show_double function:

show_double(value)

Notice that value appears inside the parentheses. This means that value is being passed as an argument to the show_double function, as shown in Figure 3-13 When this statement executes, the show_double function will be called and the number parameter will be assigned the same value as the value variable. This is shown in Figure 3-14.

3.5 Passing Arguments to Functions

99

Figure 3-13

The value variable is passed as an argument

def main():

value = 5

show_double(value)

def show_double(number):

result = number * 2

print(result)

Figure 3-14

The value variable and the number parameter reference the same value def main():

value = 5

value

show_double(value)

5

def show_double(number):

result = number * 2

number

print(result)

Let’s step through the show_double function. As we do, remember that the number parameter variable will be assigned the value that was passed to it as an argument. In this program, that number is 5.

Line 11 assigns the value of the expression number * 2 to a local variable named result.

Because number references the value 5, this statement assigns 10 to result. Line 12 displays the result variable.

The following statement shows how the show_double function can be called with a numeric literal passed as an argument:

show_double(50)

This statement executes the show_double function, assigning 50 to the number parameter.

The function will print 100.

Parameter Variable Scope

Earlier in this chapter, you learned that a variable’s scope is the part of the program in which the variable may be accessed. A variable is visible only to statements inside the variable’s scope. A parameter variable’s scope is the function in which the parameter is used. All of the statements inside the function can access the parameter variable, but no statement outside the function can access it.

100

Chapter 3

Simple Functions

In the Spotlight:

Passing an Argument to a Function

Your friend Michael runs a catering company. Some of the ingredients that his recipes require are measured in cups. When he goes to the grocery store to buy those ingredients, however, they are sold only by the fluid ounce. He has asked you to write a simple program that converts cups to fluid ounces.

You design the following algorithm:

1. Display an introductory screen that explains what the program does.

2. Get the number of cups.

3. Convert the number of cups to fluid ounces and display the result.

This algorithm lists the top level of tasks that the program needs to perform, and becomes the basis of the program’s main function. Figure 3-15 shows the program’s structure in a hierarchy chart.

Figure 3-15

Hierarchy chart for the program

main( )

cups_to_ounces

intro( )

(cups)

As shown in the hierarchy chart, the main function will call two other functions.

Here are summaries of those functions:

• intro—This function will display a message on the screen that explains what the program does.

• cups_to_ounces—This function will accept the number of cups as an argument and calculate and display the equivalent number of fluid ounces.

In addition to calling these functions, the main function will ask the user to enter the number of cups. This value will be passed to the cups_to_ounces function. The code for the program is shown in Program 3-7.

Program 3-7

(cups_to_ounces.py)

1

# This program converts cups to fluid ounces.

2

3

def main():

4

# display the intro screen.

3.5 Passing Arguments to Functions

101

5

intro()

6

# Get the number of cups.

7

cups_needed = int(input('Enter the number of cups: ')) 8

# Convert the cups to ounces.

9

cups_to_ounces(cups_needed)

10

11

# The intro function displays an introductory screen.

12

def intro():

13

print('This program converts measurements')

14

print('in cups to fluid ounces. For your')

15

print('reference the formula is:')

16

print(' 1 cup = 8 fluid ounces')

17

print()

18

19

# The cups_to_ounces function accepts a number of

20

# cups and displays the equivalent number of ounces.

21

def cups_to_ounces(cups):

22

ounces = cups * 8

23

print('That converts to', ounces, 'ounces.')

24

25

# Call the main function.

26

main()

Program Output (with input shown in bold)

This program converts measurements

in cups to fluid ounces. For your

reference the formula is:

1 cup = 8 fluid ounces

Enter the number of cups: 4 e

That converts to 32 ounces.

Passing Multiple Arguments

Often it’s useful to write functions that can accept multiple arguments. Program 3-8 shows a function named show_sum, that accepts two arguments. The function adds the two arguments and displays their sum.

Program 3-8

(multiple_args.py)

1

# This program demonstrates a function that accepts

2

# two arguments.

3

4

def main():

5

print('The sum of 12 and 45 is')

(program continues)

102

Chapter 3

Simple Functions

Program 3-8

(continued)

6

show_sum(12, 45)

7

8

# The show_sum function accepts two arguments

9

# and displays their sum.

10

def show_sum(num1, num2):

11

result = num1 + num2

12

print(result)

13

14

# Call the main function.

15

main()

Program Output

The sum of 12 and 45 is

57

Notice that two parameter variable names, num1 and num2, appear inside the parentheses in the show_sum function header. This is often referred to as a parameter list. Also notice that a comma separates the variable names.

The statement in line 6 calls the show_sum function and passes two arguments: 12 and 45. These arguments are passed by position to the corresponding parameter variables in the function. In other words, the first argument is passed to the first parameter variable, and the second argument is passed to the second parameter variable. So, this statement causes 12 to be assigned to the num1 parameter and 45 to be assigned to the num2 parameter, as shown in Figure 3-16.

Figure 3-16

Two arguments passed to two parameters

def main():

print('The sum of 12 and 45 is')

show_sum(12, 45)

def show_sum(num1, num2):

result = num1 + num2

print(result)

num1

12

num2

45

Suppose we were to reverse the order in which the arguments are listed in the function call, as shown here:

show_sum(45, 12)

This would cause 45 to be passed to the num1 parameter and 12 to be passed to the num2

parameter. The following code shows another example. This time we are passing variables as arguments.

3.5 Passing Arguments to Functions

103

value1 = 2

value2 = 3

show_sum(value1, value2)

When the show_sum function executes as a result of this code, the num1 parameter will be assigned the value 2 and the num2 parameter will be assigned the value 3.

Program 3-9 shows one more example. This program passes two strings as arguments to a function.

Program 3-9

(string_args.py)

1

# This program demonstrates passing two string

2

# arguments to a function.

3

4

def main():

5

first_name = input('Enter your first name: ')

6

last_name = input('Enter your last name: ')

7

print('Your name reversed is')

8

reverse_name(first_name, last_name)

9

10

def reverse_name(first, last):

11

print(last, first)

12

13

# Call the main function.

14

main()

Program Output (with input shown in bold)

Enter your first name: Matt e

Enter your last name: Hoyle e

Your name reversed is

Hoyle Matt

Making Changes to Parameters

When an argument is passed to a function in Python, the function parameter variable will reference the argument’s value. However, any changes that are made to the parameter variable will not affect the argument. To demonstrate this look at Program 3-10.

Program 3-10 (change_me.py)

1

# This program demonstrates what happens when you

2

# change the value of a parameter.

3

(program continues)

104

Chapter 3

Simple Functions

Program 3-10 (continued)

4

def main():

5

value = 99

6

print('The value is', value)

7

change_me(value)

8

print('Back in main the value is', value)

9

10

def change_me(arg):

11

print('I am changing the value.')

12

arg = 0

13

print('Now the value is', arg)

14

15

# Call the main function.

16

main()

Program Output

The value is 99

I am changing the value.

Now the value is 0

Back in main the value is 99

The main function creates a local variable named value in line 5, assigned the value 99.

The print statement in line 6 displays 'The value is 99'. The value variable is then passed as an argument to the change_me function in line 7. This means that in the change_me function the arg parameter will also reference the value 99. This is shown in Figure 3-17.

Figure 3-17

The value variable is passed to the change_me function def main():

value = 99

print('The value is', value)

change_me(value)

value

print('Back in main the value is', value)

99

def change_me(arg):

print('I am changing the value.')

arg

arg = 0

print('Now the value is', arg)

Inside the change_me function, in line 12, the arg parameter is assigned the value 0.

This reassignment changes arg, but it does not affect the value variable in main.

As shown in Figure 3-18, the two variables now reference different values in memory.

The print statement in line 13 displays 'Now the value is 0' and the function ends.

3.5 Passing Arguments to Functions

105

Figure 3-18

The value variable is passed to the change_me function def main():

value = 99

print('The value is', value)

change_me(value)

value

print('Back in main the value is', value)

99

def change_me(arg):

print('I am changing the value.')

arg

0

arg = 0

print('Now the value is', arg)

Control of the program then returns to the main function. The next statement to execute is in line 8. This statement displays 'Back in main the value is 99'. This proves that even though the parameter variable arg was changed in the change_me function, the argument (the value variable in main) was not modified.

The form of argument passing that is used in Python, where a function cannot change the value of an argument that was passed to it, is commonly called pass by value. This is a way that one function can communicate with another function. The communication channel works in only one direction, however. The calling function can communicate with the called function, but the called function cannot use the argument to communicate with the calling function. In Chapter 6 you will learn how to write a function that can communicate with the part of the program that called it by returning a value.

Keyword Arguments

Programs 3-8 and 3-9 demonstrate how arguments are passed by position to parameter variables in a function. Most programming languages match function arguments and parameters this way. In addition to this conventional form of argument passing, the Python language allows you to write an argument in the following format, to specify which parameter variable the argument should be passed to:

parameter_name=value

In this format, parameter_name is the name of a parameter variable and value is the value being passed to that parameter. An argument that is written in accordance with this syntax is known as a keyword argument.

Program 3-11 demonstrates keyword arguments. This program uses a function named show_interest that displays the amount of simple interest earned by a bank account for a number of periods. The function accepts the arguments principal (for the account principal), rate (for the interest rate per period), and periods (for the number of periods). When the function is called in line 7, the arguments are passed as keyword arguments.

Program 3-11 (keyword_args.py)

1

# This program demonstrates keyword arguments.

2

3

def main():

4

# Show the amount of simple interest, using 0.01 as

5

# interest rate per period, 10 as the number of periods, (program continues)

106

Chapter 3

Simple Functions

Program 3-11 (continued)

6

# and $10,000 as the principal.

7

show_interest(rate=0.01, periods=10, principal=10000.0) 8

9

# The show_interest function displays the amount of

10

# simple interest for a given principal, interest rate 11

# per period, and number of periods.

12

13

def show_interest(principal, rate, periods):

14

interest = principal * rate * periods

15

print('The simple interest will be $', \

16

format(interest, ',.2f'), \

17

sep='')

18

19

# Call the main function.

20

main()

Program Output

The simple interest will be $1000.00.

Notice in line 7 that the order of the keyword arguments does not match the order of the parameters in the function header in line 13. Because a keyword argument specifies which parameter the argument should be passed into, its position in the function call does not matter.

Program 3-12 shows another example. This is a variation of the string_args program shown in Program 3-9. This version uses keyword arguments to call the reverse_name function.

Program 3-12 (keyword_string_args.py)

1

# This program demonstrates passing two strings as

2

# keyword arguments to a function.

3

4

def main():

5

first_name = input('Enter your first name: ')

6

last_name = input('Enter your last name: ')

7

print('Your name reversed is')

8

reverse_name(last=last_name, first=first_name)

9

10

def reverse_name(first, last):

11

print(last, first)

12

13

# Call the main function.

14

main()

Program Output (with input shown in bold)

Enter your first name: Matt e

Enter your last name: Hoyle e

Your name reversed is

Hoyle Matt

3.6 Global Variables and Global Constants

107

Mixing Keyword Arguments with Positional Arguments

It is possible to mix positional arguments and keyword arguments in a function call, but the positional arguments must appear first, followed by the keyword arguments. Otherwise an error will occur. Here is an example of how we might call the show_interest function of Program 3-10 using both positional and keyword arguments: show_interest(10000.0, rate=0.01, periods=10)

In this statement, the first argument, 10000.0, is passed by its position to the principal parameter. The second and third arguments are passed as keyword arguments. The following function call will cause an error, however, because a non-keyword argument follows a keyword argument:

# This will cause an ERROR!

show_interest(1000.0, rate=0.01, 10)

Checkpoint

3.13

What are the pieces of data that are passed into a function called?

3.14

What are the variables that receive pieces of data in a function called?

3.15

What is a parameter variable’s scope?

3.16

When a parameter is changed, does this affect the argument that was passed into the parameter?

3.17

The following statements call a function named show_data. Which of the statements passes arguments by position, and which passes keyword arguments?

a) show_data(name='Kathryn', age=25)

b) show_data('Kathryn', 25)

3.6

Global Variables and Global Constants

CONCEPT: A global variable is accessible to all the functions in a program file.

You’ve learned that when a variable is created by an assignment statement inside a function, the variable is local to that function. Consequently, it can be accessed only by statements inside the function that created it. When a variable is created by an assignment statement that is written outside all the functions in a program file, the variable is global. A global variable can be accessed by any statement in the program file, including the statements in any function. For example, look at Program 3-13.

Program 3-13 (global1.py)

1

# Create a global variable.

2

my_value = 10

3

4

# The show_value function prints

5

# the value of the global variable.

(program continues)

108

Chapter 3

Simple Functions

Program 3-13 (continued)

6

def show_value():

7

print(my_value)

8

9

# Call the show_value function.

10

show_value()

Program Output

10

The assignment statement in line 2 creates a variable named my_value. Because this statement is outside any function, it is global. When the show_value function executes, the statement in line 7 prints the value referenced by my_value.

An additional step is required if you want a statement in a function to assign a value to a global variable. In the function you must declare the global variable, as shown in Program 3-14.

Program 3-14 (global2.py)

1

# Create a global variable.

2

number = 0

3

4

def main():

5

global number

6

number = int(input('Enter a number: '))

7

show_number()

8

9

def show_number():

10

print('The number you entered is', number)

11

12

# Call the main function.

13

main()

Program Output

Enter a number: 55 e

The number you entered is 55

The assignment statement in line 2 creates a global variable named number. Notice that inside the main function, line 5 uses the global key word to declare the number variable. This statement tells the interpreter that the main function intends to assign a value to the global number variable. That’s just what happens in line 6. The value entered by the user is assigned to number.

Most programmers agree that you should restrict the use of global variables, or not use them at all. The reasons are as follows:

• Global variables make debugging difficult. Any statement in a program file can change the value of a global variable. If you find that the wrong value is being 3.6 Global Variables and Global Constants

109

stored in a global variable, you have to track down every statement that accesses it to determine where the bad value is coming from. In a program with thousands of lines of code, this can be difficult.

• Functions that use global variables are usually dependent on those variables. If you want to use such a function in a different program, most likely you will have to redesign it so it does not rely on the global variable.

• Global variables make a program hard to understand. A global variable can be modified by any statement in the program. If you are to understand any part of the program that uses a global variable, you have to be aware of all the other parts of the program that access the global variable.

In most cases, you should create variables locally and pass them as arguments to the functions that need to access them.

Global Constants

Although you should try to avoid the use of global variables, it is permissible to use global constants in a program. A global constant is a global name that references a value that cannot be changed. Because a global constant’s value cannot be changed during the program’s execution, you do not have to worry about many of the potential hazards that are associated with the use of global variables.

Although the Python language does not allow you to create true global constants, you can simulate them with global variables. If you do not declare a global variable with the global key word inside a function, then you cannot change the variable’s assignment inside that function. The following In the Spotlight section demonstrates how global variables can be used in Python to simulate global constants.

In the Spotlight:

Using Global Constants

Marilyn works for Integrated Systems, Inc., a software company that has a reputation for providing excellent fringe benefits. One of their benefits is a quarterly bonus that is paid to all employees. Another benefit is a retirement plan for each employee. The company contributes 5 percent of each employee’s gross pay and bonuses to their retirement plans.

Marilyn wants to write a program that will calculate the company’s contribution to an employee’s retirement account for a year. She wants the program to show the amount of contribution for the employee’s gross pay and for the bonuses separately. Here is an algorithm for the program:

Get the employee’s annual gross pay.

Get the amount of bonuses paid to the employee.

Calculate and display the contribution for the gross pay.

Calculate and display the contribution for the bonuses.

The code for the program is shown in Program 3-15.

110

Chapter 3

Simple Functions

Program 3-15 (retirement.py)

1 # The following is used as a global constant

2 # the contribution rate.

3 CONTRIBUTION_RATE = 0.05

4

5 def main():

6 gross_pay = float(input('Enter the gross pay: ')) 7 bonus = float(input('Enter the amount of bonuses: ')) 8 show_pay_contrib(gross_pay)

9 show_bonus_contrib(bonus)

10

11 # The show_pay_contrib function accepts the gross

12 # pay as an argument and displays the retirement

13 # contribution for that amount of pay.

14 def show_pay_contrib(gross):

15 contrib = gross * CONTRIBUTION_RATE

16 print('Contribution for gross pay: $', \

17 format(contrib, ',.2f'), \

18 sep='')

19

20 # The show_bonus_contrib function accepts the

21 # bonus amount as an argument and displays the

22 # retirement contribution for that amount of pay.

23 def show_bonus_contrib(bonus):

24 contrib = bonus * CONTRIBUTION_RATE

25 print('Contribution for gross pay: $', \

26 format(contrib, ',.2f'), \

27 sep='')

28

29 # Call the main function.

30 main()

Program Output (with input shown in bold)

Enter the gross pay: 80000.00 e

Enter the amount of bonuses: 20000.00 e

Contribution for gross pay: $4000.00

Contribution for bonuses: $1000.00

First, notice the global declaration in line 3:

CONTRIBUTION_RATE = 0.05

CONTRIBUTION_RATE will be used as a global constant to represent the percentage of an employee’s pay that the company will contribute to a retirement account. It is a common practice to write a constant’s name in all uppercase letters. This serves as a reminder that the value referenced by the name is not to be changed in the program.

The CONTRIBUTION_RATE constant is used in the calculation in line 15 (in the show_

pay_contrib function) and again in line 24 (in the show_bonus_contrib function).

Review Questions

111

Marilyn decided to use this global constant to represent the 5 percent contribution rate for two reasons:

• It makes the program easier to read. When you look at the calculations in lines 15 and 24 it is apparent what is happening.

• Occasionally the contribution rate changes. When this happens, it will be easy to update the program by changing the assignment statement in line 3.

Checkpoint

3.18

What is the scope of a global variable?

3.19

Give one good reason that you should not use global variables in a program.

3.20

What is a global constant? Is it permissible to use global constants in a program?

Review Questions

Multiple Choice

1. A group of statements that exist within a program for the purpose of performing a specific task is a(n) __________.

a. block

b. parameter

c. function

d. expression

2. A design technique that helps to reduce the duplication of code within a program and is a benefit of using functions is __________.

a. code reuse

b. divide and conquer

c. debugging

d. facilitation of teamwork

3. The first line of a function definition is known as the __________.

a. body

b. introduction

c. initialization

d. header

4. You __________ the function to execute it.

a. define

b. call

c. import

d. export

5. A design technique that programmers use to break down an algorithm into functions is known as __________.

a. top-down design

b. code simplification

112

Chapter 3

Simple Functions

c. code refactoring

d. hierarchical subtasking

6. A __________ is a diagram that gives a visual representation of the relationships between functions in a program.

a. flowchart

b. function relationship chart

c. symbol chart

d. hierarchy chart

7. A __________ is a variable that is created inside a function.

a. global variable

b. local variable

c. hidden variable

d. none of the above; you cannot create a variable inside a function 8. A(n) __________ is the part of a program in which a variable may be accessed.

a. declaration space

b. area of visibility

c. scope

d. mode

9. A(n) __________ is a piece of data that is sent into a function.

a. argument

b. parameter

c. header

d. packet

10. A(n) __________ is a special variable that receives a piece of data when a function is called.

a. argument

b. parameter

c. header

d. packet

11. A variable that is visible to every function in a program file is a __________.

a. local variable

b. universal variable

c. program-wide variable

d. global variable

12. When possible, you should avoid using __________ variables in a program.

a. local

b. global

c. reference

d. parameter

True or False

1. The phrase “divide and conquer” means that all of the programmers on a team should be divided and work in isolation.

2. Functions make it easier for programmers to work in teams.

3. Function names should be as short as possible.

Review Questions

113

4. Calling a function and defining a function mean the same thing.

5. A flowchart shows the hierarchical relationships between functions in a program.

6. A hierarchy chart does not show the steps that are taken inside a function.

7. A statement in one function can access a local variable in another function.

8. In Python you cannot write functions that accept multiple arguments.

9. In Python, you can specify which parameter an argument should be passed into a function call.

10. You cannot have both keyword arguments and non-keyword arguments in a function call.

Short Answer

1. How do functions help you to reuse code in a program?

2. Name and describe the two parts of a function definition.

3. When a function is executing, what happens when the end of the function block is reached?

4. What is a local variable? What statements are able to access a local variable?

5. What is a local variable’s scope?

6. Why do global variables make a program difficult to debug?

Algorithm Workbench

1. Write a function named times_ten. The function should accept an argument and display the product of its argument multiplied times 10.

2. Examine the following function header, and then write a statement that calls the function, passing 12 as an argument.

def show_value(quantity):

3. Look at the following function header:

def my_function(a, b, c):

Now look at the following call to my_function:

my_function(3, 2, 1)

When this call executes, what value will be assigned to a? What value will be assigned to b? What value will be assigned to c?

4. What will the following program display?

def main():

x = 1

y = 3.4

print(x, y)

change_us(x, y)

print(x, y)

def change_us(a, b):

a = 0

b = 0

print(a, b)

main()

114

Chapter 3

Simple Functions

5. Look at the following function definition:

def my_function(a, b, c):

d = (a + c) / b

print(d)

a. Write a statement that calls this function and uses keyword arguments to pass 2 into a, 4 into b, and 6 into c.

b. What value will be displayed when the function call executes?

Programming Exercises

1. Kilometer Converter

Write a program that asks the user to enter a distance in kilometers, and then converts that VideoNote

The Kilometer

distance to miles. The conversion formula is as follows: Converter Problem

Miles ϭ Kilometers ϫ 0.6214

2. Sale Tax Program Refactoring

Programming Exercise #6 in Chapter 2 was the Sales Tax program. For that exercise you were asked to write a program that calculates and displays the county and state sales tax on a purchase. If you have already written that program, redesign it so the subtasks are in functions. If you have not already written that program, write it using functions.

3. How Much Insurance?

Many financial experts advise that property owners should insure their homes or buildings for at least 80 percent of the amount it would cost to replace the structure. Write a program that asks the user to enter the replacement cost of a building and then displays the minimum amount of insurance he or she should buy for the property.

4. Automobile Costs

Write a program that asks the user to enter the monthly costs for the following expenses incurred from operating his or her automobile: loan payment, insurance, gas, oil, tires, and maintenance. The program should then display the total monthly cost of these expenses, and the total annual cost of these expenses.

5. Property Tax

A county collects property taxes on the assessment value of property, which is 60 percent of the property’s actual value. For example, if an acre of land is valued at $10,000, its assessment value is $6,000. The property tax is then 64¢ for each $100 of the assessment value. The tax for the acre assessed at $6,000 will be $38.40. Write a program that asks for the actual value of a piece of property and displays the assessment value and property tax.

Programming Exercises

115

6. Body Mass Index

Write a program that calculates and displays a person’s body mass index (BMI). The BMI is often used to determine whether a person is overweight or underweight for his or her height. A person’s BMI is calculated with the following formula: BMI ϭ weight ϫ 703 / height2

where weight is measured in pounds and height is measured in inches.

7. Calories from Fat and Carbohydrates

A nutritionist who works for a fitness club helps members by evaluating their diets. As part of her evaluation, she asks members for the number of fat grams and carbohydrate grams that they consumed in a day. Then, she calculates the number of calories that result from the fat, using the following formula:

calories from fat ϭ fat grams ϫ 9

Next, she calculates the number of calories that result from the carbohydrates, using the following formula:

calories from carbs ϭ carb grams ϫ 4

The nutritionist asks you to write a program that will make these calculations.

8. Stadium Seating

There are three seating categories at a stadium. For a softball game, Class A seats cost $15, Class B seats cost $12, and Class C seats cost $9. Write a program that asks how many tickets for each class of seats were sold, and then displays the amount of income generated from ticket sales.

9. Paint Job Estimator

A painting company has determined that for every 115 square feet of wall space, one gallon of paint and eight hours of labor will be required. The company charges $20.00 per hour for labor. Write a program that asks the user to enter the square feet of wall space to be painted and the price of the paint per gallon. The program should display the following data:

• The number of gallons of paint required

• The hours of labor required

• The cost of the paint

• The labor charges

• The total cost of the paint job

10. Monthly Sales Tax

A retail company must file a monthly sales tax report listing the total sales for the month, and the amount of state and county sales tax collected. The state sales tax rate is 4 percent and the county sales tax rate is 2 percent. Write a program that asks the user to enter the total sales for the month. From this figure, the application should calculate and display the following:

• The amount of county sales tax

• The amount of state sales tax

• The total sales tax (county plus state)

This page intentionally left blank

Decision Structures

CHAPTER

4 and Boolean Logic

TOPICS

4.1

The if Statement

4.5

Logical Operators

4.2

The if-else Statement

4.6

Boolean Variables

4.3

Comparing Strings

4.4

Nested Decision Structures and

the if-elif-else Statement

4.1

The if Statement

CONCEPT: The if statement is used to create a decision structure, which allows a program to have more than one path of execution. The if statement causes one or more statements to execute only when a Boolean expression is true.

A control structure is a logical design that controls the order in which a set of statements execute. So far in this book we have used only the simplest type of control structure: the sequence structure. A sequence structure is a set of statements that execute in the order that they appear. For example, the following code is a sequence structure because the statements VideoNote

The if Statement

execute from top to bottom.

name = input('What is your name? ')

age = int(input('What is your age? '))

print('Here is the data you entered:')

print('Name:', name)

print('Age:', age)

Even in Chapter 3, where you learned about functions, each function contained a block of statements that are executed in the order that they appear. For example, the following function is a sequence structure because the statements in its block execute in the order that they appear, from the beginning of the function to the end.

def show_double(value):

result = value * 2

print(result)

117

118

Chapter 4

Decision Structures and Boolean Logic

Although the sequence structure is heavily used in programming, it cannot handle every type of task. This is because some problems simply cannot be solved by performing a set of ordered steps, one after the other. For example, consider a pay calculating program that determines whether an employee has worked overtime. If the employee has worked more than 40 hours, he or she gets paid extra for all the hours over 40. Otherwise, the overtime calculation should be skipped. Programs like this require a different type of control structure: one that can execute a set of statements only under certain circumstances. This can be accomplished with a decision structure. (Decision structures are also known as selection structures.)

In a decision structure’s simplest form, a specific action is performed only if a certain condition exists. If the condition does not exist, the action is not performed. The flowchart shown in Figure 4-1 shows how the logic of an everyday decision can be diagrammed as a decision structure. The diamond symbol represents a true/false condition. If the condition is true, we follow one path, which leads to an action being performed. If the condition is false, we follow another path, which skips the action.

Figure 4-1

A simple decision structure

Cold

True

outside

Wear a coat.

False

In the flowchart, the diamond symbol indicates some condition that must be tested. In this case, we are determining whether the condition Cold outside is true or false. If this condition is true, the action Wear a coat is performed. If the condition is false, the action is skipped. The action is conditionally executed because it is performed only when a certain condition is true.

Programmers call the type of decision structure shown in Figure 4-1 a single alternative decision structure. This is because it provides only one alternative path of execution. If the condition in the diamond symbol is true, we take the alternative path. Otherwise, we exit the structure. Figure 4-2 shows a more elaborate example, where three actions are taken only when it is cold outside. It is still a single alternative decision structure, because there is one alternative path of execution.

4.1 The if Statement

119

Figure 4-2

A decision structure that performs three actions if it is cold outside Cold

True

outside

Wear a coat.

False

Wear a hat.

Wear gloves.

In Python we use the if statement to write a single alternative decision structure. Here is the general format of the if statement:

if condition:

statement

statement

etc.

For simplicity, we will refer to the first line as the if clause. The if clause begins with the word if, followed by a condition, which is an expression that will be evaluated as either true or false. A colon appears after the condition. Beginning at the next line is a block of statements. (Recall from Chapter 3 that all of the statements in a block must be consistently indented. This indentation is required because the Python interpreter uses it to tell where the block begins and ends.)

When the if statement executes, the condition is tested. If the condition is true, the statements that appear in the block following the if clause are executed. If the condition is false, the statements in the block are skipped.

Boolean Expressions and Relational Operators

As previously mentioned, the if statement tests an expression to determine whether it is true or false. The expressions that are tested by the if statement are called Boolean 120

Chapter 4

Decision Structures and Boolean Logic

expressions, named in honor of the English mathematician George Boole. In the 1800s Boole invented a system of mathematics in which the abstract concepts of true and false can be used in computations.

Typically, the Boolean expression that is tested by an if statement is formed with a relational operator. A relational operator determines whether a specific relationship exists between two values. For example, the greater than operator (Ͼ) determines whether one value is greater than another. The equal to operator (==) determines whether two values are equal. Table 4-1 lists the relational operators that are available in Python.

Table 4-1

Relational operators

Operator

Meaning

Ͼ

Greater than

Ͻ

Less than

Ͼ=

Greater than or equal to

Ͻ=

Less than or equal to

==

Equal to

!=

Not equal to

The following is an example of an expression that uses the greater than (Ͼ) operator to compare two variables, length and

length Ͼ width

This expression determines whether the value referenced by length is greater than the value referenced by width. If length is greater than width, the value of the expression is true. Otherwise, the value of the expression is false. The following expression uses the less than operator to determine whether length is less than Ͻ width

Table 4-2 shows examples of several Boolean expressions that compare the variables x and y.

Table 4-2

Boolean expressions using relational operators

Expression

Meaning

x Ͼ y

Is x greater than y?

x Ͻ y

Is x less than y?

x Ͼ= y

Is x greater than or equal to y?

x Ͻ= y

Is x less than or equal to y?

x == y

Is x equal to y?

x != y

Is x not equal to y?

4.1 The if Statement

121

The >= and <= Operators

Two of the operators, Ͼ= and Ͻ=, test for more than one relationship. The Ͼ= operator determines whether the operand on its left is greater than or equal to the operand on its right. The Ͻ= operator determines whether the operand on its left is less than or equal to the operand on its right.

For example, assume the following:

• a is assigned 4

• b is assigned 6

• c is assigned 4

These expressions are true:

b Ͼ= a

a Ͼ= c

a Ͻ= c

b Ͻ= 10

And these expressions are false:

a Ͼ= 5

b Ͻ= a

The == Operator

The == operator determines whether the operand on its left is equal to the operand on its right. If the values referenced by both operands are the same, the expression is true.

Assuming that a is 4, the expression a == 4 is true and the expression a == 2 is false.

N O T E : The equality operator is two = symbols together. Don’t confuse this operator with the assignment operator, which is one = symbol.

The != Operator

The != operator is the not-equal-to operator. It determines whether the operand on its left is not equal to the operand on its right, which is the opposite of the == operator. As before, assuming a is 4, b is 6, and c is 4, both a != b and b != c are true because a is not equal to b and b is not equal to c. However, a != c is false because a is equal to c.

Putting It All Together

Let’s look at the following example of the if statement: if sales Ͼ 50000:

bonus = 500.0

This statement uses the Ͼ operator to determine whether sales is greater than 50,000. If the expression sales Ͼ 50000 is true, the variable bonus is assigned 500.0. If the expression is false, however, the assignment statement is skipped. Figure 4-3 shows a flowchart for this section of code.

122

Chapter 4

Decision Structures and Boolean Logic

Figure 4-3

Example decision structure

True

sales > 50000

bonus = 500.0

False

The following example conditionally executes a block containing three statements. Figure 4-4 shows a flowchart for this section of code.

if sales Ͼ 50000:

bonus = 500.0

commission_rate = 0.12

print('You met your sales quota!')

Figure 4-4

Example decision structure

True

sales > 50000

bonus = 500.0

False

commission_rate

= 0.12

print ('You met

your sales quota!')

4.1 The if Statement

123

The following code uses the == operator to determine whether two values are equal. The expression balance == 0 will be true if the balance variable is assigned 0. Otherwise the expression will be false.

if balance == 0:

# Statements appearing here will

# be executed only if balance is

# equal to 0.

The following code uses the != operator to determine whether two values are not equal.

The expression choice != 5 will be true if the choice variable does not reference the value 5. Otherwise the expression will be false.

if choice != 5:

# Statements appearing here will

# be executed only if choice is

# not equal to 5.

In the Spotlight:

Using the if Statement

Kathryn teaches a science class and her students are required to take three tests. She wants to write a program that her students can use to calculate their average test score. She also wants the program to congratulate the student enthusiastically if the average is greater than 95. Here is the algorithm in pseudocode:

Get the first test score

Get the second test score

Get the third test score

Calculate the average

Display the average

If the average is greater than 95:

Congratulate the user

Program 4-1 shows the code for the program.

Program 4-1

(test_average.py)

1 # This program gets three test scores and displays

2 # their average. It congratulates the user if the

3 # average is a high score.

4

5 # Global constant for a high score

6 HIGH_SCORE = 95

7

8 def main():

9 # Get the three test scores.

(program continues)

124

Chapter 4

Decision Structures and Boolean Logic

Program 4-1

(continued)

10 test1 = int(input('Enter the score for test 1: ')) 11 test2 = int(input('Enter the score for test 2: ')) 12 test3 = int(input('Enter the score for test 3: ')) 13

14 # Calculate the average test score.

15 average = (test1 + test2 + test3) / 3

16

17 # Print the average.

18 print('The average score is', average)

19

20 # If the average is a high score,

21 # congratulate the user.

22 if average >= HIGH_SCORE:

23 print('Congratulations!')

24 print('That is a great average!')

25

26 # Call the main function

27 main()

Program Output (with input shown in bold)

Enter the score for test 1: 82 e

Enter the score for test 2: 76 e

Enter the score for test 3: 91 e

The average score is 83.0

Program Output (with input shown in bold)

Enter the score for test 1: 93 e

Enter the score for test 2: 99 e

Enter the score for test 3: 96 e

The average score is 96.0

Congratulations!

That is a great score.

Nested Blocks

Program 4-1 is an example of a program that has a block inside a block. The main function has a block (in lines 9 through 24), and inside that block the if statement has a block (in lines 23 through 24). This is shown in Figure 4-5.

As you learned in Chapter 3, Python requires you to indent the statements in a block. When you have a block nested inside a block, the inner block must be further indented. As you can see in Figure 4-5, four spaces are used to indent the main function’s block, and eight spaces are used to indent the if statement’s block.

4.2 The if-else Statement

125

Figure 4-5

Nested blocks

def main():

This is the main

# Get the three test scores.

function's block.

test1 = int(input('Enter the score for test 1: '))

test2 = int(input('Enter the score for test 2: '))

test3 = int(input('Enter the score for test 3: '))

# Calculate the average test score.

average = (test1 + test2 + test3) / 3

# Print the average.

print('The average score is', average)

# If the average is a high score,

# congratulate the user.

if average >= HIGH_SCORE:

print('Congratulations!')

This is the if

print('That is a great average!')

statement's block.

# Call the main function.

main()

Checkpoint

4.1

What is a control structure?

4.2

What is a decision structure?

4.3

What is a single alternative decision structure?

4.4

What is a Boolean expression?

4.5

What types of relationships between values can you test with relational operators?

4.6

Write an if statement that assigns 0 to x if y is equal to 20.

4.7

Write an if statement that assigns 0.2 to commissionRate if sales is greater than or equal to 10000.

4.2

The if-else Statement

CONCEPT: An if-else statement will execute one block of statements if its condition is true, or another block if its condition is false.

The previous section introduced the single alternative decision structure (the if statement), which has one alternative path of execution. Now we will look at the dual alternative deci-VideoNote

The if-else Statement

sion structure, which has two possible paths of execution—one path is taken if a condition is true, and the other path is taken if the condition is false. Figure 4-6 shows a flowchart for a dual alternative decision structure.

The decision structure in the flowchart tests the condition temperature Ͻ 40. If this condition is true, the statement print(”A little cold, isn't it?”) is performed. If the condition is false, the statement print(”Nice weather we're having.”) is performed.

126

Chapter 4

Decision Structures and Boolean Logic

Figure 4-6

A dual alternative decision structure

False

temperature

True

< 40

print("Nice weather

print("A little cold,

we're having.")

isn't it?")

In code we write a dual alternative decision structure as an if-else statement. Here is the general format of the if-else statement:

if condition:

statement

statement

etc.

else:

statement

statement

etc.

When this statement executes, the condition is tested. If it is true, the block of indented statements following the if clause is executed, and then control of the program jumps to the statement that follows the if-else statement. If the condition is false, the block of indented statements following the else clause is executed, and then control of the program jumps to the statement that follows the if-else statement. This action is described in Figure 4-7.

Figure 4-7

Conditional execution in an if-else statement

if condition:

if condition:

If the condition is true, this

statement

statement

block of statements is

statement

statement

executed.

etc.

etc.

else:

else:

statement

If the condition is false, this

statement

statement

block of statements is

statement

Then, control jumps here,

etc.

executed.

etc.

to the statement following

the if-else statement.

Then, control jumps here,

to the statement following

the if-else statement.

4.2 The if-else Statement

127

The following code shows an example of an if-else statement. This code matches the flowchart that was shown in Figure 4-5.

if temperature Ͻ 40:

print("A little cold, isn't it?")

else:

print("Nice weather we're having.")

Indentation in the if-else Statement

When you write an if-else statement, follow these guidelines for indentation:

• Make sure the if clause and the else clause are aligned.

• The if clause and the else clause are each followed by a block of statements. Make sure the statements in the blocks are consistently indented.

This is shown in Figure 4-8.

Figure 4-8

Indentation with an if-else statement

if temperature < 40:

Align the if and

print("A little cold, isn't it?")

else clauses.

print("Turn up the heat!")

The statements in each

else:

block must be indented

print("Nice weather we're having.")

consistently.

print("Pass the sunscreen.")

In the Spotlight:

Using the if-else Statement

Chris owns an auto repair business and has several employees. If any employee works over 40 hours in a week, he pays them 1.5 times their regular hourly pay rate for all hours over 40. He has asked you to design a simple payroll program that calculates an employee’s gross pay, including any overtime wages. You design the following algorithm: Get the number of hours worked.

Get the hourly pay rate.

If the employee worked more than 40 hours:

Calculate and display the gross pay with overtime.

Else:

Calculate and display the gross pay as usual.

Next, you go through the top-down design process (described in Chapter 3) and create the hierarchy chart shown in Figure 4-9. As shown in the hierarchy chart, there are three functions, summarized as follows:

• main—This function will be called when the program starts. It will get the number of hours worked and the hourly pay rate as input from the user. It will then call either the calc_pay_with_OT function or the calc_regular_pay function to calculate and display the gross pay.

128

Chapter 4

Decision Structures and Boolean Logic

• calc_pay_with_OT—This function will calculate and display an employee’s pay with overtime.

• calc_regular_pay—This function will calculate and display the gross pay for an employee with no overtime.

Figure 4-9

Hierarchy chart

main( )

calc_pay_with_OT

calc_regular_pay

(hours, rate, gross)

(hours, rate, gross)

The code for the program is shown in Program 4-2. Notice that two global variables, which are used as constants, are created in lines 2 and 3. BASE_HOURS is assigned 40, which is the number of hours an employee can work in a week without getting paid overtime. OT_MULTIPLIER is assigned 1.5, which is the pay rate multiplier for overtime hours. This means that the employee’s hourly pay rate is multiplied by 1.5 for all overtime hours.

Program 4-2

(auto_repair_payroll.py)

1

# Global constants

2

BASE_HOURS = 40 # Base hours per week

3

OT_MULTIPLIER = 1.5 # Overtime multiplier

4

5

# The main function gets the number of hours worked and 6

# the hourly pay rate. It calls either the calc_pay_with_OT

7

# function or the calc_regular_pay function to calculate 8

# and display the gross pay.

9

def main():

10

# Get the hours worked and the hourly pay rate.

11

hours_worked = float(input('Enter the number of hours worked: ')) 12

pay_rate = float(input('Enter the hourly pay rate: ')) 13

14

# Calculate and display the gross pay.

15

if hours_worked Ͼ BASE_HOURS:

16

calc_pay_with_OT(hours_worked, pay_rate)

17

else:

18

calc_regular_pay(hours_worked, pay_rate)

19

20

# The calc_pay_with_OT function calculates pay with

21

# overtime. It accepts the hours worked and the hourly 4.2 The if-else Statement

129

22

# pay rate as arguments. The gross pay is displayed.

23

def calc_pay_with_OT(hours, rate):

24

# Calculate the number of overtime hours worked.

25

overtime_hours = hours - BASE_HOURS

26

27

# Calculate the amount of overtime pay.

28

overtime_pay = overtime_hours * rate * OT_MULTIPLIER

29

30

# Calculate the gross pay.

31

gross_pay = BASE_HOURS * rate + overtime_pay

32

33

# Display the gross pay.

34

print('The gross pay is $', format(gross_pay, ',.2f'), sep='') 35

36

# The calc_regular_pay function calculates pay with

37

# no overtime. It accepts the hours worked and the hourly 38

# pay rate as arguments. The gross pay is displayed.

39

def calc_regular_pay(hours, rate):

40

# Calculate the gross pay.

41

gross_pay = hours * rate

42

43

# Display the gross pay.

44

print('The gross pay is $', format(gross_pay, ',.2f'), sep='') 45

46

# Call the main function.

47

main()

Program Output (with input shown in bold)

Enter the number of hours worked: 40 e

Enter the hourly pay rate: 20 e

The gross pay is $800.00.

Program Output (with input shown in bold)

Enter the number of hours worked: 50 e

Enter the hourly pay rate: 20 e

The gross pay is $1,100.00.

Checkpoint

4.8

How does a dual alternative decision structure work?

4.9

What statement do you use in Python to write a dual alternative decision structure?

4.10

When you write an if-else statement, under what circumstances do the statements that appear after the else clause execute?

130

Chapter 4

Decision Structures and Boolean Logic

4.3

Comparing Strings

CONCEPT: Python allows you to compare strings. This allows you to create decision structures that test the value of a string.

You saw in the preceding examples how numbers can be compared in a decision structure.

You can also compare strings. For example, look at the following code: name1 = 'Mary'

name2 = 'Mark'

if name1 == name2:

print('The names are the same.')

else:

print('The names are NOT the same.')

The == operator compares name1 and name2 to determine whether they are equal. Because the strings 'Mary' and 'Mark' are not equal, the else clause will display the message 'The names are NOT the same.'

Let’s look at another example. Assume the month variable references a string. The following code uses the != operator to determine whether the value referenced by month is not equal to 'October'.

if month != 'October':

print('This is the wrong time for Octoberfest!')

Program 4-3 is a complete program demonstrating how two strings can be compared. The program prompts the user to enter a password and then determines whether the string entered is equal to 'prospero'.

Program 4-3

(password.py)

1

# This program compares two strings.

2

# Get a password from the user.

3

password = input('Enter the password: ')

4

5

# Determine whether the correct password

6

# was entered.

7

if password == 'prospero':

8

print('Password accepted.')

9

else:

10

print('Sorry, that is the wrong password.')

Program Output (with input shown in bold)

Enter the password: ferdinand e

Sorry, that is the wrong password.

Program Output (with input shown in bold)

Enter the password: prospero e

Password accepted.

4.3 Comparing Strings

131

String comparisons are case sensitive. For example, the strings 'saturday' and

'Saturday' are not equal because the "s" is lowercase in the first string, but uppercase in the second string. The following sample session with Program 4-3 shows what happens when the user enters Prospero as the password (with an uppercase P).

Program Output (with input shown in bold)

Enter the password: Prospero e

Sorry, that is the wrong password.

T I P : In Chapter 6 you will learn how to manipulate strings so that case-insensitive comparisons can be performed.

Other String Comparisons

In addition to determining whether strings are equal or not equal, you can also determine whether one string is greater than or less than another string. This is a useful capability because programmers commonly need to design programs that sort strings in some order.

Recall from Chapter 1 that computers do not actually store characters, such as A, B, C, and so on, in memory. Instead, they store numeric codes that represent the characters. Chapter 1

mentioned that ASCII (the American Standard Code for Information Interchange) is a commonly used character coding system. You can see the set of ASCII codes in Appendix C, but here are some facts about it:

• The uppercase characters A through Z are represented by the numbers 65 through 90.

• The lowercase characters a through z are represented by the numbers 97 through 122.

• When the digits 0 through 9 are stored in memory as characters, they are represented by the numbers 48 through 57. (For example, the string 'abc123' would be stored in memory as the codes 97, 98, 99, 49, 50, and 51.)

• A blank space is represented by the number 32.

In addition to establishing a set of numeric codes to represent characters in memory, ASCII also establishes an order for characters. The character “A” comes before the character “B”, which comes before the character “C”, and so on.

When a program compares characters, it actually compares the codes for the characters.

For example, look at the following if statement:

if 'a' Ͻ 'b':

print('The letter a is less than the letter b.')

132

Chapter 4

Decision Structures and Boolean Logic

This code determines whether the ASCII code for the character 'a' is less than the ASCII code for the character 'b'. The expression 'a' Ͻ 'b' is true because the code for 'a' is less than the code for 'b'. So, if this were part of an actual program it would display the message 'The letter a is less than the letter b.'

Let’s look at how strings containing more than one character are typically compared.

Suppose a program uses the strings 'Mary' and 'Mark' as follows: name1 = 'Mary'

name2 = 'Mark'

Figure 4-10 shows how the individual characters in the strings 'Mary' and 'Mark' would actually be stored in memory, using ASCII codes.

Figure 4-10

Character codes for the strings 'Mary' and 'Mark'

M a

r

y

M a

r

k

77 97 114 121

77 97 114 107

When you use relational operators to compare these strings, the strings are compared character-by-character. For example, look at the following code: name1 = 'Mary'

name2 = 'Mark'

if name1 Ͼ name2:

print('Mary is greater than Mark')

else:

print('Mary is not greater than Mark')

The Ͼ operator compares each character in the strings 'Mary' and 'Mark', beginning with the first, or leftmost, characters. This is shown in Figure 4-11.

Figure 4-11

Comparing each character in a string

M a

r

y

77 97 114 121

77 97 114 107

M a

r

k

Here is how the comparison takes place:

1. The 'M' in 'Mary' is compared with the 'M' in 'Mark'. Since these are the same, the next characters are compared.

2. The 'a' in 'Mary' is compared with the 'a' in 'Mark'. Since these are the same, the next characters are compared.

3. The 'r' in 'Mary' is compared with the 'r' in 'Mark'. Since these are the same, the next characters are compared.

4. The 'y' in 'Mary' is compared with the 'k' in 'Mark'. Since these are not the same, the two strings are not equal. The character 'y' has a higher ASCII code (121) than 'k'

(107), so it is determined that the string 'Mary' is greater than the string 'Mark'.

If one of the strings in a comparison is shorter than the other, only the corresponding characters will be compared. If the corresponding characters are identical, then the shorter string is 4.3 Comparing Strings

133

considered less than the longer string. For example, suppose the strings 'High' and 'Hi'

were being compared. The string 'Hi' would be considered less than 'High' because it is shorter.

Program 4-4 shows a simple demonstration of how two strings can be compared with the Ͻ operator. The user is prompted to enter two names and the program displays those two names in alphabetical order.

Program 4-4

(sort_names.py)

1 # This program compare strings with the < operator.

2 # Get two names from the user.

3 name1 = input('Enter a name (last name first): ')

4 name2 = input('Enter another name (last name first): ') 5

6 # Display the names in alphabetical order.

7 print('Here are the names, listed alphabetically.') 8

9 if name1 < name2:

10 print(name1)

11 print(name2)

12 else:

13 print(name2)

14 print(name1)

Program Output (with input shown in bold)

Enter a name (last name first): Jones, Richard e Enter another name (last name first) Costa, Joan e Here are the names, listed alphabetically:

Costa, Joan

Jones, Richard

Checkpoint

4.11

What would the following code display?

if 'z' Ͻ 'a':

print('z is less than a.')

else:

print('z is not less than a.')

4.12

What would the following code display?

s1 = 'New York'

s2 = 'Boston'

134

Chapter 4

Decision Structures and Boolean Logic

if s1 Ͼ s2:

print(s2)

print(s1)

else:

print(s1)

print(s2)

4.4

Nested Decision Structures and the

if-elif-else Statement

CONCEPT: To test more than one condition, a decision structure can be nested inside another decision structure.

In Section 4.1, we mentioned that a control structure determines the order in which a set of statements execute. Programs are usually designed as combinations of different control structures. For example, Figure 4-12 shows a flowchart that combines a decision structure with two sequence structures.

Figure 4-12

Combining sequence structures with a decision structure Start

Go to the window.

Sequence structure

Read thermometer.

Cold

True

outside

Decision structure

Wear a coat.

False

Open the door.

Sequence structure

Go outside.

End

4.4 Nested Decision Structures and the if-elif-else Statement 135

The flowchart in the figure starts with a sequence structure. Assuming you have an outdoor thermometer in your window, the first step is Go to the window, and the next step is Read thermometer. A decision structure appears next, testing the condition Cold outside. If this is true, the action Wear a coat is performed. Another sequence structure appears next. The step Open the door is performed, followed by Go outside.

Quite often, structures must be nested inside other structures. For example, look at the partial flowchart in Figure 4-13. It shows a decision structure with a sequence structure nested inside it. The decision structure tests the condition Cold outside. If that condition is true, the steps in the sequence structure are executed.

Figure 4-13

A sequence structure nested inside a decision structure Cold

True

outside

Wear a coat.

False

Decision

structure

Sequence

Wear a hat.

structure

Wear gloves.

You can also nest decision structures inside other decision structures. In fact, this is a common requirement in programs that need to test more than one condition. For example, consider a program that determines whether a bank customer qualifies for a loan.

To qualify, two conditions must exist: (1) the customer must earn at least $30,000 per year, and (2) the customer must have been employed for at least two years. Figure 4-14

shows a flowchart for an algorithm that could be used in such a program. Assume that the salary variable is assigned the customer’s annual salary, and the years_on_job variable is assigned the number of years that the customer has worked on his or her current job.

136

Chapter 4

Decision Structures and Boolean Logic

Figure 4-14

A nested decision structure

False

True

salary >= 30000

print('You must earn at

least $30,000 per year

to qualify.')

False

True

years_on_job >= 2

print('You must have

been employed for at

print('You qualify for

least two years to

the loan.')

qualify.')

If we follow the flow of execution, we see that the condition salary >= 30000 is tested. If this condition is false, there is no need to perform further tests; we know that the customer does not qualify for the loan. If the condition is true, however, we need to test the second condition. This is done with a nested decision structure that tests the condition years_on_job

>= 2. If this condition is true, then the customer qualifies for the loan. If this condition is false, then the customer does not qualify. Program 4-5 shows the code for the complete program.

Program 4-5

(loan_qualifier.py)

1 # This program determines whether a bank customer

2 # qualifies for a loan.

3

4 # Constants for minimum salary and minimum

5 # years on the job

6 MIN_SALARY = 30000.0

7 MIN_YEARS = 2

8

9 def main():

10

# Get the customer's annual salary.

11

salary = float(input('Enter your annual salary: '))

12

4.4 Nested Decision Structures and the if-elif-else Statement 137

13

# Get the number of years on the current job.

14

years_on_job = int(input('Enter the number of ' +

15

'years employed: '))

16

17

# Determine whether the customer qualifies.

18

if salary >= MIN_SALARY:

19

if years_on_job >= MIN_YEARS:

20

print('You qualify for the loan.')

21

else:

22

print('You must have been employed', \

23

'for at least', MIN_YEARS, \

24

'years to qualify.')

25

else:

26

print('You must earn at least $', \

27

format(MIN_SALARY, ',.2f'), \

28

' per year to qualify.', sep='')

29

30 # Call the main function.

31 main()

Program Output (with input shown in bold)

Enter your annual salary: 35000 e

Enter the number of years employed: 1 e

You must have been employed for at least 2 years to qualify.

Program Output (with input shown in bold)

Enter your annual salary: 25000 e

Enter the number of years employed: 5 e

You must earn at least $30,000.00 per year to qualify.

Program Output (with input shown in bold)

Enter your annual salary: 35000 e

Enter the number of years employed: 5 e

You qualify for the loan.

Look at the if-else statement that begins in line 18. It tests the condition salary >=

MIN_SALARY. If this condition is true, the if-else statement that begins in line 19 is executed.

Otherwise the program jumps to the else clause in line 25 and executes the statement in lines 26 through 28. The program then leaves the decision structure and the main function ends.

It’s important to use proper indentation in a nested decision structure. Not only is proper indentation required by the Python interpreter, but it also makes it easier for you, the human reader of your code, to see which actions are performed by each part of the structure. Follow these rules when writing nested if statements:

• Make sure each else clause is aligned with its matching if clause. This is shown in Figure 4-15.

• Make sure the statements in each block are consistently indented. The shaded parts of Figure 4-16 show the nested blocks in the decision structure. Notice that each statement in each block is indented the same amount.

138

Chapter 4

Decision Structures and Boolean Logic

Figure 4-15

Alignment of if and else clauses

if salary >= MIN_SALARY:

This if

if years_on_job >= MIN_YEARS:

This if

and else

print('You qualify for the loan.')

and else

go together.

else:

go together.

print('You must have been employed', \

'for at least', MIN_YEARS, \

'years to qualify.')

else:

print('You must earn at least $', \

format(MIN_SALARY, ',.2f'), \

' per year to qualify.', sep='')

Figure 4-16

Nested blocks

if salary >= MIN_SALARY:

if years_on_job >= MIN_YEARS:

print('You qualify for the loan.')

else:

print('You must have been employed', \

'for at least', MIN_YEARS, \

'years to qualify.')

else:

print('You must earn at least $', \

format(MIN_SALARY, ',.2f'), \

' per year to qualify.', sep='')

Testing a Series of Conditions

In the previous example you saw how a program can use nested decision structures to test more than one condition. It is not uncommon for a program to have a series of conditions to test, and then perform an action depending on which condition is true. One way to accomplish this is to have a decision structure with numerous other decision structures nested inside it. For example, consider the program presented in the following In the Spotlight section.

In the Spotlight:

Multiple Nested Decision Structures

Dr. Suarez teaches a literature class and uses the following 10 point grading scale for all of his exams:

Test Score

Grade

90 and above

A

80–89

B

70–79

C

60–69

D

Below 60

F

4.4 Nested Decision Structures and the if-elif-else Statement 139

He has asked you to write a program that will allow a student to enter a test score and then display the grade for that score. Here is the algorithm that you will use: 1. Ask the user to enter a test score.

2. Determine the grade in the following manner:

If the score is greater than or equal to 90, then the grade is A.

Else, if the score is greater than or equal to 80, then the grade is B.

Else, if the score is greater than or equal to 70, then the grade is C.

Else, if the score is greater than or equal to 60, then the grade is D.

Else, the grade is F.

You decide that the process of determining the grade will require several nested decision structures, as shown in Figure 4-17. Program 4-6 shows the code for the program. The code for the nested decision structures is in lines 15 through 27.

Figure 4-17

Nested decision structure to determine a grade

False

True

score

>= 90

print('Your

False

True

grade is A.')

score

>= 80

print('Your

False

True

score

grade is B.')

>= 70

print('Your

False

True

score

grade is C.')

>= 60

print('Your

print('Your

grade is F.')

grade is D.')

Program 4-6

(grader.py)

1 # This program gets a numeric test score from the

2 # user and displays the corresponding letter grade.

3

4 # Constants for the grade thresholds

5 A_SCORE = 90

(program continues)

140

Chapter 4

Decision Structures and Boolean Logic

Program 4-6

(continued)

6 B_SCORE = 80

7 C_SCORE = 70

8 D_SCORE = 60

9

10 def main():

11 # Get a test score from the user.

12 score = int(input('Enter your test score: '))

13

14 # Determine the grade.

15 if score >= A_SCORE:

16 print('Your grade is A.')

17 else:

18 if score >= B_SCORE:

19 print('Your grade is B.')

20 else:

21 if score >= C_SCORE:

22 print('Your grade is C.')

23 else:

24 if score >= D_SCORE:

25 print('Your grade is D.')

26 else:

27 print('Your grade is F.')

28

29 # Call the main function.

30 main()

Program Output (with input shown in bold)

Enter your test score: 78 e

Your grade is C.

Program Output (with input shown in bold)

Enter your test score: 84 e

Your grade is B.

The if-elif-else Statement

Even though Program 4-6 is a simple example, the logic of the nested decision structure is fairly complex. Python provides a special version of the decision structure known as the if-elif-else statement, which makes this type of logic simpler to write. Here is the general format of the if-elif-else statement:

if condition_1:

statement

statement

etc.

elif condition_2:

statement

4.4 Nested Decision Structures and the if-elif-else Statement 141

statement

etc.

Insert as many elif clauses as necessary . . .

else:

statement

statement

etc.

When the statement executes, condition_1 is tested. If condition_1 is true, the block of statements that immediately follow is executed, up to the elif clause. The rest of the structure is ignored. If condition_1 is false, however, the program jumps to the very next elif clause and tests condition_2. If it is true, the block of statements that immediately follow is executed, up to the next elif clause. The rest of the structure is then ignored. This process continues until a condition is found to be true, or no more elif clauses are left. If no condition is true, the block of statements following the else clause is executed.

The following is an example of the if-elif-else statement. This code works the same as the nested decision structure in lines 15 through 27 of Program 4-6.

if score >= A_SCORE:

print('Your grade is A.')

elif score >= B_SCORE:

print('Your grade is B.')

elif score >= C_SCORE:

print('Your grade is C.')

elif score >= D_SCORE:

print('Your grade is D.')

else:

print('Your grade is F.')

Notice the alignment and indentation that is used with the if-elif-else statement: The if, elif, and else clauses are all aligned, and the conditionally executed blocks are indented.

The if-elif-else statement is never required because its logic can be coded with nested if-else statements. However, a long series of nested if-else statements has two particular disadvantages when you are debugging code:

• The code can grow complex and become difficult to understand.

• Because of the required indentation, a long series of nested if-else statements can become too long to be displayed on the computer screen without horizontal scrolling.

Also, long statements tend to “wrap around” when printed on paper, making the code even more difficult to read.

The logic of an if-elif-else statement is usually easier to follow than a long series of nested if-else statements. And, because all of the clauses are aligned in an if-elif-else statement, the lengths of the lines in the statement tend to be shorter.

Checkpoint

4.13

Convert the following code to an if-elif-else statement: if number == 1:

print('One')

142

Chapter 4

Decision Structures and Boolean Logic

else:

if number == 2:

print('Two')

else:

if number == 3:

print('Three')

else:

print('Unknown')

4.5

Logical Operators

CONCEPT: The logical and operator and the logical or operator allow you to connect multiple Boolean expressions to create a compound expression. The logical not operator reverses the truth of a Boolean expression.

Python provides a set of operators known as logical operators, which you can use to create complex Boolean expressions. Table 4-3 describes these operators.

Table 4-3

Logical operators

Operator

Meaning

and

The and operator connects two Boolean expressions into one compound expression. Both subexpressions must be true for the compound expression to be true.

or

The or operator connects two Boolean expressions into one compound expression. One or both subexpressions must be true for the compound expression to be true. It is only necessary for one of the subexpressions to be true, and it does not matter which.

not

The not operator is a unary operator, meaning it works with only one operand.

The operand must be a Boolean expression. The not operator reverses the truth of its operand. If it is applied to an expression that is true, the operator returns false. If it is applied to an expression that is false, the operator returns true.

Table 4-4 shows examples of several compound Boolean expressions that use logical operators.

Table 4-4

Compound Boolean expressions using logical operators

Expression

Meaning

x Ͼ y and a Ͻ b

Is x greater than y AND is a less than b?

x == y or x == z

Is x equal to y OR is x equal to z?

not (x Ͼ y)

Is the expression x Ͼ y NOT true?

4.5 Logical Operators

143

The and Operator

The and operator takes two Boolean expressions as operands and creates a compound Boolean expression that is true only when both subexpressions are true. The following is an example of an if statement that uses the and operator: if temperature Ͻ 20 and minutes Ͼ 12:

print('The temperature is in the danger zone.')

In this statement, the two Boolean expressions temperature Ͻ 20 and minutes Ͼ 12 are combined into a compound expression. The print function will be called only if temperature is less than 20 and minutes is greater than 12. If either of the Boolean subexpressions is false, the compound expression is false and the message is not displayed.

Table 4-5 shows a truth table for the and operator. The truth table lists expressions showing all the possible combinations of true and false connected with the and operator. The resulting values of the expressions are also shown.

Table 4-5

Truth table for the and operator

Expression

Value of the Expression

true and false

false

false and true

false

false and false

false

true and true

true

As the table shows, both sides of the and operator must be true for the operator to return a true value.

The or Operator

The or operator takes two Boolean expressions as operands and creates a compound Boolean expression that is true when either of the subexpressions is true. The following is an example of an if statement that uses the or operator: if temperature Ͻ 20 or temperature Ͼ 100:

print('The temperature is too extreme')

The print function will be called only if temperature is less than 20 or temperature is greater than 100. If either subexpression is true, the compound expression is true. Table 4-6

shows a truth table for the or operator.

Table 4-6

Truth table for the or operator

Expression

Value of the Expression

true or false

true

false or true

true

false or false

false

true or true

true

144

Chapter 4

Decision Structures and Boolean Logic

All it takes for an or expression to be true is for one side of the or operator to be true. It doesn’t matter if the other side is false or true.

Short-Circuit Evaluation

Both the and and or operators perform short-circuit evaluation. Here’s how it works with the and operator: If the expression on the left side of the and operator is false, the expression on the right side will not be checked. Because the compound expression will be false if only one of the subexpressions is false, it would waste CPU time to check the remaining expression. So, when the and operator finds that the expression on its left is false, it short-circuits and does not evaluate the expression on its right.

Here’s how short-circuit evaluation works with the or operator: If the expression on the left side of the or operator is true, the expression on the right side will not be checked.

Because it is only necessary for one of the expressions to be true, it would waste CPU time to check the remaining expression.

The not Operator

The not operator is a unary operator that takes a Boolean expression as its operand and reverses its logical value. In other words, if the expression is true, the not operator returns false, and if the expression is false, the not operator returns true. The following is an if statement using the not operator:

if not(temperature Ͼ 100):

print('This is below the maximum temperature.')

First, the expression (temperature Ͼ 100) is tested and a value of either true or false is the result. Then the not operator is applied to that value. If the expression (temperature Ͼ

100) is true, the not operator returns false. If the expression (temperature Ͼ 100) is false, the not operator returns true. The previous code is equivalent to asking: “Is the temperature not greater than 100?”

N O T E : In this example, we have put parentheses around the expression temperature Ͼ 100. This is to make it clear that we are applying the not operator to the value of the expression temperature Ͼ 100, not just to the temperature variable.

Table 4-7 shows a truth table for the not operator.

Table 4-7

Truth table for the not operator

Expression

Value of the Expression

not true

false

not false

true

4.5 Logical Operators

145

The Loan Qualifier Program Revisited

In some situations the and operator can be used to simplify nested decision structures. For example, recall that the loan qualifier program in Program 4-5 uses the following nested if-else statements:

if salary >= MIN_SALARY:

if years_on_job >= MIN_YEARS:

print('You qualify for the loan.')

else:

print('You must have been employed', \

'for at least', MIN_YEARS, \

'years to qualify.')

else:

print('You must earn at least $', \

format(MIN_SALARY, ',.2f'), \

' per year to qualify.', sep='')

The purpose of this decision structure is to determine that a person’s salary is at least $30,000 and that he or she has been at their current job for at least two years. Program 4-7

shows a way to perform a similar task with simpler code.

Program 4-7

(loan_qualifier2.py)

1 # This program determines whether a bank customer

2 # qualifies for a loan.

3

4 # Constants for minimum salary and minimum

5 # years on the job

6 MIN_SALARY = 30000.0

7 MIN_YEARS = 2

8

9 def main():

10

# Get the customer's annual salary.

11

salary = float(input('Enter your annual salary: '))

12

13

# Get the number of years on the current job.

14

years_on_job = int(input('Enter the number of ' +

15

'years employed: '))

16

17

# Determine whether the customer qualifies.

18

if salary >= MIN_SALARY and years_on_job >= MIN_YEARS: 19

print('You qualify for the loan.')

20

else:

21

print('You do not qualify for this loan.')

22

23 # Call the main function.

24 main()

(program continues)

146

Chapter 4

Decision Structures and Boolean Logic

Program 4-7

(continued)

Program Output (with input shown in bold)

Enter your annual salary: 35000 e

Enter the number of years employed: 1 e

You do not qualify for this loan.

Program Output (with input shown in bold)

Enter your annual salary: 25000 e

Enter the number of years employed: 5 e

You do not qualify for this loan.

Program Output (with input shown in bold)

Enter your annual salary: 35000 e

Enter the number of years employed: 5 e

You qualify for the loan.

The if-then-else statement in lines 18 through 21 tests the compound expression salary Ͼ= MIN_SALARY and years_on_job Ͼ= MIN_YEARS. If both subexpressions are true, the compound expression is true and the message “You qualify for the loan” is displayed. If either of the subexpressions is false, the compound expression is false and the message “You do not qualify for this loan” is displayed.

N O T E : A careful observer will realize that Program 4-7 is similar to Program 4-5, but it is not equivalent. If the user does not qualify for the loan, Program 4-7 displays only the message “You do not qualify for this loan” whereas Program 4-5 displays one of two possible messages explaining why the user did not qualify.

Yet Another Loan Qualifier Program

Suppose the bank is losing customers to a competing bank that isn’t as strict about whom it loans money to. In response, the bank decides to change its loan requirements. Now, customers have to meet only one of the previous conditions, not both. Program 4-8 shows the code for the new loan qualifier program. The compound expression that is tested by the if-else statement in line 18 now uses the or operator.

Program 4-8

(loan_qualifier3.py)

1 # This program determines whether a bank customer

2 # qualifies for a loan.

3

4 # Constants for minimum salary and minimum

5 # years on the job

6 MIN_SALARY = 30000.0

7 MIN_YEARS = 2

8

9 def main():

4.5 Logical Operators

147

10

# Get the customer's annual salary.

11

salary = float(input('Enter your annual salary: '))

12

13

# Get the number of years on the current job.

14

years_on_job = int(input('Enter the number of ' +

15

'years employed: '))

16

17

# Determine whether the customer qualifies.

18

if salary >= MIN_SALARY or years_on_job >= MIN_YEARS: 19

print('You qualify for the loan.')

20

else:

21

print('You do not qualify for this loan.')

22

23 # Call the main function.

24 main()

Program Output (with input shown in bold)

Enter your annual salary: 35000 e

Enter the number of years employed: 1 e

You qualify for the loan.

Program Output (with input shown in bold)

Enter your annual salary: 25000 e

Enter the number of years employed: 5 e

You qualify for the loan.

Program Output (with input shown in bold)

Enter your annual salary 12000 e

Enter the number of years employed: 1 e

You do not qualify for this loan.

Checking Numeric Ranges with Logical Operators

Sometimes you will need to design an algorithm that determines whether a numeric value is within a specific range of values or outside a specific range of values. When determining whether a number is inside a range, it is best to use the and operator. For example, the following if statement checks the value in x to determine whether it is in the range of 20 through 40: if x Ͼ= 20 and x Ͻ= 40:

print('The value is in the acceptable range.')

The compound Boolean expression being tested by this statement will be true only when x is greater than or equal to 20 and less than or equal to 40. The value in x must be within the range of 20 through 40 for this compound expression to be true.

When determining whether a number is outside a range, it is best to use the or operator.

The following statement determines whether x is outside the range of 20 through 40: if x Ͻ 20 or x Ͼ 40:

print('The value is outside the acceptable range.')

148

Chapter 4

Decision Structures and Boolean Logic

It is important not to get the logic of the logical operators confused when testing for a range of numbers. For example, the compound Boolean expression in the following code would never test true:

# This is an error!

if x Ͻ 20 and x Ͼ 40:

print('The value is outside the acceptable range.')

Obviously, x cannot be less than 20 and at the same time be greater than 40.

Checkpoint

4.14

What is a compound Boolean expression?

4.15

The following truth table shows various combinations of the values true and false connected by a logical operator. Complete the table by circling T or F to indicate whether the result of such a combination is true or false.

Logical Expression

Result (circle T or F)

True and False

T

F

True and True

T

F

False and True

T

F

False and False

T

F

True or False

T

F

True or True

T

F

False or True

T

F

False or False

T

F

not True

T

F

not False

T

F

4.16

Assume the variables a = 2, b = 4, and c = 6. Circle the T or F for each of the following conditions to indicate whether its value is true or false.

a == 4 or b Ͼ 2

T

F

6 Ͻ= c and a Ͼ 3

T

F

1 != b and c != 3

T

F

a Ͼ= -1 or a Ͻ= b

T

F

not (a Ͼ 2)

T

F

4.17

Explain how short-circuit evaluation works with the and and or operators.

4.18

Write an if statement that displays the message “The number is valid” if the value referenced by speed is within the range 0 through 200.

4.19

Write an if statement that displays the message “The number is not valid” if the value referenced by speed is outside the range 0 through 200.

4.6 Boolean Variables

149

4.6

Boolean Variables

CONCEPT: A Boolean variable can reference one of two values: True or False.

Boolean variables are commonly used as flags, which indicate whether specific conditions exist.

So far in this book we have worked with int, float, and str (string) variables. In addition to these data types, Python also provides a bool data type. The bool data type allows you to create variables that may reference one of two possible values: True or False. Here are examples of how we assign values to a bool variable: hungry = True

sleepy = False

Boolean variables are most commonly used as flags. A flag is a variable that signals when some condition exists in the program. When the flag variable is set to False, it indicates the condition does not exist. When the flag variable is set to True, it means the condition does exist.

For example, suppose a salesperson has a quota of $50,000. Assuming sales references the amount that the salesperson has sold, the following code determines whether the quota has been met:

if sales Ͼ= 50000.0:

sales_quota_met = True

else:

sales_quota_met = False

As a result of this code, the sales_quota_met variable can be used as a flag to indicate whether the sales quota has been met. Later in the program we might test the flag in the following way:

if sales_quota_met:

print('You have met your sales quota!')

This code displays 'You have met your sales quota!' if the bool variable sales_quota_met is True. Notice that we did not have to use the == operator to explicitly compare the sales_quota_met variable with the value True. This code is equivalent to the following:

if sales_quota_met == True:

print('You have met your sales quota!')

Checkpoint

4.20

What values can you assign to a bool variable?

4.21

What is a flag variable?

150

Chapter 4

Decision Structures and Boolean Logic

Review Questions

Multiple Choice

1. A __________ structure can execute a set of statements only under certain circumstances.

a. sequence

b. circumstantial

c. decision

d. Boolean

2. A __________ structure provides one alternative path of execution.

a. sequence

b. single alternative decision

c. one path alternative

d. single execution decision

3. A(n) __________ expression has a value of either true or false.

a. binary

b. decision

c. unconditional

d. Boolean

4. The symbols Ͼ, Ͻ, and == are all __________ operators.

a. relational

b. logical

c. conditional

d. ternary

5. A(n) _________ structure tests a condition and then takes one path if the condition is true, or another path if the condition is false.

a. if statement

b. single alternative decision

c. dual alternative decision

d. sequence

6. You use a(n) __________ statement to write a single alternative decision structure.

a. test-jump

b. if

c. if-else

d. if-call

7. You use a(n) __________ statement to write a dual alternative decision structure.

a. test-jump

b. if

c. if-else

d. if-call

Review Questions

151

8. and, or, and not are __________ operators.

a. relational

b. logical

c. conditional

d. ternary

9. A compound Boolean expression created with the __________ operator is true only if both of its subexpressions are true.

a. and

b. or

c. not

d. both

10. A compound Boolean expression created with the _________ operator is true if either of its subexpressions is true.

a. and

b. or

c. not

d. either

11. The ___________ operator takes a Boolean expression as its operand and reverses its logical value.

a. and

b. or

c. not

d. either

12. A ___________ is a Boolean variable that signals when some condition exists in the program.

a. flag

b. signal

c. sentinel

d. siren

True or False

1. You can write any program using only sequence structures.

2. A program can be made of only one type of control structure. You cannot combine structures.

3. A single alternative decision structure tests a condition and then takes one path if the condition is true, or another path if the condition is false.

4. A decision structure can be nested inside another decision structure.

5. A compound Boolean expression created with the and operator is true only when both subexpressions are true.

Short Answer

1. Explain what is meant by the term “conditionally executed.” 2. You need to test a condition and then execute one set of statements if the condition is true. If the condition is false, you need to execute a different set of statements. What structure will you use?

152

Chapter 4

Decision Structures and Boolean Logic

3. Briefly describe how the and operator works.

4. Briefly describe how the or operator works.

5. When determining whether a number is inside a range, which logical operator is it best to use?

6. What is a flag and how does it work?

Algorithm Workbench

1. Write an if statement that assigns 20 to the variable y and assigns 40 to the variable z if the variable x is greater than 100.

2. Write an if statement that assigns 0 to the variable b and assigns 1 to the variable c if the variable a is less than 10.

3. Write an if-else statement that assigns 0 to the variable b if the variable a is less than 10. Otherwise, it should assign 99 to the variable b.

4. The following code contains several nested if-else statements. Unfortunately, it was written without proper alignment and indentation. Rewrite the code and use the proper conventions of alignment and indentation.

if score >= A_SCORE:

print('Your grade is A.')

else:

if score >= B_SCORE:

print('Your grade is B.')

else:

if score >= C_SCORE:

print('Your grade is C.')

else:

if score >= D_SCORE:

print('Your grade is D.')

else:

print('Your grade is F.')

5. Write nested decision structures that perform the following: If amount1 is greater than 10

and amount2 is less than 100, display the greater of amount1 and amount2.

6. Write an if-else statement that displays 'Speed is normal' if the speed variable is within the range of 24 to 56. If the speed variable’s value is outside this range, display 'Speed is abnormal'.

7. Write an if-else statement that determines whether the points variable is outside the range of 9 to 51. If the variable’s value is outside this range it should display “Invalid points.” Otherwise, it should display “Valid points.”

Programming Exercises

1. Roman Numerals

Write a program that prompts the user to enter a number within the range of 1 through 10.

The program should display the Roman numeral version of that number. If the number is outside the range of 1 through 10, the program should display an error message. The following table shows the Roman numerals for the numbers 1 through 10: Programming Exercises

153

Number

Roman Numeral

1

I

2

II

3

III

4

IV

5

V

6

VI

7

VII

8

VIII

9

IX

10

X

2. Areas of Rectangles

The area of a rectangle is the rectangle’s length times its width. Write a program that asks VideoNote

The Areas of

for the length and width of two rectangles. The program should tell the user which rectangle Rectangles Problem

has the greater area, or if the areas are the same.

3. Mass and Weight

Scientists measure an object’s mass in kilograms and its weight in newtons. If you know the amount of mass of an object in kilograms, you can calculate its weight in newtons with the following formula:

weight ϭ mass ϫ 9.8

Write a program that asks the user to enter an object’s mass, and then calculates its weight.

If the object weighs more than 1,000 newtons, display a message indicating that it is too heavy. If the object weighs less than 10 newtons, display a message indicating that it is too light.

4. Magic Dates

The date June 10, 1960, is special because when it is written in the following format, the month times the day equals the year:

6/10/60

Design a program that asks the user to enter a month (in numeric form), a day, and a two-digit year. The program should then determine whether the month times the day equals the year. If so, it should display a message saying the date is magic. Otherwise, it should display a message saying the date is not magic.

5. Color Mixer

The colors red, blue, and yellow are known as the primary colors because they cannot be made by mixing other colors. When you mix two primary colors, you get a secondary color, as shown here:

When you mix red and blue, you get purple.

When you mix red and yellow, you get orange.

When you mix blue and yellow, you get green.

154

Chapter 4

Decision Structures and Boolean Logic

Design a program that prompts the user to enter the names of two primary colors to mix.

If the user enters anything other than “red,” “blue,” or “yellow,” the program should display an error message. Otherwise, the program should display the name of the secondary color that results.

6. Change for a Dollar Game

Create a change-counting game that gets the user to enter the number of coins required to make exactly one dollar. The program should prompt the user to enter the number of pennies, nickels, dimes, and quarters. If the total value of the coins entered is equal to one dollar, the program should congratulate the user for winning the game. Otherwise, the program should display a message indicating whether the amount entered was more than or less than one dollar.

7. Book Club Points

Serendipity Booksellers has a book club that awards points to its customers based on the number of books purchased each month. The points are awarded as follows:

• If a customer purchases 0 books, he or she earns 0 points.

• If a customer purchases 1 book, he or she earns 5 points.

• If a customer purchases 2 books, he or she earns 15 points.

• If a customer purchases 3 books, he or she earns 30 points.

• If a customer purchases 4 or more books, he or she earns 60 points.

Write a program that asks the user to enter the number of books that he or she has purchased this month and displays the number of points awarded.

8. Software Sales

A software company sells a package that retails for $99. Quantity discounts are given according to the following table:

Quantity

Discount

10–19

20%

20–49

30%

50–99

40%

100 or more

50%

Write a program that asks the user to enter the number of packages purchased. The program should then display the amount of the discount (if any) and the total amount of the purchase after the discount.

9. Shipping Charges

The Fast Freight Shipping Company charges the following rates: Weight of Package

Rate per Pound

2 pounds or less

$1.10

Over 2 pounds but not more than 6 pounds

$2.20

Over 6 pounds but not more than 10 pounds

$3.70

Over 10 pounds

$3.80

Programming Exercises

155

Write a program that asks the user to enter the weight of a package and then displays the shipping charges.

10. Body Mass Index Program Enhancement

In programming Exercise #6 in Chapter 3 you were asked to write a program that calculates a person’s body mass index (BMI). Recall from that exercise that the BMI is often used to determine whether a person is overweight or underweight for their height. A person’s BMI is calculated with the formula

BMI ϭ weight ϫ 703 / height 2

where weight is measured in pounds and height is measured in inches. Enhance the program so it displays a message indicating whether the person has optimal weight, is underweight, or is overweight. A person’s weight is considered to be optimal if his or her BMI is between 18.5 and 25. If the BMI is less than 18.5, the person is considered to be underweight. If the BMI value is greater than 25, the person is considered to be overweight.

11. Time Calculator

Write a program that asks the user to enter a number of seconds, and works as follows:

• There are 60 seconds in a minute. If the number of seconds entered by the user is greater than or equal to 60, the program should display the number of minutes in that many seconds.

• There are 3,600 seconds in an hour. If the number of seconds entered by the user is greater than or equal to 3,600, the program should display the number of hours in that many seconds.

• There are 86,400 seconds in a day. If the number of seconds entered by the user is greater than or equal to 86,400, the program should display the number of days in that many seconds.

This page intentionally left blank

Repetition Structures

CHAPTER

5

TOPICS

5.1

Introduction to Repetition Structures

5.4

Calculating a Running Total

5.2

The while Loop: a Condition-

5.5

Sentinels

Controlled Loop

5.6

Input Validation Loops

5.3

The for Loop: a Count-Controlled Loop

5.7

Nested Loops

5.1

Introduction to Repetition Structures

CONCEPT: A repetition structure causes a statement or set of statements to execute repeatedly.

Programmers commonly have to write code that performs the same task over and over. For example, suppose you have been asked to write a program that calculates a 10 percent sales commission for several sales people. Although it would not be a good design, one approach would be to write the code to calculate one sales person’s commission, and then repeat that code for each sales person. For example, look at the following:

# Get a salesperson's sales and commission rate.

sales = float(input('Enter the amount of sales: '))

comm_rate = float(input('Enter the commission rate: '))

# Calculate the commission.

commission = sales * comm_rate

# Display the commission.

print('The commission is $', format(commission, ',.2f', sep=''))

# Get another salesperson's sales and commission rate.

sales = float(input('Enter the amount of sales: '))

comm_rate = float(input('Enter the commission rate: '))

# Calculate the commission.

commission = sales * comm_rate

157

158

Chapter 5

Repetition Structures

# Display the commission.

print('The commission is $', format(commission, ',.2f', sep=''))

# Get another salesperson's sales and commission rate.

sales = float(input('Enter the amount of sales: '))

comm_rate = float(input('Enter the commission rate: '))

# Calculate the commission.

commission = sales * comm_rate

# Display the commission.

print('The commission is $', format(commission, ',.2f', sep='')) And this code goes on and on . . .

As you can see, this code is one long sequence structure containing a lot of duplicated code.

There are several disadvantages to this approach, including the following:

• The duplicated code makes the program large.

• Writing a long sequence of statements can be time consuming.

• If part of the duplicated code has to be corrected or changed then the correction or change has to be done many times.

Instead of writing the same sequence of statements over and over, a better way to repeatedly perform an operation is to write the code for the operation once, and then place that code in a structure that makes the computer repeat it as many times as necessary. This can be done with a repetition structure, which is more commonly known as a loop.

Condition-Controlled and Count-Controlled Loops

In this chapter, we will look at two broad categories of loops: condition-controlled and count-controlled. A condition-controlled loop uses a true/false condition to control the number of times that it repeats. A count-controlled loop repeats a specific number of times.

In Python you use the while statement to write a condition-controlled loop, and you use the for statement to write a count-controlled loop. In this chapter, we will demonstrate how to write both types of loops.

Checkpoint

5.1

What is a repetition structure?

5.2

What is a condition-controlled loop?

5.3

What is a count-controlled loop?

5.2

The while Loop: a Condition-Controlled Loop

CONCEPT: A condition-controlled loop causes a statement or set of statements to repeat as long as a condition is true. In Python you use the while state-VideoNote

The while Loop

ment to write a condition-controlled loop.

5.2 The while Loop: a Condition-Controlled Loop

159

The while loop gets its name from the way it works: while a condition is true, do some task. The loop has two parts: (1) a condition that is tested for a true or false value, and (2) a statement or set of statements that is repeated as long as the condition is true. Figure 5-1

shows the logic of a while loop.

Figure 5-1

The logic of a while loop

True

Condition

Statement(s)

False

The diamond symbol represents the condition that is tested. Notice what happens if the condition is true: one or more statements are executed and the program’s execution flows back to the point just above the diamond symbol. The condition is tested again, and if it is true, the process repeats. If the condition is false, the program exits the loop. In a flowchart, you will always recognize a loop when you see a flow line going back to a previous part of the flowchart.

Here is the general format of the while loop in Python: while condition:

statement

statement

etc.

For simplicity, we will refer to the first line as the while clause. The while clause begins with the word while, followed by a Boolean condition that will be evaluated as either true or false. A colon appears after the condition. Beginning at the next line is a block of statements. (Recall from Chapter 3 that all of the statements in a block must be consistently indented. This indentation is required because the Python interpreter uses it to tell where the block begins and ends.)

When the while loop executes, the condition is tested. If the condition is true, the statements that appear in the block following the while clause are executed, and then the loop starts over. If the condition is false, the program exits the loop. Program 5-1 shows how we might use a while loop to write the commission calculating program that was described at the beginning of this chapter.

160

Chapter 5

Repetition Structures

Program 5-1

(commission.py)

1 # This program calculates sales commissions.

2 def main():

3

# Create a variable to control the loop.

4

keep_going = 'y'

5

6

# Calculate a series of commissions.

7

while keep_going == 'y':

8

# Get a salesperson's sales and commission rate.

9

sales = float(input('Enter the amount of sales: '))

10

comm_rate = float(input('Enter the commission rate: ')) 11

12

# Calculate the commission.

13

commission = sales * comm_rate

14

15

# Display the commission.

16

print('The commission is $', \

17

format(commission, ',.2f'), sep='')

18

19

# See if the user wants to do another one.

20

keep_going = input('Do you want to calculate another ' + \

21

'commission (Enter y for yes): ')

22

23 # Call the main function.

24 main()

Program Output (with input shown in bold)

Enter the amount of sales: 10000.00 e

Enter the commission rate: 0.10 e

The commission is $1,000.00.

Do you want to calculate another commission (Enter y for yes): y e Enter the amount of sales: 20000.00 e

Enter the commission rate: 0.15 e

The commission is $3,000.00.

Do you want to calculate another commission (Enter y for yes): y e Enter the amount of sales: 12000.00 e

Enter the commission rate: 0.10 e

The commission is $1,200.00.

Do you want to calculate another commission (Enter y for yes): n e In line 4 we use an assignment statement to create a variable named keep_going. Notice that the variable is assigned the value 'y'. This initialization value is important, and in a moment you will see why.

Line 7 is the beginning of a while loop, which starts like this: while keep_going == 'y':

5.2 The while Loop: a Condition-Controlled Loop

161

Notice the condition that is being tested: keep_going == 'y'. The loop tests this condition, and if it is true, the statements in lines 8 through 21 are executed. Then, the loop starts over at line 7. It tests the expression keep_going == 'y' and if it is true, the statements in lines 8

through 21 are executed again. This cycle repeats until the expression keep_going == 'y' is tested in line 7 and found to be false. When that happens, the program exits the loop. This is illustrated in Figure 5-2.

Figure 5-2

The while loop

This condition is tested.

while keep_going == 'y':

# Get a salesperson's sales and commission rate.

sales = float(input('Enter the amount of sales: '))

comm_rate = float(input('Enter the commission rate: ')) If the condition is true,

these statements are

# Calculate the commission.

executed, and then the

commission = sales * comm_rate

loop starts over.

# Display the commission.

If the condition is false,

print('The commission is $', \

these statements are

format(commission, ',.2f'), sep='')

skipped and the

program exits the loop.

# See if the user wants to do another one.

keep_going = input('Do you want to calculate another ' + \

'commission (Enter y for yes): ')

In order for this loop to stop executing, something has to happen inside the loop to make the expression keep_going == 'y' false. The statement in lines 20 through 21 take care of this. This statement displays the prompt “Do you want to calculate another commission (Enter y for yes).” The value that is read from the keyboard is assigned to the keep_going variable. If the user enters y (and it must be a lowercase y), then the expression keep_going == 'y' will be true when the loop starts over. This will cause the statements in the body of the loop to execute again. But if the user enters anything other than lowercase y, the expression will be false when the loop starts over, and the program will exit the loop.

Now that you have examined the code, look at the program output in the sample run. First, the user entered 10000.00 for the sales and 0.10 for the commission rate. Then, the program displayed the commission for that amount, which is $1,000.00. Next the user is prompted “Do you want to calculate another commission? (Enter y for yes).” The user entered y, and the loop started the steps over. In the sample run, the user went through this process three times. Each execution of the body of a loop is known as an iteration. In the sample run, the loop iterated three times.

Figure 5-3 shows a flowchart for the main function. In the flowchart we have a repetition structure, which is the while loop. The condition keep_going == 'y' is tested, and if it is true a series of statements are executed and the flow of execution returns to the point just above the conditional test.

162

Chapter 5

Repetition Structures

Figure 5-3

Flowchart for Program 5-1

main()

Assign 'y' to keep_going

True

keep_going == 'y'

Prompt the user to enter

the amount of sales and

assign it to sales.

False

Prompt the user to enter

the commission rate and

Return

assign it to comm_rate.

commission = sales *

comm_rate

Display the

commission

Prompt the user: 'Do you

want to calculate another

commission? (Enter y for

yes)' and assign the input

to keep_going.

The while Loop is a Pretest Loop

The while loop is known as a pretest loop, which means it tests its condition before performing an iteration. Because the test is done at the beginning of the loop, you usually have 5.2 The while Loop: a Condition-Controlled Loop

163

to perform some steps prior to the loop to make sure that the loop executes at least once.

For example, the loop in Program 5-1 starts like this: while keep_going == 'y':

The loop will perform an iteration only if the expression keep_going == 'y' is true.

This means that (a) the keep_going variable has to exist, and (b) it has to reference the value 'y'. To make sure the expression is true the first time that the loop executes, we assigned the value 'y' to the keep_going variable in line 4 as follows: keep_going = 'y'

By performing this step we know that the condition keep_going == 'y' will be true the first time the loop executes. This is an important characteristic of the while loop: it will never execute if its condition is false to start with. In some programs, this is exactly what you want. The following In the Spotlight section gives an example.

In the Spotlight:

Designing a Program with a while Loop

A project currently underway at Chemical Labs, Inc. requires that a substance be continually heated in a vat. A technician must check the substance’s temperature every 15 minutes.

If the substance’s temperature does not exceed 102.5 degrees Celsius, then the technician does nothing. However, if the temperature is greater than 102.5 degrees Celsius, the technician must turn down the vat’s thermostat, wait 5 minutes, and check the temperature again. The technician repeats these steps until the temperature does not exceed 102.5 degrees Celsius. The director of engineering has asked you to write a program that guides the technician through this process.

Here is the algorithm:

1. Get the substance’s temperature.

2. Repeat the following steps as long as the temperature is greater than 102.5 degrees Celsius:

a. Tell the technician to turn down the thermostat, wait 5 minutes, and check the temperature again.

b. Get the substance’s temperature.

3. After the loop finishes, tell the technician that the temperature is acceptable and to check it again in 15 minutes.

After reviewing this algorithm, you realize that steps 2(a) and 2(b) should not be performed if the test condition (temperature is greater than 102.5) is false to begin with. The while loop will work well in this situation, because it will not execute even once if its condition is false. Program 5-2 shows the code for the program.

164

Chapter 5

Repetition Structures

Program 5-2

(temperature.py)

1

# This program assists a technician in the process

2

# of checking a substance's temperature.

3

4

# MAX_TEMP is used as a global constant for

5

# the maximum temperature.

6

MAX_TEMP = 102.5

7

8

# The main function

9

def main():

10

# Get the substance's temperature.

11

temperature = float(input("Enter the substance's Celsius temperature: ")) 12

13

# As long as necessary, instruct the user to

14

# adjust the thermostat.

15

while temperature > MAX_TEMP:

16

print('The temperature is too high.')

17

print('Turn the thermostat down and wait')

18

print('5 minutes. Then take the temperature')

19

print('again and enter it.')

20

temperature = float(input('Enter the new Celsius temperature: ')) 21

22

# Remind the user to check the temperature again

23

# in 15 minutes.

24

print('The temperature is acceptable.')

25

print('Check it again in 15 minutes.')

26

27

# Call the main function.

28

main()

Program Output (with input shown in bold)

Enter the substance's Celsius temperature: 104.7 e The temperature is too high.

Turn the thermostat down and wait

5 minutes. Take the temperature

again and enter it.

Enter the new Celsius temperature: 103.2 e

The temperature is too high.

Turn the thermostat down and wait

5 minutes. Take the temperature

again and enter it.

Enter the new Celsius temperature: 102.1 e

The temperature is acceptable.

Check it again in 15 minutes.

5.2 The while Loop: a Condition-Controlled Loop

165

Program Output (with input shown in bold)

Enter the substance's Celsius temperature: 102.1 e The temperature is acceptable.

Check it again in 15 minutes.

Infinite Loops

In all but rare cases, loops must contain within themselves a way to terminate. This means that something inside the loop must eventually make the test condition false. The loop in Program 5-1 stops when the expression keep_going == 'y' is false. If a loop does not have a way of stopping, it is called an infinite loop. An infinite loop continues to repeat until the program is interrupted. Infinite loops usually occur when the programmer forgets to write code inside the loop that makes the test condition false. In most circumstances you should avoid writing infinite loops.

Program 5-3 demonstrates an infinite loop. This is a modified version of the commission calculating program shown in Program 5-1. In this version, we have removed the code that modifies the keep_going variable in the body of the loop. Each time the expression keep_going == 'y' is tested in line 7, keep_going will reference the string ‘y’. As a consequence, the loop has no way of stopping. (The only way to stop this program is to press Ctrl+C on the keyboard to interrupt it.)

Program 5-3

(infinite.py)

1 # This program demonstrates an infinite loop.

2 def main():

3

# Create a variable to control the loop.

4

keep_going = 'y'

5

6

# Warning! Infinite loop!

7

while keep_going == 'y':

8

# Get a salesperson's sales and commission rate.

9

sales = float(input('Enter the amount of sales: '))

10

comm_rate = float(input('Enter the commission rate: ')) 11

12

# Calculate the commission.

13

commission = sales * comm_rate

14

15

# Display the commission.

16

print('The commission is $', \

17

format(commission, ',.2f'), sep='')

18

19 # Call the main function.

20 main()

166

Chapter 5

Repetition Structures

Calling Functions in a Loop

Functions can be called from statements in the body of a loop. In fact, such code in a loop often improves the design. For example, in Program 5-1, the statements that get the amount of sales, calculate the commission, and display the commission can easily be placed in a function. That function can then be called in the loop. Program 5-4 shows how this might be done.

This program has a main function, which is called when the program runs, and a show_

commission function that handles all of the steps related to calculating and displaying a commission. Figure 5-4 shows flowcharts for the main and show_commission functions.

Program 5-4

(commission2.py)

1 # This program calculates sales commissions.

2 def main():

3

# Create a variable to control the loop.

4

keep_going = 'y'

5

6

# Calculate a series of commissions.

7

while keep_going == 'y':

8

# Call the show_commission function to

9

# display a salesperson's commission.

10

show_commission()

11

12

# See if the user wants to do another one.

13

keep_going = input('Do you want to calculate another ' + \

14

'commission (Enter y for yes): ')

15

16 # The show_commission function gets the amount of

17 # sales and the commission rate, and then displays

18 # the amount of commission.

19 def show_commission():

20

# Get a salesperson's sales and commission rate.

21

sales = float(input('Enter the amount of sales: '))

22

comm_rate = float(input('Enter the commission rate: ')) 23

24

# Calculate the commission.

25

commission = sales * comm_rate

26

27

# Display the commission.

28

print('The commission is $', \

29

format(commission, ',.2f'), sep='')

30

31 # Call the main function.

32 main()

The output of this program is the same as that of Program 5-1

5.3 The for Loop: a Count-Controlled Loop

167

Figure 5-4

Flowcharts for the main and show_commission functions

main()

show_commission( )

Prompt the user to enter

Assign 'y' to keep_going

the amount of sales and

assign it to sales.

Prompt the user to enter

the commission rate and

assign it to comm_rate.

True

commission = sales *

keep_going == 'y'

comm_rate

show_commission( )

Display the

commission

False

Prompt the user: 'Do you

Return

want to calculate another

Return

commission? (Enter y for

yes)' and assign the input

to keep_going.

Checkpoint

5.4

What is a loop iteration?

5.5

Does the while loop test its condition before or after it performs an iteration?

5.6

How many times will 'Hello World' be printed in the following program?

count = 10

while count < 1:

print('Hello World')

5.7

What is an infinite loop?

5.3

The for Loop: a Count-Controlled Loop

CONCEPT: A count-controlled loop iterates a specific number of times. In Python you use the for statement to write a count-controlled loop.

As mentioned at the beginning of this chapter, a count-controlled loop iterates a specific VideoNote

The for Loop

number of times. Count-controlled loops are commonly used in programs. For example, 168

Chapter 5

Repetition Structures

suppose a business is open six days per week, and you are going to write a program that calculates the total sales for a week. You will need a loop that iterates exactly six times.

Each time the loop iterates, it will prompt the user to enter the sales for one day.

You use the for statement to write a count-controlled loop. In Python, the for statement is designed to work with a sequence of data items. When the statement executes, it iterates once for each item in the sequence. Here is the general format: for variable in [value1, value2, etc.]:

statement

statement

etc.

We will refer to the first line as the for clause. In the for clause, variable is the name of a variable. Inside the brackets a sequence of values appears, with a comma separating each value. (In Python, a comma-separated sequence of data items that are enclosed in a set of brackets is called a list. In Chapter 8 you will learn more about lists.) Beginning at the next line is a block of statements that is executed each time the loop iterates.

The for statement executes in the following manner: The variable is assigned the first value in the list, and then the statements that appear in the block are executed. Then, variable is assigned the next value in the list, and the statements in the block are executed again. This continues until variable has been assigned the last value in the list.

Program 5-5 shows a simple example that uses a for loop to display the numbers 1

through 5.

Program 5-5

(simple_loop1.py)

1

# This program demonstrates a simple for loop

2

# that uses a list of numbers.

3

4

def main():

5

print('I will display the numbers 1 through 5.')

6

for num in [1, 2, 3, 4, 5]:

7

print(num)

8

9

# Call the main function.

10

main()

Program Output

I will display the numbers 1 through 5.

1

2

3

4

5

The first time the for loop iterates, the num variable is assigned the value 1 and then the print statement in line 7 executes (displaying the value 1). The next time the loop iterates, 5.3 The for Loop: a Count-Controlled Loop

169

num is assigned the value 2, and the print statement executes (displaying the value 2). This process continues, as shown in Figure 5-5, until num has been assigned the last value in the list. Because the list contains five values, the loop will iterate five times.

Python programmers commonly refer to the variable that is used in the for clause as the target variable because it is the target of an assignment at the beginning of each loop iteration.

Figure 5-5

The for loop

for num in [1, 2, 3, 4, 5]:

1st iteration:

print(num)

2nd iteration:

for num in [1, 2, 3, 4, 5]:

print(num)

3rd iteration:

for num in [1, 2, 3, 4, 5]:

print(num)

4th iteration:

for num in [1, 2, 3, 4, 5]:

print(num)

5th iteration:

for num in [1, 2, 3, 4, 5]:

print(num)

The values that appear in the list do not have to be a consecutively ordered series of numbers. For example, Program 5-6 uses a for loop to display a list of odd numbers. There are five numbers in the list, so the loop iterates five times.

Program 5-6

(simple_loop2.py)

1

# This program also demonstrates a simple for

2

# loop that uses a list of numbers.

3

4

def main():

5

print('I will display the odd numbers 1 through 9.')

6

for num in [1, 3, 5, 7, 9]:

7

print(num)

8

9

# Call the main function.

10

main()

(program output continues)

170

Chapter 5

Repetition Structures

Program 5-6

(continued)

Program Output

I will display the odd numbers 1 through 9.

1

3

5

7

9

Program 5-7 shows another example. In this program the for loop iterates over a list of strings. Notice that the list (in line 5) contains the three strings ‘Winken’, ‘Blinken’, and

‘Nod’. As a result, the loop iterates three times.

Program 5-7

(simple_loop3.py)

1

# This program also demonstrates a simple for

2

# loop that uses a list of strings.

3

4

def main():

5

for name in ['Winken', 'Blinken', 'Nod']:

6

print(name)

7

8

# Call the main function.

9

main()

Program Output

Winken

Blinken

Nod

Using the range Function with the for Loop

Python provides a built-in function named range that simplifies the process of writing a count-controlled for loop. The range function creates a type of object known as an iterable. An iterable is an object which is similar to a list. It contains a sequence of values that can be iterated over with something like a loop. Here is an example of a for loop that uses the range function: for num in range(5):

print(num)

Notice that instead of using a list of values, we call to the range function passing 5 as an argument. In this statement the range function will generate an iterable sequence of integers in the range of 0 up to (but not including) 5. This code works the same as the following: for num in [0, 1, 2, 3, 4]:

print(num)

5.3 The for Loop: a Count-Controlled Loop

171

As you can see, the list contains five numbers, so the loop will iterate five times. Program 5-8

uses the range function with a for loop to display “Hello world” five times.

Program 5-8

(simple_loop4.py)

1

# This program demonstrates how the range

2

# function can be used with a for loop.

3

4

def main():

5

# Print a message five times.

6

for x in range(5):

7

print('Hello world!')

8

9

# Call the main function.

10

main()

Program Output

Hello world

Hello world

Hello world

Hello world

Hello world

If you pass one argument to the range function, as demonstrated in Program 5-8, that argument is used as the ending limit of the sequence of numbers. If you pass two arguments to the range function, the first argument is used as the starting value of the sequence and the second argument is used as the ending limit. Here is an example: for num in range(1, 5):

print(num)

This code will display the following:

1

2

3

4

By default, the range function produces a sequence of numbers that increase by 1 for each successive number in the list. If you pass a third argument to the range function, that argument is used as step value. Instead of increasing by 1, each successive number in the sequence will increase by the step value. Here is an example: for num in range(1, 10, 2):

print(num)

In this for statement, three arguments are passed to the range function:

• The first argument, 1, is the starting value for the sequence.

• The second argument, 10, is the ending limit of the list. This means that the last number in the sequence will be 9.

172

Chapter 5

Repetition Structures

• The third argument, 2, is the step value. This means that 2 will be added to each successive number in the sequence.

This code will display the following:

1

3

5

7

9

Using the Target Variable Inside the Loop

In a for loop, the purpose of the target variable is to reference each item in a sequence of items as the loop iterates. In many situations it is helpful to use the target variable in a calculation or other task within the body of the loop. For example, suppose you need to write a program that displays the numbers 1 through 10 and their squares, in a table similar to the following:

Number

Square

1

1

2

4

3

9

4

16

5

25

6

36

7

49

8

64

9

81

10

100

This can be accomplished by writing a for loop that iterates over the values 1 through 10.

During the first iteration, the target variable will be assigned the value 1, during the second iteration it will be assigned the value 2, and so forth. Because the target variable will reference the values 1 through 10 during the loop’s execution, you can use it in the calculation inside the loop. Program 5-9 shows how this is done.

Program 5-9

(squares.py)

1

# This program uses a loop to display a

2

# table showing the numbers 1 through 10

3

# and their squares.

4

5.3 The for Loop: a Count-Controlled Loop

173

5

def main():

6

# Print the table headings.

7

print('Number\tSquare')

8

print('--------------')

9

10

# Print the numbers 1 through 10

11

# and their squares.

12

for number in range(1, 11):

13

square = number**2

14

print(number, '\t', square)

15

16

# Call the main function.

17

main()

Program Output

Number Square

---------------

1

1

2

4



two page view?


Share "Starting Out with Python":

Download for all devices (1.35 MB)