Home > Enterprise >  How do I end a while True: loop once all possibilities have been printed?
How do I end a while True: loop once all possibilities have been printed?

Time:12-23

How do I end the loop once all possibilities have been printed?

Sorry if the question is formatted in a bad/annoying way, I'm new so just bear with me.

import random
while True:
    comb = random.randint(0,100)
    print(comb)

CodePudding user response:

By all possibilities I assume you want to stop once all numbers between [0, 100) have been printed randomly. In this case, you'd need to keep track of which numbers have been printed so far and break only once you've printed all 100 different values.

import random
vals_so_far = set()
while True:
    comb = random.randint(0, 100)
    print(comb)
    vals_so_far.add(comb)
    if len(vals_so_far) == 101:
        break
 

CodePudding user response:

I could've just done this:

for i in range (1,101):
    print (i)

CodePudding user response:

You would have to keep track of the results, and ensure all of them have been printed. If it is enough to just print the uniquely found values as they are found:

import random

comb_values = {}
while len(comb_values) < 101:
    comb = random.randint(0,100)
    print(comb)
    comb_values[comb] = ""

print(len(comb_values))

I used a dict called comb_values because it only permits unique values. Once you've got 101 unique values, you have found every number within the range. You could also do something like increment the value inside the dict to figure out how many times each value was found.

CodePudding user response:

Here I think I have a solution:

import random

comb_set = set()
run = True

while run:
    comb = random.randint(0,100)
    print(comb)
    comb_set.add(comb)
    if len(comb_set) == 100:
        run = False
    

    

CodePudding user response:

I personally wouldn't (I would add a condition on the loop), but if you simply add a break statement it will do so.

import random
while True:
    comb = random.randint(0,100)
    print(comb)
    break

https://docs.python.org/3/tutorial/controlflow.html

This will just print one random number and stop.

  • Related