3

我知道有人问过类似的问题,但请多多包涵。我正在帮助我的表弟在 python 中创建一个程序,其中硬币被翻转 1000 次,“玩家”可以这么说猜测出现了多少次正面。然后,她想检查猜测是否在正面出现次数的 10 以内,并相应地做出回应(骗子你(回答 - 猜测)关闭)或(干得好(回答 - 猜测)关闭)。我习惯于使用 UNIX,而 python 似乎以非常不同的方式处理项目。这是代码可能以某种方式使用范围来检查猜测是否在范围内?

#Guess how many times heads will occur when a coin is flipped 1000 time
import random
import time

print('I will flip a coin 1000 times. Guess how many times it will come up heads.     (Press enter to begin)')
int(guess) = input()
flips = 0
heads = 0
while flips < 1000:
    if random.randint(0, 1) == 1:
        heads = heads + 1
    flips = flips + 1

    if flips == 900:
        print('900 flips and there have been ' + str(heads) + ' heads.')
        time.sleep(5)
    if flips == 100:
        print('At 100 tosses, heads has come up ' + str(heads) + ' times so far.')
        time.sleep(2)
    if flips == 500:
        print('Half way done, and heads has come up ' + str(heads) + ' times.')
        time.sleep(2)

print()
print('Out of 1000 coin tosses, heads came up ' + str(heads) + ' times!')
time.sleep(2)
print('Were you close?')
int(answer) = input()
4

1 回答 1

7
if heads - 10 <= int(guess) <= heads + 10:

或者

if abs(heads - int(guess)) <= 10:
于 2013-04-03T06:01:54.363 回答