Let's go through your code line-for-line
import random
for x in range(1,100): # this will go 1, 2, ... , 99
q = random.randint(0, 99) # q is a random number 0-99
w = random.randint(0, 99) # w is a random number 0-99
e = q * w # e is q times w
q = [] # q is now an empty list
print '%s * %s = %s' % (q,w,e)
# q is an empty list, so this is wrong
Obviously you're not trying to assign q
to an empty list each time. You need to make a list BEFORE the loop, then keep adding to it.
some_list = [] # some_list is an empty list
for _ in range(99): # this will go 0, 1, ... , 98
q = random.randint(0, 99) # q is a random number 0-99
w = random.randint(0, 99) # w is a random number 0-99
e = q * w # e is q times w
some_list.append(e) # add e to the list!
print "%s * %s = %s" % (q,w,e)
# print "q * w = e"
Note that when you get a bit more advanced, you can wrap this up nicely as a list comprehension so you don't have to initialize it empty then add to it.
some_list = [random.randint(0,99) * random.randint(0,99) for _ in range(99)]
# equivalent to your code
But this is still a bit past your comfort level. One step at a time! :)
Things to note here that I changed:
range
is a half-open range, e.g. range(1,100)
is 99 numbers, 1-99
. It does not include 100.
- You don't actually USE any of the numbers in your range, you just want to run your loop that many times. The common idiom for this is
for _ in range(some_number)
. You use an underscore (_
) to represent to other coders that you don't use the variable here (note that _
does not represent anything special to Python, it's just convention)
for _ in range(N)
is a quick way to do something N
times.
list.append
adds to a list =)