简体   繁体   中英

How do I repeat/loop code so that it runs multiples until I ask it to stop?

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:

  1. The sum of the three generated numbers to equate to 20 and if it doesn't equal 20 to then repeat the code again until it comes up with 3 numbers that do equal 20.
  2. To keep doing this repeat N number of times so it has generated multiple lists that add up to 20.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM