从Python开发开始:Coin-Tossing Loops

时间:2013-02-28 17:30:01

标签: python coin-flipping

下午所有,

我是一个想要自学编程的人。因此,我开始使用Python。作为免责声明,我已经搜索了一些Python硬币抛出的例子,但我还没有真正理解以前的askers所提出的任何代码。

我的任务 我的教育资料要求我提出一个应用程序,翻转虚拟硬币100次,然后打印结果。我的想法是使用无限循环,当硬币折腾达到100时突破,然后打印结果。

我没有完全实现这一点,我没有发现我写的错误。它似乎达到了100翻转,但只打印了50个头/尾;因此我的错误在计数逻辑中某处?

任何解释(记住我是初学者,而不是白痴!)会得到我的感激和我的赞成

感谢您阅读

# Exercise 3.2
# Heads and Tails coin flip

#import random
import random

#declare variables
heads = 0
tails = 0
cointoss = 0
coinresult = random.randint(1,2)

#start the loop
while True:
    cointoss +=1

    #end the loop if cointoss is greater than 100
    if cointoss > 100:
        break
    if coinresult == 1:
        heads +=1
        cointoss +=1
    elif coinresult == 2:
        tails +=1
        cointoss +=1

  print("Heads came up", heads, "times")
  print("Tails came up", tails, "times")

5 个答案:

答案 0 :(得分:4)

每个循环增加cointoss两次。

while True:
    cointoss +=1      # You already incremented here, therefore...
    if cointoss > 100:
        break
    if coinresult == 1:
        heads +=1
        cointoss +=1  # ...get rid of this...
    elif coinresult == 2:
        tails +=1
        cointoss +=1  # ...and this.

另外,正如所指出的,你应该在循环中的某个地方获得一个新的coinresult

答案 1 :(得分:3)

把这一行:

coinresult = random.randint(1,2)

在while循环中。否则你得到一次值,并且只是在循环中反复使用它,并且你在每个循环中在两个地方添加了cointoss。

答案 2 :(得分:3)

您可以更轻松地使用range方法编写循环,如下所示:

for i in range(0, 100):
    coinresult = random.randint(1, 2)
    if coinresult == 1:
        heads += 1
    else:
        tails += 1
print("Heads came up", heads, "times")
print("Tails came up", tails, "times")

答案 3 :(得分:1)

# Exercise 3.2
# Heads and Tails coin flip

#import random
import random

#declare variables
heads = 0
tails = 0
cointoss = 0
coinresult = random.randint(1,2)

#start the loop
while True:
   cointoss +=1

#end the loop if cointoss is greater than 100
   if cointoss > 100:
       break
   if coinresult == 1:
       heads +=1
   elif coinresult == 2:
       tails +=1
   coinresult = random.randint(1,2)

print("Heads came up", heads, "times")
print("Tails came up", tails, "times")

你永远不会记得你的随机化,因此这个数字从未改变过,你在每个循环中在两个地方添加了cointoss。

答案 4 :(得分:0)

如果您想要冒险,请查看generator expressions和内置sum以及random.randint

heads = sum(random.randint(0,1) for _ in range(100))
print("Heads came up {} times".format(heads))
print("Tails came up {} times".format(100 - heads))