For school we have to make a code which shows the average of a certain list into another list but for some reason my list which should show the smaller numbers is empty, I don’t know if it is possible but I tried using an extra variable which counts +1 to itself
from random import randint
kleiner = []
list = []
teller = 0
aantal = int(input("Hoeveel random getallen wilt u? "))
veelvoud = int(input("Welke veelvoud? "))
while len(list) < aantal:
getal = randint(1, 100)
if getal % veelvoud == 0:
list.append(getal)
gemiddelde = sum(list) / len(list)
while len(list) < aantal:
if list[teller] < gemiddelde:
kleiner.append(list[teller])
teller += 1
print(list)
print(list[::-1])
print(kleiner)
help is appreciated in advance.
Advertisement
Answer
2 things:
- don’t name a variable
listaslistis also a python type - the second
whileloop causes the issue, as the length of the list is by default equal toaantalas the list has already been created. So whatever is in the while loop is never executed. Rather you could just iterate over the list in a simple for loop
That makes:
from random import randint
kleiner = []
list_ = []
teller = 0
aantal = int(input("Hoeveel random getallen wilt u? "))
veelvoud = int(input("Welke veelvoud? "))
while len(list_) < aantal:
getal = randint(1, 100)
if getal % veelvoud == 0:
list_.append(getal)
gemiddelde = sum(list_) / len(list_)
for i in list_:
if i < gemiddelde:
kleiner.append(i)
print(list_)
print(list_[::-1])
print(kleiner)