For loop, definite vs indefinite iteration, range, random
For Loop used in situations where the programmer knows exactly how many times to repeat a Python for loop is an example of a definite iteration (vs. indefinite iteration) the easiest way to construct a for loop is with the range function for i in range(10) : # count from 0 to 9 print i # print from 0 to 9
For n in range(r) When used in a for loop, the range(x) function will execute x times but the counting starts at 0 and ends at x -1 (for example, if x is 3, then 0, 1, 2) 0, 1, 2, 3, … x -1 for i in range(10) : # count from 0 to 9 print i + 1 # print from 1 to 10
Indefinite vs. Definite Iteration Compare an indefinite loop to a definite loop Indefinite loop Definite loop name = raw_input(“Name : ") while (name <> "") : print name print "Done" m = input(“Max : ") for x in range(m) : print x + 1
Range Parameters Using range(); returns a list of integers range() can take additional arguments; range(start, stop, step) Examples of Range Result range(4) [0, 1, 2, 3] range(1, 5) [1, 2, 3, 4] range(0, 15, 3) [0, 3, 6, 9, 12] range(7, 0, -1) [7, 6, 5, 4, 3, 2, 1]
Convert Decimal to Binary the text book version (Unit 3) appears to have some “bugs” I have provided an alternate version of the pseudocode as well, note the algorithm only works with numbers within range(255); 0, 1, … 255
Algorithm to convert Some adjustments in the right panel makes the algorithm different from the text (Unit 3) Convert Decimal -> Binary Algorithm From Textbook Suggested Algorithm read num for positions p from 7, 6, . . . 0, do this: if num ≤ 2p, then set binary to “0” + binary otherwise, set binary to “1” + binary set num to num – 2p write binary read num between 0 & 255 if num < 2p, then set binary to binary + “0” set binary to binary + “1”
Python implementation # Convert Decimal input to Binary import math binary = "" n = input("number n (0 .. 255) :") if (n >= 0 and n <= 255) : for p in range(7, -1, -1) : if (n < math.pow(2, p)) : binary = binary + '0' else : binary = binary + '1' n = n - math.pow(2, p) print binary
Random Numbers Python has a “random number” module; used to generate random numbers ref : http://docs.python.org/library/random.html randint(a, b) can be used to generate a random integer between a & b; a <= N <= b
Use randint Import the random module Call the randint() function within limits a & b import random print random.randint(0, 10)
Random sequence The random module will generate a sequence of random numbers; if for example, randint is call more than once The sequence will be the same, unless seed is called import random random.seed() print random.randint(0, 10) print random.randint(0, 10)