Page 24 - MSDN Magazine, October 2019
P. 24

# While
count = 0
while count < 5:
print(“Hello”)
count = count + 1 else:
print(“Done saying hello”)
Spot the quirk? As you might infer, the “else” block gets executed after the while loop ceases looping, regardless of how many times the loop was actually executed. Even if the count variable had started at 6, the else block would’ve fired. This is something Python offers that no other mainstream language does, and it provides a useful way to provide cleanup or other sorts of behavior that should always be executed, regardless of what actually happens with the loop.
The for loop operates similarly, but operates against a sequence, so let’s start with a list, which fundamentally is an array, but is dynamically resizable:
# For
numbers = \[1, 2, 3, 5\] for n in numbers:
if n == 3: continue
print(n) else:
print(“3! From the Book of Armaments”)
As might be expected, this will recite King Arthur’s count down for the Holy Hand Grenade of Antioch.
Using a list might be acceptable for small numbers, but obvi- ously if you want to count up to 100, having to construct a list of 100 elements ahead of time would be impractical. In some other languages, you have a particular flavor of the for-loop construct to set a starting point, ending point and iteration, but remember, in Python, there’s only one way to do it. (On top of which, that three-part for-loop construct is pretty cumbersome when you look back on it.) For these scenarios, Python provides a function, called range, to provide a sequence of numbers suitable for use in a loop:
ns = range(0,100) for n in ns:
print(n)
As you might infer, the “else” block gets executed after the while loop ceases looping, regardless of how many times the loop was actually executed.
Regardless of the source of the iteration, the for-loop construct allows for manipulation of the loops via the break and continue key- words; the former arbitrarily exits the loop, and the latter causes the loop to begin again. Note as well that the range doesn’t have to start low and grow high; you can just as easily start with zero and “grow downward” by stepping by negative one each time, if so desired:
ns = range(0,-100,-1) for n in ns:
print(n)
For the most part, any experienced object-oriented developer familiar with the language constructs of Java, C#, C++ or any of their kin will find Python’s flow-control constructs to be easily digestible.
But the real power of the range function comes into play when you realize that the underlying construct that the for-loop is operating off of is a sequence: an object that knows how to produce the next value expected. Many people will assume that this is sim- ilar to the iterator object that’s frequently used as part of C# (the IEnumerator interface), but in fact, this is a little bit more powerful than that. If you were to print the returned object from the range function, what you’d see isn’t the full list of values, but the object itself; that is to say, this snippet of code:
ns = range(0,10) print(ns)
This code will print “range(0,10),” not “\[0,1,2,3,4,5,6,7,8,9\],” because no list has been constructed. The sequence object knows its lower range (0), its upper range (10), and how to produce each next successive value (add one to the current value) as requested, so it doesn’t need to construct the entire collection. This means the sequence object occupies the same amount of memory whether it’s a sequence from zero to 10 or from zero to 10 million. (This is often referred to as a “stream” in other languages.) Python makes use of sequences in a variety of ways throughout the platform, not just in for-loop constructs.
Exceptions
Finally, Python also supports exception-handling similar to the way C#, Java and C++ do: To signal an error condition that can be trapped and handled further up the call stack, Python allows you to “raise” an object instance (or a class, which Python will take to mean create an instance and then raise it) and immediately exit the current function, in the same way that you “throw” exceptions in C#:
Running this snippet will also demonstrate that the results of the range function are bottom-inclusive, top-exclusive (meaning you’d see zerio, but not 100). For ranges that want to “step” by more than one, you can construct the range to jump by a set value by passing a third parameter to the range:
ns = range(0,100, 5) for n in ns:
print(n)
This will print the values five, 10, 15 and so on.
raise Exception()
20 msdn magazine
The Working Programmer

































































   22   23   24   25   26