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.
2 things:
list
as list
is also a builtin python functionwhile
loop causes the issue, as the length of the list is by default equal to aantal
as 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 loopThat 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)
Once you have the average (gemiddelde), you can build the resulting list using a list comprehension:
kleiner = [n for n in list_ if n < gemiddelde ]
If you want a list of random numbers that are a multiple of veelvoud <= 100, you can get that using the choices() function:
list_ = random.choices(range(velvoud,100,velvoud), k=aantal)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.