I’ve been working on a problem for a class that involves random number generation and returning a count for those divisible by 7 or 13. The function appears to work, or is at least returning the proper values along the steps. But, it returns a list for the count instead of a single value. What am I doing wrong? The requirements and my code so far are:
Develop and call a function that will:
- Generate a random number n with a value between 1 and 1,000.
- In the range of (n, n+200), iterate each number and count how many of them are divisible by 7 and how many of them are divisible by 13.
- Print out the result
import random
def randDiv():
n = random.randint(1, 1000)
randList=[]
for x in range(n, n+200):
if (x%7==0) or (x%13==0):
randList.append(str(x))
total = len(randList)
print(total)
randDiv()
Advertisement
Answer
You are printing the total in each iteration. You should print it after for loop.
import random
def randDiv():
n = random.randint(1, 1000)
randList=[]
for x in range(n, n+200):
if (x%7==0) or (x%13==0):
randList.append(x)
print(len(randList))
randDiv()