Reputation: 13
I am writing code about the probability of flipping a coin as follows, but I keep getting errors.
import random
tries = 0
number = random.randint(0, 1)
def coin_probability(hehe):
for a in range(1, 101):
heads = 0; tails = 0
tries += 1
if tries <= 10:
if number == 0:
heads += 1
cp = heads/n
print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5d%%" %(tries, cp))
else:
if number == 0:
heads += 1
cp = heads/n
print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5d%%" %(tries, cp))
n = int(input("동전 던지기 시도 횟수를 입력(1 - 100) : "))
print('*' * 47)
print('총 %d번 동전 던지기에서 앞면이 나올 확률 : %s' %(n, coin_probability(n))) `
I want the probability to come out one by one from 1 to 10, and display 10 units from 11 to 100. For example:
1 번째까지~: (probability)%
2 번째까지~: (probability)%
3 번째까지~: (probability)%
...
10 번째까지~: (probability)%
20 번째까지~: (probability)%
...
it should be printed like this. (※I set heads to 0 and tails to 1.)
Upvotes: 0
Views: 107
Reputation: 659
I believe this is what you're looking for.
import random
def coin_probability(n):
tries = 0
heads = 0
for a in range(n):
number = random.randint(0, 1)
tries += 1
if tries <= 10:
if number == 0:
heads += 1
cp = 100*heads/tries
print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5f%%" %(tries, cp))
else:
if number == 0:
heads += 1
cp = 100*heads/tries
if tries%10 == 0:
print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5f%%" %(tries, cp))
return cp
n = int(input("동전 던지기 시도 횟수를 입력(1 - 100) : "))
print('*' * 47)
p = coin_probability(n)
print('*' * 47)
print('총 %d번 동전 던지기에서 앞면이 나올 확률 : %s' %(n, p))
Upvotes: 1
Reputation: 71
I hope that's what you want:
import random
def coin_probability(attempts):
heads = 0
for try_number in range(1, attempts + 1):
number = random.randint(0, 1)
if number == 0:
heads += 1
cp = (heads/try_number) * 100
if try_number <= 10 or (try_number % 10) == 0:
print(f"{try_number} 번째까지 던지기에서 앞면이 나온 확률: {round(cp,5)}")
def main():
attempts = int(input("동전 던지기 시도 횟수를 입력: "))
print('*' * 47)
coin_probability(attempts)
if __name__ == "__main__":
main()
Upvotes: 1
Reputation: 26
You could handle the print() after another if with
...
else:
if tries % 10 == 0:
print("something", cp, tries)
also you give n to your function as "hehe" but never use it? Other than that you could be a little more specific what kind of error occurs.
Upvotes: 0