Home > front end >  Having an issue printing my For loop results into a single list
Having an issue printing my For loop results into a single list

Time:07-09

I need to create a function that prints a list of numbers between 1k and 5k that is divisible by x and x 5 with no remainder. When I run my code with x= 100 for example I get: [2100] [2100,4200] when my answer should just be [2100,4200]. if I move the print outside of the function itself I get NONE. Still new to python, I feel like I'm missing something so simple

def inrange(x):
  list= []
  for i in range(1000,5001):
    if i%x == 0 and i%(x 5) == 0:
      list.append(i)
      print(list)
    else:
      continue
      
inrange(100)

CodePudding user response:

Remove the print statement from the for-loop and just return the list at the end:

def inrange(x):
  list= []
  for i in range(1000,5001):
    if i%x == 0 and i%(x 5) == 0:
      list.append(i)
     
    else:
      continue

  return list
      

print(inrange(100))

CodePudding user response:

The reason its printing twice is because it prints everytime you append something to the list. So just move the print statement to outside the loop like below:

def inrange(x):
  list= []
  for i in range(1000,5001):
    if i%x == 0 and i%(x 5) == 0:
      list.append(i)
  
    else:
      continue


  return list

print(inrange(100)) 
  • Related