Thread: Perfect Python
View Single Post
Old Jan 5th, 2007, 5:04 AM   #30
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
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:
python Syntax (Toggle Plain Text)
  1. from datetime import datetime
  2.  
  3. while user_input != "q":
  4. print "The date and time is %s" % datetime.now()
  5.  
  6. print "Type in 'q' to quit, or press enter to print the date again."
  7.  
  8. 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:
python Syntax (Toggle Plain Text)
  1. numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  2.  
  3. print "The 7 times table: "
  4.  
  5. for number in numbers:
  6. 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:
python Syntax (Toggle Plain Text)
  1. >>> range(10)
  2. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  3. >>> range(1, 10)
  4. [1, 2, 3, 4, 5, 6, 7, 8, 9]
  5. >>> range(1, 11)
  6. [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.
Arevos is offline   Reply With Quote