[Tutor] Newbie Anxiety

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Thu Nov 10 23:50:16 CET 2005


Terry Kemmerer 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.)

You need to choose the appropriate control structure. In this case you
need an infinite loop, which in Python is written as:

while True:
    # do stuff...

Also, in Python you need to explicitly give x its initial value:

x = 0

In Python 'x = x + 1' can be written shorter as 'x += 1' (though 'x = x
+ 1') works too.

All together:

x = 0
while True:
    x += 1
    print x

HTH

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven



More information about the Tutor mailing list