Martin
Martin

Reputation: 75

using random to flip coins and it whont work

Ok so i tried to make a program that flipped a bunch of coins by uning random.randint(0,1) to flip them and have it run for example 100 times (with a while loop) but it always outputed 0 as the score help?

Code:

import random

i = int(1) # the thing to count how many coins have been fliped
score = int(0) #the score
coins = int(100) # the amont of coins to ble fliped

while i <= coins:
    rand = random.randrange(0,1)
    score += rand
    i += 1

print("your score is", score)
print("you flipped ", coins, " coins")

optuput to console (im using sublime atm but i tried cmd too and got the same thing):

your score is 0
you flipped  100  coins
[Finished in 0.8s]

Upvotes: 0

Views: 184

Answers (2)

Cameron Chandler
Cameron Chandler

Reputation: 418

Just like how range(0, 1) would give you all the numbers from 0 to 1 not including 1 i.e. just 0, the randrange(0, 1) function will choose numbers randomly from 0 to 1 not including 1. Try randrange(0, 2) instead.

Or even better:

import numpy as np
np.random.randint(0, 2, 100)

And the mean can be found as

np.mean(np.random.randint(0, 2, 100))

Upvotes: 0

hjpotter92
hjpotter92

Reputation: 80629

From docs of randrange function:

Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.

and range:

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.

Replace randrange with randint, and you'd get the expected™ coin flips.

Upvotes: 2

Related Questions