[Tutor] Newbie Anxiety
John Fouhy
john at fouhy.net
Thu Nov 10 23:49:37 CET 2005
On 11/11/05, Terry Kemmerer <wildcard2005 at comcast.net> wrote:
> I'm working on Ch. 5, "Fruitful Functions", or "How To Think Like A
> Computer Scientist" and I still can't count.
> (Don't laugh! I can't play the violin either...)
>
> In Basic, I would have said:
>
> 10 x = x + 1 : print x : goto 10
>
> run
> 1
> 2
> 3
> etc....
>
> How is this done in Python? (So I can stop holding my breath as I study
> this great language....and relax.)
Hi Terry,
There's a couple of options.
First, we could do it with a while loop. This is not the best or the
most idiomatic way, but it's probably most similar to what you've seen
before.
#### count forever
i = 0
while True:
print i
i = i + 1
####
Of course, we generally don't want to keep counting forever. Maybe
we'll count up to 9.
#### count to 9
i = 0
while i < 10::
print i
i = i + 1
####
A while loop contains an implicit "GOTO start" at the end. At the
start, it checks the condition, and breaks out of the loop if the
condition is false.
Like i said, though, this is not idiomatic Python. Python has for
loops which are based around the idea of iterating over a sequence.
So, we could count to 9 like this:
#### count to 9
for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
print i
####
The loop will go through the list, assigning each item to i in turn,
until the list is exhausted. The range() function is useful for
building lists like that, so we don't have to type it out manually.
#### count to 9
for i in range(10):
print i
####
And, of course, once we've got range(), we can give it a variable
limit (eg, n = 10; range(n)). Iteration is the key to doing all kinds
of funky stuff in python (including new ideas like geneartor
functions), so it's good to get the hang of :-)
--
John.
More information about the Tutor
mailing list