For those of you unfamiliar with the term, a "loop" is a programmingconstruct that allows you to execute a set of statements over and overagain, until a pre-defined condition is met. It's one of the most basicconstructs available in a programming language, and comes in handy when youneed to perform a repetitive task over and over again. Unlike its counterparts, which offer a variety of different loop variants,Python keeps things simple with only two types of loops: the "while" loopand the "for" loop. The former is simpler to read and understand, and itusually looks like this: In English, this would roughly translate to while the Python equivalent would look like this As with conditional statements, so long as the specified condition remainstrue, the indented code block will continue to execute. However, as soon asthe condition becomes false - you move out and get your own place, say -the loop will be broken and the indented statements will stop executing. You'll notice that Python uses indentation to decide which statementsbelong to the "while" block - you probably remember this from last time. Aswith the "if" statement, if the code block consists of only a singlestatement, Python allows you to place it on the same line as the "while"statement. For example, is a perfectly valid "while" loop. Here's a simple example which demonstrates the "while" loop. And here's the output. Python allows you to add an "else" clause to your "while" loop as well;this clause is executed if the loop is executed without encountering asingle "break" statement (more on this later.) Consequently, the example above could be rewritten to read: How about something a little more constructive? In case you flunked math class, the factorial of a number X is the productof all the numbers between 1 and X. And here's what the output looks like: And if you have a calculator handy, you'll see that Once the user enters a number, a "while" loop is used to calculate theproduct of that number and the variable "factorial" (initialized to 1) -this value is again stored in the variable "factorial". Next, the number isreduced by 1, and the process is repeated, until the number becomes equalto 1. At this stage, the value of "factorial" is printed.
blog comments powered by Disqus |