Exercise 32
Code
the_count = [1, 2, 3, 4, 5]fruits = [' apples ', ' oranges ', ' Pears ', ' apricots ']change = [1, ' pennies ', 2, "dimes ', 3, ' quarters ']# this first kind of for-loop goes through a listfor number in the_count: print "this is count %d" % Number # same as abovefor fruit in fruits: print "a fruit of type: %s" % fruit # also we can go through mixed lists too# notice we have to use %r since we don ' T know what ' s in it for i in change: print "I got %r" % i # we can also build lists, first start with an empty one elements = []# then use the range function to do 0 to 5 countsfor i in Range (0,6): print "Adding %d to the list." % i # append is a function that lists understand elements.append (i) # now we can print them out toofor i in elements: print "element was: %d" % i
Output
Notes:
①range (start,end) returns an integer sequence, ranging from start to end-1
>>> Range (0.6) [0, 1, 2, 3, 4, 5]
②for...in ... Iterative loops apply to sequence types such as strings, lists, and so on
③ sequences can be connected by a plus sign to form a new sequence
>>> elements = []>>> elements + range (0,6) [0, 1, 2, 3, 4, 5]
Exercise 33
Code
i = 0numbers = []while i < 6:print "at the top I am%d"% i numbers.append (i) i = i + 1 print "Numbe RS Now: ", numbers print" At the bottom I was%d "% i print" The numbers: "For num in Numbers:print num
Output
Notes:
①while determines whether the loop continues by checking the true and false of the Boolean expression. Unless necessary, to minimize the use of while-loop, in most cases for-loop is a better choice; use While-loop when checking for changes in Boolean expressions to ensure that they eventually become false unless you want an infinite loop
② Plus points exercise a code rewrite
Code
i = 0numbers = []def numbers_list (x): Global numbers, I and I < X:print "at the top I am%d"% i Numbers.append (i) i = i + 1 print "Numbers now:", numbers print "At the bottom I was%d"% i Numbers_list (7) print "The numbers:" For num in Numbers:print num
Output
PS: The function should pay attention to the problem of local variables and global variables.
③ Plus points exercise two code rewriting
Code
i = 0numbers = []def numbers_list (x, y): global numbers, I and I < X:print "at the top I am%d"% i Numbers.append (i) i = i + y print "numbers now:", numbers print "At the bottom I was%d" % i numbers_list (7, 3) print "The numbers:" For num in Numbers:print num
Output
Exercise 34
This section has no code, the main practice list of the slice, ordinal and cardinality problems
Practice:
The animal at 1 are the 2nd animal and is a python. The 3rd animal is at 2 and is a peocock. The 1st animal are at 0 and are a bear. The animal at 3 are the 4th animal and is a kanaroo. The 5th animal is at 4 and is a whale. The animal at 2 are the 3rd animal and is a peocock. The 6th animal is at 5 and is a platypus. The animal at 4 are the 5th and is a whale.
Stupid methodology Python,lesson 32-lesson