HomePython Page 5 - Python 101 (part 3): A Twist In The Tail
Looping The Loop - Python
Find out more about adding flow control to your Python programswith the "for" and "while" loops, see how the range() function can be usedto generate number ranges, and learn all about list objects. And bring anold flame along for the ride.
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:
while (condition):
do this!
In English, this would roughly translate to
while (living with Mom and Dad):
curfew is 11 PM
while the Python equivalent would look like this
while (livingWithParents == 1):
curfew = 2300
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,
while (livingWithParents == 0): curfew = "Huh? What curfew?"
is a perfectly valid "while" loop.
Here's a simple example which demonstrates the "while" loop.
#!/usr/bin/python
# initialize a variable
response = ""
# while loop
while response != "y":
# keep asking the question
response = raw_input("Would you like to receive unsolicited
commercial email from people you don't know, advertising products you have
no interest in, on a regular basis (once every 15 minutes)? [y/n] ")
print "Thank you for your cooperation!"
And here's the output.
Would you like to receive unsolicited commercial email from people you
don't know, advertising products you have no interest in, on a regular
basis (once every 15 minutes)? [y/n] n
Would you like to receive unsolicted commerial email from people you don't
know, advertising products you have no interest in, on a regular basis
(once every 15 minutes)? [y/n] n
Would you like to receive unsolicted commerial email from people you don't
know, advertising products you have no interest in, on a regular basis
(once every 15 minutes)? [y/n] n
Would you like to receive unsolicted commerial email from people you don't
know, advertising products you have no interest in, on a regular basis
(once every 15 minutes)? [y/n] y
Thank you for your cooperation!
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:
#!/usr/bin/python
# initialize a variable
response = ""
# while loop
while response != "y":
# keep asking the question
response = raw_input("Would you like to receive unsolicited
commercial email from people you don't know, advertising products you have
no interest in, on
a regular basis (once every 15 minutes)? [y/n] ")
else:
print "Thank you for your cooperation!"
How about something a little more constructive?
#!/usr/bin/python
# get a number
num = input("Gimme a number: ")
# assign the number to a "temp" variable
tmpnum = num
factorial = 1
# calculate the factorial
while (num != 1):
factorial = factorial * num
num = num - 1
print "The factorial of", tmpnum, "is", factorial
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:
Gimme a number: 7
The factorial of 7 is 5040
And if you have a calculator handy, you'll see that
7*6*5*4*3*2*1 = 5040
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.