HomePython Page 7 - Python 101 (part 3): A Twist In The Tail
Within Range() - 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.
While on the topic of the "for" loop, it's worth mentioning the range()function, a built-in Python function whose sole raison d'etre is to returna range of numbers, given a starting and ending point. This range is alwaysreturned as a list - and as you'll see, this can combine quite effectivelywith the "for" loop in certain situations.
What does this have to do with anything? Well, the range() function, incombination with the "for" loop, can come in handy when you need to performa series of actions a specified number of times,
>>> for x in range(1,12):
... print "It is now", x, "o'clock"
It is now 1 o'clock
It is now 2 o'clock
It is now 3 o'clock
It is now 4 o'clock
It is now 5 o'clock
It is now 6 o'clock
It is now 7 o'clock
It is now 8 o'clock
It is now 9 o'clock
It is now 10 o'clock
It is now 11 o'clock
or to generate indices (corresponding to list elements) in a "for" loop.
# get a number
num = input("Gimme a number: ")
# for loop
for count in range(2,num):
# if factor exists, num cannot be prime!
if num % count == 0:
print num, "is not a prime number."
# if we get this far, num is prime!
print num, "is a prime number."
This is a simple piece of code to test whether or not a number is prime. A"for" loop is used, in conjunction with the range() function, to divide theuser-specified number (num) by all numbers within the range 2 to (num). Ifno factors are found, it implies that the number is a prime number.
Here's what it looks like:
Gimme a number: 23
23 is a prime number.
Gimme a number: 45
45 is not a prime number.
Gimme a number: 11
11 is a prime number.
Gimme a number: 111
111 is not a prime number.
As with the "while" loop, Python allows you to add an "else" clause to a"for" loop; it is executed only if the loop is completed withoutencountering a "break" statement even once.