|
Programming Guru
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 
|
Loops are used for repeating blocks of code. There are two basic types of loops; while loops, which keep repeating until a condition is met, and for loops, which repeat for each item in a list.
Here's an example of a "while" loop:
from datetime import datetime while user_input != "q": print "The date and time is %s" % datetime.now() print "Type in 'q' to quit, or press enter to print the date again." user_input = raw_input()
The while loop will keep repeating the date and time until the user types in "q".
And here's an example of a "for" loop:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print "The 7 times table: " for number in numbers: print "%d times 7 is %d" % (number, number * 7)
The for loop will output the 7 times table, without you having to type every line. You can also use the "range" function to return a list of numbers:
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1, 10) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
When given one number N, the sequence range returns is 0 <= x < N. When given two numbers N and M, the range is N <= x < M.
It's a little counter intuitive, but there are a few good reasons for not including the last number.
|