I have a piece of python code which I am generating 3 random integers between 0 and 100:
list1=random.sample(0, 100),3)
if sum(list1)=20:
print(list1)
else:
pass #do nothing
I want:
Can anybody help? My ideas so far are something to do with loop functions but don't know where to start.
list1=random.sample(0, 100),3)
while sum(list1) != 20:
list1=random.sample(0, 100),3)
print(list1)
Use a while loop:
while True:
list1=random.sample(0, 100),3)
if sum(list1)=20:
print(list1)
break
Doing something until something else happens is a while
-loop. Doing something a given number of times is a for
-loop.
Let's say you want 3 entries in your list. This is a for
-loop with a range of 3:
for i in range(3):
do_something()
You don't know, when the random sample will add-up to 20, so this is a while
-loop:
result = []
list1 = []
while sum(list1) != 20:
list1 = random.sample(range(100),3)
result.append(list1)
So putting that together will give:
result = []
for i in range(3):
list1 = []
while sum(list1) != 20:
list1 = random.sample(range(100),3)
result.append(list1)
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.