Python 使用循环翻转 x 次硬币 x 次但收到奇数输出

问题描述 投票:0回答:1

我是 python 和一般编码的新手。我有一个课堂作业要编写一个程序,该程序使用循环多次翻转多个硬币。代码必须:

  1. 询问硬币的数量以及抛硬币的次数。
  2. 必须再次询问输入是否小于 0.
  3. 打印每个硬币翻转指定次数的结果,并且必须是随机的。
  4. 然后打印正面和反面的总数。 我确实必须使用随机,所以其他模块的建议或实现随机化的更好方法不是我要找的东西,谢谢。

输出应该是这样的:

How many coins do you want to flip? 2
How many times do you want to flip each coin? 2

Coin 1
Flip: 1; Result: Heads
Flip: 2; Result: Tails

Coin 2
Flip: 1; Result: Tails
Flip: 2; Result: Heads

There were 2 Tails in total
There were 2 Heads in total

这是我尝试过的方法:(由于一些 irl 问题,我不得不使用我的手机来询问这个问题,所以如果格式已关闭,我很抱歉!)

import random

heads = 0
tails = 0

coins = int(input("How many coins: "))

while coins !="":
    if coins \<= 0:
        print ("Invalid input")
        coins = int(input("How many coins: "))
    else:
        flips = int(input("How many times to flip: "))
        if flips \<= 0:
            print ("Invalid input")
            flips = int(input("How many times to flip: "))
        else:
            for n in range (0, coins):
                for i in range (0, flips):
                    print (" ")
                    print ("Coin %0d" %n)
                    print (" ")
                    n = coins + 1
                    for flips in range (0, flips):
                        flip = random.randint(0,1)
                        if flip == 0:
                            heads += 1
                            print ("Flips: %0d;" %i, "Result: heads")
                        else:
                            tails += 1
                            print ("Flip: %0d;" %i, "Result: tails")
                        i = flips + 1
print ("total heads:", heads)
print ("total tails:", tails)
break

我得到的结果因我输入的数字而异。我可能会掷 4 个硬币 3 次,它会掷 6 个硬币。或者 1 个硬币 3 次,它会翻转 6 个硬币。但是 1 个硬币 2 次翻转 1 个硬币 2 次。计算硬币和翻转的数字也不能正常工作。我得到如下结果:

Coin 0
Flip: 0; Result: Tails
Flip: 3; Result: Heads

Coin 2
Flip: 1; Result: Tails
Flip: 3; Result: Tails.

我很难过,此时所有代码看起来都像 abc 汤。任何帮助表示赞赏。

python loops random nested-loops coin-flipping
1个回答
0
投票

我建议您在进入评估阶段(当您正在抛硬币时)重新查看代码的流程控制和变量使用情况。

具体来说,您似乎在使用两个不同循环的翻转次数:for i in range (0, flips):for flips in range (0, flips):

此外,第二个 (for flips in range (0, flips):) 正在覆盖您用来存储用户请求的每个硬币的翻转次数的 flips 变量。

© www.soinside.com 2019 - 2024. All rights reserved.