Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Gauld A.Learning to program (Python)_1.pdf
Скачиваний:
23
Добавлен:
23.08.2013
Размер:
1.34 Mб
Скачать

Case statements

A sequence of nested if/else/if/else... is such a common construction that many languages provide a special type of branch for it. This is often referred to as a Case or Switch statement and the Tcl version looks like:

switch $width {

100 { set area 0}

200 { set length [expr {$length * 2}] } 500 { set width [expr {$width / 2}] }

}

Modern BASICs have a version too:

SELECT CASE width

CASE 100

LET area = 0

CASE 200

LET length = length * 2

CASE 500

LET width = width / 2

ELSE PRINT "Width not recognised"

END SELECT

Python does not provide an explicit case construct but rather compromises by providing an easier if/elseif/else format:

if width < 100: area = 0

elif width < 200: length = length * 2

elif width < 500: width = width/10

else:

print "width is too big!"

Note the use of elif and the fact that the indentation (all important in Python) does not change. It's also worth pointing out that both this version and the earlier Python example of this program are equally valid, the second is just a little easier to read if there are many tests.

BASIC also provides a slightly more cumbersome version of this technique with ElseIf...THEN which is used in exactly the same way as the Python elif but is rarely seen since CASE is easier to use.

Things to Remember

Use if/else to branch

The else is optional

Multiple decisions can be represented using a CASE or if/elif construct

Boolean expressions return true or false

53