Question on Lesson 8


#1

On the lesson “For One And All,” I’ve passed the exercise but have a question about the code.

The right code is:

my_list = [1,9,3,8,5,7]

for number in my_list:
print 2 * number

Simple enough, but since “number” was never defined, how does Python know I mean “all the numbers in the list”? Is “number” some kind of universally recognized variable? Not sure why this is working. Thanks!


#2

But it was,

for number in my_list:

The definition is in the header line of the loop.


#3

It was defined but I still don’t understand how the program was able to calculate the values in the list, the list was titled “my_list” so how did the program know “number” meant each item in the list…


#4

By using a for construct with an in operator we can iterate over a list, one value at a time. number is an individual value referenced by a volatile variable.


from random import randint
>>> for i in range(11):
    j = i * 10
    k = (j + randint(0, 9)) % 10
    print (j + k)

    
3
19
24
30
44
53
62
75
81
99
102
>>> 

What we have effectively done is generate a random list of numbers, in a specified range for each. By using the initial range as a control then adding a random second digit.

The in operator did all the work on the loop. It selected one value from the range at a time and let the computation revolve around that value.


Even more succinctly,

>>> for i in range(11):
    print (i * 10 + randint(0, 9))

    
0
13
26
39
45
55
65
78
80
94
104
>>> 

>>> def place_values(x):
	for i in range(x):
		print (i * 10 + randint(0, 9))

		
>>> place_values(10)
1
14
27
38
46
55
61
78
80
98
>>> 

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.