The for and while Loops
Ifyou need to do something repeatedly like printing the value of ten different variables, you are doing yourself a big favor by not copy/pasting the print statement ten times. Instead, use a forloop to do the work for you. forloops iterate over the items of a sequence like a list, a tuple, or a string (remember, strings are sequences of characters). As an introductory example, let’s create a forloop that takes each element of the currencieslist, assigns it to the variable currencyand prints it—one after another until there are no moreelements in the list:
In[89]:currencies=["USD","HKD","AUD"]forcurrencyincurrencies:print(currency)USD
HKD
AUD
As a side note, VBA’s For Eachstatement is close to how Python’s forloop works. The previous example could be written like this in VBA:
DimcurrenciesAsVariantDimcurrAsVariant'currency is a reserved word in VBAcurrencies=Array("USD","HKD","AUD")ForEachcurrIncurrenciesDebugPrintcurrNext
In Python, if you need a counter variable in a forloop, the rangeor enumeratebuilt-ins can help you with that. Let’s first look at range, which provides a sequence of numbers: you call it by either providing a single stopargument or by providing a startand stopargument, with an optional stepargument. Like with slicing, startis inclusive, stopis exclusive, and stepdetermines the step size, with 1being the default:
range(stop)range(start,stop,step)
rangeevaluates lazily, which means that without explicitly asking for it, you won’t see the sequence it generates:
In[90]:range(5)Out[90]: range(0, 5)
Converting the range to a list solves this issue:
In[91]:list(range(5))# stop argumentOut[91]: [0, 1, 2, 3, 4]In[92]:list(range(2,5,2))# start, stop, step argumentsOut[92]: [2, 4]
Most of the time, there’s no need to wrap rangewith a list, though:
In[93]:foriinrange(3):print(i)
|