'Loop through a tuple and printing each loop

I'm randomly generating a tuple from a dictionary. I want to run this a random number of times, and each run should return a true or false. How do I run this randomly N times and also have a counter and print out the amount of times it's True?



Solution 1:[1]

First, you need to generate a random number within a specified number range:

n = random.randint(0, 10)

Then, you need to add a base counter from which to count onto for each of the specified True outcomes:

reds = 0
blacks = 0

When iterating with a for loop, you need to set the starting point and ending point. You were missing the starting index and a colon here. You say you want to loop a random number of times, which is where n comes into play:

for i in range(0, n):

If the conditions are met, you want to increment either the reds or blacks variable by one, so you're able to see how many of each condition were True. I'd recommend changing your operator from < or > to <= or >=. As it's written, you aren't handling the third iteration of the loop. I left it in in my example below, because I'm not sure what your desired outcome is there.

At the end, you have something like this:

    n = random.randint(0, 10)
    bag = {}
    reds = 0
    blacks = 0
    for i in range(0, n):
        if i < 3:
            bag[i] = 'red'
            reds+=1
        elif i > 3 and i < 10:
            bag[i] = 'black'
            blacks+=1

        entry_list = list(bag.items())
        random_entry = random.choice(entry_list)
        print(random_entry)
    print(reds)
    print(blacks)
(0, 'red')
(1, 'red')
(2, 'red')
(1, 'red')
(1, 'red')
(5, 'black')
(6, 'black')
(4, 'black')
(8, 'black')
3
5

If you wanted to also explicitly keep track of True and False runs for each variable, you just add a little logic for that, as such:

    blackfalse = True
    redfalse = True
    for i in range(0, n):
        if i < 3:
            bag[i] = 'red'
            reds+=1
            blackfalse = True
            redfalse = False
        elif i > 3 and i < 10:
            bag[i] = 'black'
            blacks+=1
            redfalse = True
            blackfalse = False
        print(redfalse)
        print(blackfalse)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RMA Dev