Hour 6
Controlling Your Programs

This hour’s lesson extends your knowledge of Python by showing you how to compare values and repeat sections of Python programs. A user’s responses or calculated data can control the flow of your program. This lesson teaches you how to write programs that make decisions. The code sometimes needs to repeat sections in order to complete the processing of several data values. You’ll learn how to create a loop to do just that.

With the concepts that you learn in this lesson, you can write powerful programs to do what you need done. You will find yourself thinking of new ideas and new ways to use your computer.

The highlights of this hour include the following:

Image Making decisions with Python

Image Using the if statement

Image Changing decisions with the elif and else statements

Image Repeating sections of code

Image Using the for loop

Image Using while loops

Comparing Data with if

Python provides the ability for a program to make a choice and to perform one action or another action, depending on a condition. A Python decision statement has two possibilities. To decide which path to take in a Python program, you must use the if statement. Most programming languages have an if statement that works exactly like Python’s. Therefore, once you learn how Python supports the if statement, you will be able to apply the same principles for most other computer languages as well.

Writing the Relational Test

The if statement reads just as it does in plain English: If something is true, do one thing; otherwise, do something else. You do not always add an else after a spoken if, and you do not have to have one in Python, either. Consider the following statements:

If I make enough money, I’ll retire early.

If you’re out late, call me, or you’ll get in trouble.

If you’re in town, we’ll eat dinner together.

As a programming language, Python is fairly strict about how you make the if test. The relational test—the statement to the right of the if—usually includes one of the symbols from Table 6.1.

TABLE 6.1 if statement relational operators determine how the if behaves

Operator Description Example
< Less than if (sales < maxSales)
> Greater than if (amount > 100.00)
== Equal to if (age == 21)
>= Greater than or equal to if (grade >= 90)
<= Less than or equal to if (price <= 1.00)
!= Not equal to if (year != 2004)

You learned about math operators in Hour 5, “Data Processing with Numbers and Words.” Python supplies these relational operators so you can test certain conditions with if statements. There are always two possibilities with the relational operators. Something is either less than something else, or it is not. Something is either greater than something else, or it is not. Something is either equal to something else, or it is not.

Tip

The two possibilities that the relational operators enable provide the means for duplicating the two-legged decision symbol in a flowchart. A decision symbol has two possible outcomes, and so does the if. if is either true or false.

Note

Most languages, like Python, allow for multiple if...else if...else if layers, but some also offer another way to handle several possible conditions or values to a single variable: the switch statement. The switch statement is not an option for Python, but you will encounter it in other languages, like C and JavaScript.

Looping Statements

Looping statements are another important feature of any programming language. Python supplies two statements that control loops. Your computer will never get bored. It will loop over and over, quickly repeating statements as long as you need it to.

Loops have many uses. You might need a loop to ask the user for several people’s data, to calculate a combined total, or to print several lines of data. Python’s two primary looping statements are:

Image for loops

Image while loops

The following sections describe these looping statements.

Using the for Loop

The for loop is actually a block of statements indented following the initial for statement. Before you look at a for loop, an analogy to things in everyday life might be helpful. As with if, a for loop is a natural way of expressing an idea. Consider the following description:

For each of today's invoices:
        check the accuracy of the invoice,
        add the total amount to the daily sales total.

You can sense from this description of invoice totaling that a repetitive process happens. If there are five invoices, the process repeats for each invoice.

The computer’s for loop works just like the for-each concept in the invoice description (that’s why it’s called for). To ease you into the use of for loops, Listing 6.3 shows a simple loop that explains the for statement.

LISTING 6.3 Use for to control a counting loop

# Filename: firstforloop.py

# A program that goes through the first 10 numbers and
# prints the number and the number times itself
for x in range(10):
    print(x, x*x)

Here is the output from the program in Listing 6.3:

0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81

The for statement can save a programmer time and effort by repeating a line or a block of code. The for statement in Python is a little different than the versions you see in other programming languages. In Python, you generally use the for statement to iterate (loop) through something. In this example, you are working through a set of numbers—specifically the numbers 0 through 9. As noted in the discussion of strings in the previous hour, your list of numbers starts with 0 and ends at 9, the last number before the 10 in the range() function. So the first time the loop runs, it assigns 0 to the variable x. It proceeds to the print() statement and prints both x (0) and x * x (also 0). As with the if statements earlier, Python considers any indented line of code part of the for loop. Once it reaches the last indented line (in this case, the only indented line), Python returns to the for statement and increments the variable x by 1. Once again, it proceeds to the print() statement and prints both x (1) and x * x (also 1). This continues until the last number in the loop that is less than the number specified in the range() function (10). (If you wanted to print up through 10, you’d have to put 11 in the range() function.) Python then departs the for loop.

Listing 6.4 shows a program that does exactly the same thing as Listing 6.3 but without using a for loop. You can see that the for loop makes repetitive statements much easier to code. (Consider how much easier it would be to use a for statement to print the numbers from 1 to 200 than to write 200 lines of code to print those numbers if you used the method in Listing 6.4.)

LISTING 6.4 Printing without a for loop gets tedious

# Filename: noforloop.py

# A program that prints the first 10 numbers
# and prints the number times itself, but
# doesn't use a for loop

x = 0
print(x, x*x)

x = 1
print(x, x*x)

x = 2
print(x, x*x)

x = 3
print(x, x*x)

x = 4
print(x, x*x)

x = 5
print(x, x*x)

x = 6
print(x, x*x)

x = 7
print(x, x*x)

x = 8
print(x, x*x)

x = 9
print(x, x*x)

You do not have to print the value of the loop variable the way it’s done in Listing 6.4; often, a loop variable just serves as a counter and is not printed at all.

Often, a for loop controls a set of statements, determining the number of times those statements repeat, without using the control variable for anything else. Listing 6.5, controlled by a for loop, prints a message 15 times.

LISTING 6.5 Printing a message several times in a loop is efficient

# Filename formessage.py

# Program that prints a message
# 15 times


for i in range (0,15,1):
    print("Happy birthday!")

Another example will make this clearer. Look at the program in Listing 6.6. A teacher might use it to print a grade sheet. The program asks the teacher how many test scores are to be entered. It uses that answer to loop through a series of statements, asking for the next child’s name and grade. As the teacher enters the data, the values are printed to the printer. At the end of the program, there is a complete listing of names and grades. (Later, in Listing 6.8, you will see how to program an accumulator to add all the grades together and to print a class average.)

LISTING 6.6 A teacher’s grade-printing program is easy to follow when you use a loop

# Filename gradingpapers.py

# Program asks how many students are in a class
# and then gets their names and grades


# Get the number of students in the class
students = int(input('How many students? '))

# Set up two lists
# One for names and one for grades
studentnames = []
studentscores = []

# Get the test scores for each student
for x in range (students):
    studentnames.append(input("Name: "))
    studentscores.append(int(input("What was their test score? ")))

# Print all the names and grades
for x in range (students):
    print(studentnames[x], "got a", studentscores[x])

Now after running the program, the user gets a prompt box, asking for a number of students in the class (for this example, 5 was entered). The program loops through a series of additional prompts, asking for name and grade of each student. After the data entry is complete, the following output appears (though yours will match the data you enter):

Andrew got a 87
Benjamin got a 88
Chris got a 91
Katie got a 86
Maddie got a 98

A quick note about the method of data collection used in this program: In the last lesson, you learned that a word or phrase is an array of characters. With Python, you have additional ways to collect similar data under a single name, including lists, sets, tuples, and dictionaries. The program in Listing 6.6 uses two lists: one for the names of the students (studentnames) and one for their test scores (studentscores). Lists come in handy when you need a collection of similar numbers, like grades in this program or monthly expense totals. You could obviously create a separate variable for each item, but one variable name with multiple numbered versions is much easier to handle, particularly if you face a larger set of data to collect. What if you had 5,000 customers and needed to keep a balance for each? Would you prefer to create 1 name with 5,000 copies or 5,000 different variables? The former, right? In Python, if you want to create a list of any type of data, you can create it with a statement such as:

studentnames = []

This sets up a list named studentnames. With nothing between the brackets, the set is currently empty. It will be filled later with input from the user. You could also fill the list when you define it by putting the items in between the brackets. For example, if you already knew the names of the students, you could use a statement like:

NewStudents = ['Anna', 'Thomas', 'Julian', 'Maria']

This would create a list of four students, with Anna being NewStudents[0], Thomas being NewStudents[1], Julian being NewStudents[2], and Maria being NewStudents[3]. Lists are extremely flexible: You can add or delete items as your needs change.

This program then creates a second list, one for the grades. The program then runs through two for loops, the first one to get the input and the second to print out the data. The two for statements show the use of the range() function, but instead of passing a specific number, you are passing a variable—the number of students the teacher entered. If the teacher has 5 students, the program loops 5 times. If the teacher inputs that there are 10 students, the program loops 10 times.

Another new function is used twice in the first for loop. When you create a new list, you need to use the append() function to add a new item to the end of the list. So in the new student list example, if you write the statement:

NewStudents.append('Hector')

the list now has a fifth element, with NewStudents[4] being equal to 'Hector'. There are a number of functions associated with lists that you can use to add, delete, copy, and sort lists. They cannot all be covered here, but if you’re interested, look for a more comprehensive Python reference.

With just six lines of Python, you’ve managed to create a pretty powerful piece of code. (The program is longer, but the rest of the lines are comments or blank lines for readability; you only had to write six lines of code.)

Controlling the for Loop

The range() function can be used in a variety of ways. In Listing 6.3, you saw it take a single number and count from 0 to right up to the top number by 1s. That’s a great technique, and many of your programs will be able to use it. But what if you didn’t want to start at 0? What if you wanted to count up by 2s or 5s? What if you wanted to count down? The range() function can do all of these types of counting; you just need to pass it three values instead of one:

range(a,b,c)

where:

a is the starting number

b is the ending number

c is the increment

So if you wanted to count from 25 to 100 by 5s, you would use this for statement:

for (x in range(25,100,5))

Or if you wanted to print the odd numbers between 1 and 100, you would use this for statement:

for (x in range (1,100,2))

You could even count down from 10 to 1 by using this for statement:

for(x in range(10,0,-1))

This last one is a little tricky at first, but it just tells you that if you start with your highest number and your ending number is smaller, you must use a negative number as the increment (which is then called a decrement).

Listing 6.7 shows a program that counts down from 10 to 1 and then prints Blast Off! at the end of the loop. To carry out the countdown, a negative value has to be used in the third part of the range() function. Each time through the loop, –1 is added to i to create the descending count.

LISTING 6.7 Counting down from 10 to 1 is simple with a for loop

# Filename countdown.py
# Program uses a for loop to
# count down instead of up


for i in range(10,0,-1):
    print(i,'...')
print("Blastoff!")

Here is the output from the program:

10...
9...
8...
7...
6...
5...
4...
3...
2...
1...
Blast Off!

The for loop offers a lot of loop control, but it is designed to count through the control loop’s value. You don’t have to increase or decrease your counter variable by 1 in the third part of the for loop. Finally, the last line of code executes when the for loop has completed, so you print 10 countdown numbers but print the Blast Off! message only once.

You can nest one loop inside another. Such nested constructs can seem rather advanced to beginning programmers, but the nested loops are simple to understand if you consider what happens when you need to perform a loop more than once. You could write the loop twice, back to back, or you could enclose the loop inside another loop that executes its body twice. Hour 9, “Programming Algorithms,” explains nested loops in more detail.

Not all loops can be determined by a counting variable. Sometimes you need loops that loop while a certain condition is true or until a certain condition is met. The loops described in the next section often prove more effective for such programming goals.

Using the while Loop

The while loop provides a way to control loops through a relational test. A loop’s relational test uses the same relational operators used with if statements. (Refer to Table 6.1 for a complete list of relational operators.)

Suppose the teacher with the grade-printing program doesn’t know exactly how many students took the test and doesn’t want to take the time to count them. Because the total number of tests must be specified to control the for loop properly, another method is required. Listing 6.8 shows the same program but controlled by a while loop. Notice that the while continues looping while a certain condition is true. The condition in this case is the teacher’s answer in response to having more tests to enter.

LISTING 6.8 You can control the grade program with a while loop

# Filename gradingpapers2.py

# Program uses a while loop to
# get students names and grades
# until the teacher is done

# Set up two lists
# One for names and one for grades
studentnames = []
studentscores = []

answer = 'Y'
students = 0
totalscore = 0

# Get the names and test scores for each student
while (answer == 'Y'):
    studentnames.append(input("Name: "))
    studentscores.append(int(input("What was their test score? ")))
    totalscore = totalscore + studentscores[students]
    students += 1
    answer = input("Do you have another score to enter (Y/N)? ")


# Print all the names and grades
for x in range (students):
    print(studentnames[x], "got a", studentscores[x])

print("The average score was %.1f." % (totalscore/students))

This program keeps looping until the teacher indicates that there are no more grades to enter. Notice that the while is followed by a relational test, the result of which (true or false) determines whether the loop repeats again or quits. So if the conditional statement is false the first time, the block of code does not run at all. In this program, we’ve guaranteed the code will run one time by setting the answer variable to 'Y' to trigger the first pass through the loop.

Note that this is a rather limited form of data entry as only a capital Y answer will continue the loop. If a teacher enters y or Yes or 1 more or anything other than Y, the test will return false, and the loop will end. (There are better ways to ensure that data entry is complete, but this is just a general method to introduce the concept to you.)

One added bonus to this program is the addition of a totalscore variable, which gets the value of all grades and then is divided by the number of students that took the test in order to get an average grade. It’s an extra piece of information your program calculates for the teacher to add some additional programming value.

Tip

When using a while loop, make sure that, somewhere in the block of code, you are altering the variable you are testing in the relational statement. Otherwise, you might get yourself caught in an infinite loop, and your program will not end.

Summary

Congratulations! You can now enter data into a Python program and format the resulting output. You have also mastered the true power of any programming language—looping. The programs you saw in this lesson are getting to be powerful, yet you have seen that programming is easy. You have learned how the relational operators are used with the if statement so that a Python program can make decisions based on the data. In addition, the looping constructs enable sections of your program to repeat as long as necessary.

The next hour shows you how to analyze your programs to locate errors that might appear in them. You’ll learn bug-catching secrets so that you can write more accurate programs more quickly.

Q&A

Q. Does it matter whether I select while or for statements when I’m writing loops?

A. Generally, for loops are useful when you must count values or iterate the loop’s body a specified number of times. The while loop is useful for iterating until or while a certain condition is met. If you are counting up or down, a for loop is easier to write and is slightly more efficient than an equivalent while loop. Ultimately, though, you can use whatever style of loop you prefer.

Q. How does if compare to for?

A. Both the if statement and the for statement, as well as the while statements, rely on conditional values to do their jobs. Nevertheless, an if statement is never considered to be a loop. Always keep in mind that an if statement executes its body of code at most one time—and possibly never if the if is false to begin with. Even if the if condition is true, the if statement never executes its body more than one time, whereas the looping statements can repeat their code bodies many times.

Workshop

The quiz questions are provided for your further understanding.

Quiz

1. How does a conditional operator differ from a mathematical operator?

2. What is a loop?

3. True or false: Code inside an if statement might never execute.

4. True or false: Code inside for loops always executes at least once.

5. How can you make a for loop count down?

6. How many times does the following for loop print?

for (i in range (2,19;3)):
   print i

7. Which loop, while or for, is best to use when you want to execute a loop a fixed number of times?

8. Where does the conditional appear in a while loop?

9. What function do you use to add a new element to a list?

10. What are the four techniques that Python uses to collect data under a single variable name?

Answers

1. A conditional operator tests how two values compare, whereas a mathematical operator calculates an answer based on values.

2. A loop is a set of instructions that repeat.

3. True. If the conditional tested by the if statement is false, the code inside the if statement is skipped.

4. False. If the for loop’s counter variable is already past the limit before the loop begins, the for loop does not execute, and control passes to the statement that follows the loop’s next statement.

5. Use a negative increment to make a for loop count down.

6. The loop executes six times.

7. Use the for loop when you want to execute a loop a fixed number of times.

8. The conditional appears after the while command.

9. append()

10. Lists, sets, tuples, and dictionaries

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset