HzII
HzII

Reputation: 11

Percents with Python

I would like to get one program working. I almost have it, but some things still cause errors.

Main idea is that program would do these things:

Example:

Insert %  of free throws: 45
1. throw hits
2. throw hits
3. throw misses
4. throw hits
...
997. throw misses
998. throw misses
999. throw hits
1000. throw misses
Hits 458 throws.

I have created this:

from random import randint
percent = int(input("Insert % of free throws: "))
var = 1
hits = 0
while var < 1000:
if randint(1, 100) <= percent:
    var = var + 1
    print(str(var) + '. throw hits')
    hits = hits + var 
else:
    print(str(var) + '. throw misses')

print("Hits " + str(hits) + " throws.")

But there are some errors. First of all, if I insert 0% then it goes crazy and the second one is , that the hit count is ridiculous - like 500500 and so on. I have idea that var != 0 but it's still not working and count thing is still mystery for me. I have tried to but 'hits' before and after var but it still won't work. Anyone have ideas to get me on right track?

Upvotes: 0

Views: 101

Answers (2)

Barmar
Barmar

Reputation: 780889

The problem is that you're only incrementing var when you get a hit, you should be incrementing it for every throw. So just use a simple for loop.

And you should increment hits by just 1 every time there's a hit, not by var.

for var in range(1, 1001):
    if randint(1, 100) <= percent:
        hits += 1
        print(str(var) + '. throw hits')
    else:
        print(str(var) + '. throw misses')
print ("Hits " + str(hits) " throws.")

Note that range() does not include the end number in the range, so to get 1,000 throws starting with var = 1, you have to use 1001 as the end.

Upvotes: 1

Adam Smith
Adam Smith

Reputation: 54183

Barmar picked up on the reason for the weirdness in your result values, so let me just pick out some points for review since this is an illustrative code sample.

The "standard" way of doing weighted distributions in Python is:

random.random() < pct

Where pct is a fraction of 1, e.g 45% -> 0.45. This changes your code to:

percent = int(input("Insert % of free throws: ")) / 100

...
    if random.random() < percent:
        ...

Other nitpicks include avoiding while loops whenever possible. It's rare that you need a while loop in Python that isn't while True. Use a for loop, especially since you're trying to track the loop index! Combine that with a few other tweaks and you get...

hitcount = 0

for i in range(1, 1001):  # loop from 1 -> 1000 inclusive
    if random.random() < percent:
        hitcount += 1
        msg = "{}. throw hits".format(i)
    else:
        msg = "{}. throw misses".format(i)
    print(msg)
print("Hit {} throws.".format(hitcount))

Notably this uses str.format instead of string building with the % operator. This is preferred.

Upvotes: 1

Related Questions