Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Introduction to Python for Science 2013.pdf
Скачиваний:
60
Добавлен:
21.05.2015
Размер:
2.41 Mб
Скачать

CHAPTER

SIX

CONDITIONALS AND LOOPS

Computer programs are useful for performing repetitive tasks. Without complaining, getting bored, or growing tired, they can repetitively perform the same calculations with minor, but important, variations over and over again. Humans share with computers none of these qualities. And so we humans employ computers to perform the massive repetitive tasks we would rather avoid. However, we need efficient ways of telling the computer to do these repetitive tasks; we don’t want to have stop to tell the computer each time it finishes one iteration of a task to do the task again, but for a slightly different case. We want to tell it once, “Do this task 1000 times with slightly different conditions and report back to me when you are done.” This is what loops were made for.

In the course of doing these repetitive tasks, computers often need to make decisions. In general, we don’t want the computer to stop and ask us what it should do if a certain result is obtained from its calculations. We might prefer to say, “Look, if you get result A during your calculations, do this, otherwise, do this other thing.” That is, we often want to tell the computer ahead of time what to do if it encounters different situations. This is what conditionals were made for.

Conditionals and loops control the flow of a program. They are essential to performing virtually any significant computational task. Python, like most computer languages, provides a variety of ways of implementing loops and conditionals.

6.1 Conditionals

Conditional statements allow a computer program to take different actions based on whether some condition, or set of conditions is true or false. In this way, the programmer can control the flow of a program.

99

Introduction to Python for Science, Release 0.9.23

6.1.1 if, elif, and else statements

The if, elif, and else statements are used to define conditionals in Python. We illustrate their use with a few examples.

if-elif-else example

Suppose we want to know if the solutions to the quadratic equation

ax2 + bx + c = 0

are real, imaginary, or complex for a given set of coefficients a, b, and c. Of course, the answer to that question depends on the value of the discriminant d = b2 4ac. The solutions are real if d 0, imaginary if b = 0 and d < 0, and complex if b 6= 0 and d < 0. The program below implements the above logic in a Python program.

1 a = float(raw_input("What is the coefficients a? "))

2b = float(raw_input("What is the coefficients b? "))

3c = float(raw_input("What is the coefficients c? "))

4

5d = b*b - 4.*a*c

6

7if d >= 0.0:

8

print("Solutions are real")

# block 1

9elif b == 0.0:

10

print("Solutions are imaginary")

# block 2

11

else:

 

12

13

print("Solutions are complex")

# block 3

14print("Finished!")

After getting the inputs of from the user, the program evaluates the discriminant d. The code d >= 0.0 has a boolean truth value of either True or False depending on whether or not d 0. You can check this out in the interactive IPython shell by typing the following set of commands

In [2]: d = 5

In [3]: d >= 2 Out[3]: True

In [4]: d >= 7 Out[4]: False

100

Chapter 6. Conditionals and Loops

Introduction to Python for Science, Release 0.9.23

Therefore, the if statement in line 7 is simply testing to see if the statement d >= 0.0 if True or False. If the statement is True, Python executes the indented block of statements following the if statement. In this case, there is only one line in indented block. Once it executes this statement, Python skips past the elif and else blocks and executes the print("Finished!") statement.

If the if statement in line 7 is False, Python skips the indented block directly below the if statement and executes the elif statement. If the condition b == 0.0 is True, it executes the indented block immediately below the elif statement and then skips the else statement and the indented block below it. It then executes the print("Finished!") statement.

Finally, if the elif statement is False, Python skips to the else statement and executes the block immediately below the else statement. Once finished with that indented block, it then executes the print("Finished!") statement.

As you can see, each time a False result is obtained in an if or elif statement, Python skips the indented code block associated with that statement and drops down to the next conditional statement, that is, the next elif or else. A flowchart of the if-elif-else code is shown below.

 

start

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

if

d≥0?

 

 

 

 

 

block 1

True

 

 

 

 

 

 

 

 

 

 

False

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

elif

b=0?

 

 

block 2

 

 

True

 

 

 

 

 

 

 

 

 

 

 

False

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

else

block 3

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

finish

Figure 6.1: Flowchart for if-elif-else code.

At the outset of this problem we stated that the solutions to the quadratic equation are imaginary only if b = 0 and d < 0. In the elif b == 0.0 statement on line 9,

6.1. Conditionals

101

Introduction to Python for Science, Release 0.9.23

however, we only check to see if b = 0. The reason that we don’t have to check if d < 0 is that the elif statement is executed only if the condition if d >= 0.0 on line 7 is False. Similarly, we don’t have to check if if b = 0 and d < 0 for the final else statement because this part of the if, elif, and else block will only be executed if the preceding if and elif statements are False. This illustrates a key feature of the if, elif, and else statements: these statements are executed sequentially until one of the if or elif statements is found to be True. Therefore, Python reaches an elif or else statement only if all the preceding if and elif statements are False.

The if-elif-else logical structure can accomodate as many elif blocks as desired. This allows you to set up logic with more than the three possible outcomes illustrated in the example above. When designing the logical structure you should keep in mind that once Python finds a true condition, it skips all subsequent elif and else statements in a given if, elif, and else block, irrespective of their truth values.

if-else example

You will often run into situations where you simply want the program to execute one of two possible blocks based on the outcome of an if statement. In this case, the elif block is omitted and you simply use an if-else structure. The following program testing whether an integer is even or odd provides a simple example.

a = int(raw_input("Please input an integer: ")) if a%2 == 0:

print("{0:0d} is an even number.".format(a)) else:

print("{0:0d} is an odd number.".format(a))

The flowchart below shows the logical structure of an if-else structure.

if example

The simplest logical structure you can make is a simple if statement, which executes a block of code if some condition is met but otherwise does nothing. The program below, which takes the absolute value of a number, provides a simple example of such a case.

a = eval(raw_input("Please input a number: ")) if a < 0:

a = -a

print("The absolute value is {0}".format(a))

102

Chapter 6. Conditionals and Loops

Introduction to Python for Science, Release 0.9.23

 

start

 

 

 

 

 

 

 

 

 

 

 

if

d≥0?

 

 

block 1

True

 

 

 

 

 

 

 

False

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

else

block 2

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

finish

Figure 6.2: Flowchart for if-else code.

When the block of code in an if or elif statement is only one line long, you can write it on the same line as the if or elif statement. For example, the above code can be written as follows.

a = eval(raw_input("Please input a number: ")) if a < 0: a = -a

print("The absolute value is {0}".format(a))

This works exactly as the preceding code. Note, however, that if the block of code associated with an if or elif statement is more than one line long, the entire block of code should be written as indented text below the if or elif statement.

The flowchart below shows the logical structure of a simple if structure.

 

start

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

if

d≥0?

 

 

block 1

True

 

 

 

 

 

 

 

 

 

 

False

finish

Figure 6.3: Flowchart for if code.

6.1. Conditionals

103

Introduction to Python for Science, Release 0.9.23

6.1.2 Logical operators

It is important to understand that “==” in Python is not the same as “=”. The operator “=” is the assignment operator: d = 5 assigns the value of 5 to the valiable d. On the other hand “==” is the logical equals operator and d == 5 is a logical truth statement. It tells Python to check to see if d is equal to 5 or not, and assigns a value of True or False to the statement d == 5 depending on whether or not d is equal to 5. The table below summarizes the various logical operators available in Python.

operator

function

<

less than

<=

less than or equal to

>

greater than

>=

greater than or equal to

==

equal

!=

not equal

and

both must be true

or

one or both must be true

not

reverses the truth value

Logical operators in Python

The table above list three logical operators, and, or, and not, that we haven’t encountered before. There are useful for combining different logical conditions. For example, suppose you want to check if a > 2 and b < 10 simultaneously. To do so, you would write a>2 and b<10. The code below illustrates the use of the logical operators and, or, and not.

In [5]: a = 5

 

In [6]: b = 10

 

In [7]: a != 5

# a is not equal to 5

Out[7]: False

 

In [8]: a>2 and b<20

 

Out[8]: True

 

In [9]: a>2 and b>10

 

Out[9]: False

 

In [10]: a>2 or b>10

 

Out[10]: True

 

104

Chapter 6. Conditionals and Loops

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]