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

The code for that might look something like this:

def numwords(s):

list = split(s) # list with each element a word return len(list) # return number of elements in list

for line in file:

total = total + numwords(line) # accumulate totals for each line print "File had %d words" % total

Now if you tried it, you'll know that it didn't work. What I've done is a common design technique which is to sketch out how I think the code should look but not bothered to use the absolutely correct code. This is sometimes known as Pseudo Code or in a slightly more formal style Program Description Language (PDL).

Once we've had a closer look at file and string handling, a little later in the course, we'll come back to this example and do it for real.

Tcl Functions

We can also create functions in Tcl, of course, and we do so using the proc command, like so:

proc times {m} {

for {set i 1} {$i <= 12} {incr i} { lappend results [expr $i * $m]

}

return $results

}

Note that by using the Tcl lappend list command I automatically create a list called results and start adding elements to it.

A Word of Caution

Tcl is a little different in the way it deals with functions. In fact you may have noticed that I have been calling the builtin Tcl functions commands. That's because in Tcl every command you type at the Tcl prompt is actually a function call. Most languages come with a set of keywords like for, while, if/else and so on. Tcl makes all of these control keywords commands or functions. This has the interesting, confusing and very powerful effect of allowing us to redefine builtin control structures like this:

set i 3

while {$i < 10} { puts $i

set i [expr $i + 1]

}

As expected this prints out the numbers from 3 to 9 (1 less than 10). But let's now define our own version of the while command:

proc while {x y} { puts "My while now"

}

set i 3

while {$i < 10} { puts $i

set i [expr $i + 1]

}

59