RhinoPython Primer

Page 31

5.2 Looping Executing certain lines of code more than once is called looping in programming slang. There are two types of loops; conditional and incremental which can be described respectively as: Keep adding milk until the dough is kneadable Add five spoons of cinnamon

Conditional loops will keep repeating until some condition is met where as incremental loops will run a predefined number of times. Life isn't as simple as that though, and there are many different syntax specifications for loops in Python, we'll only discuss the two most important ones in depth.

5.3 Conditional loops Sometimes we do not know how many iterations we will need in advance, so we need a loop which is potentially capable of running an infinite number of times. This type is called a Do‌Loop. In the most basic form it looks like this: 1 2 3 4

while (something is true): DoSomething() if (condition is met): break

All the lines indented after the while keyword will be repeated until we abort the loop ourselves. If we do not abort the loop, I.e. if we omit the break statement or if our condition just never happens to be met, the loop will continue forever. This sounds like an easy problem to avoid but it is in fact a very common bug. In Python it does not signify the end of the world to have a truly infinite loop. The following example script contains an endless While...Loop which can only be cancelled by shutting down the application. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

import rhinoscriptsyntax as rs import datetime as dt def viewportclock(): now = dt.datetime.now() textobject_id = rs.AddText(str(now), (0,0,0), 20) if textobject_id is None: return while True: rs.Sleep(1000) now = dt.datetime.now() rs.TextObjectText(str(textobject_id), now) if __name__=="__main__": viewportclock() Rhino Viewport

Here's how it works:

27


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.