Danielle
Danielle

Reputation: 55

randint returns same number over and over

I'm just getting started with Python, and ran into a problem. I'm writing a function to simulate a coin flip. When I wrote some mock code to test the randint function it worked perfectly fine and returned a nice random sequence of heads and tails. The code I try to use in my program however returns only h's or t's.

import random

coin_sequence = "hhththththhhhttthht"
generated_sequence = "" #define generated_sequence
length = len(coin_sequence)
flip = random.randint(0, 1)
for value in range(length):
    if flip == 0:
        generated_sequence = generated_sequence + "t"
    else:
        generated_sequence = generated_sequence + "h"

print(generated_sequence)

I probably made some really stupid mistake. Who can help me?

Upvotes: 1

Views: 4588

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121904

You only call random.randint() once, before the loop starts:

flip = random.randint(0, 1)
for value in range(length):
    # ...

That call returns an integer object. Checking that integer again and again in a loop won't change its value, no matter what function produced it originally.

If you wanted to get new random numbers, ask random.randint() to produce one in the loop:

for value in range(length):
    flip = random.randint(0, 1)
    if flip == 0:
        generated_sequence = generated_sequence + "t"
    else:
        generated_sequence = generated_sequence + "h"

Note that you could write that loop a little more concisely with:

for value in range(length):
    flip = random.randint(0, 1)
    generated_sequence += "t" if flip == 0 else "h"

Upvotes: 1

Related Questions