当抛硬币的整个过程完成后,无法计算出如何使python抛硬币程序循环回到某个点

2024-05-16 00:19:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我的头撞在墙上已经有几个小时了,我想弄清楚这个问题,所以我非常感谢你的帮助。我要做的是在一个Y/N问题的Y输入上循环程序,特别是当Y被输入时,我希望它以示例输出中所示的方式进行反应。在

这是我的代码:

import random
def main():
    name = eval(input("Hello user, please enter your name: "))
    print("Hello", name ,"This program runs a coin toss simulation")
    yn = input("Would you like to run the coin toss simulation?(Y/N):")
    if yn == Y:

    elif yn == N:
        print("Ok have a nice day!")

    heads = 0
    tails = 0
    count = tails + heads
    count = int(input("Enter the amount of times you would like the coin to     flip: "))
    if count <= 0: 
        print("Silly rabbit, that won't work")
    while tails + heads < count:
        coin = random.randint(1, 2)
        if coin ==1:

            heads = heads + 1
        elif coin == 2:

            tails = tails + 1
    print("you flipped", count , "time(s)")
    print("you flipped heads", heads , "time(s)")
    print("you flipped tails", tails , "time(s)")
main()

下面是我要查找的示例输出:

^{pr2}$

Tags: thenameyou示例inputiftimecount
2条回答

要多次运行抛硬币模拟,可以将其放入while循环中。在

您的if yn == Y:测试将不起作用,因为您还没有定义变量Y,所以当Python尝试执行该行时,会得到一个NameError。您实际应该做的是根据字符串测试yn的值。在

我对你的代码做了一些其他的小调整。我去掉了那个潜在危险的eval函数调用,你不需要它。我还创建了一个循环来请求所需的翻转计数;当count是一个正数时,我们就中断循环。在

import random

def main():
    name = input("Hello user, please enter your name: ")
    print("Hello", name , "This program runs a coin toss simulation")
    yn = input("Would you like to run the coin toss simulation?(Y/N): ")
    if yn != 'Y':
        print("Ok have a nice day!")
        return

    while True:
        heads = tails = 0
        while True:
            count = int(input("Enter the amount of times you would like the coin to flip: "))
            if count <= 0: 
                print("Silly rabbit, that won't work")
            else:
                break

        while tails + heads < count:
            coin = random.randint(1, 2)
            if coin ==1:
                heads = heads + 1
            else:
                tails = tails + 1

        print("you flipped", count , "time(s)")
        print("you flipped heads", heads , "time(s)")
        print("you flipped tails", tails , "time(s)")

        yn = input("Would you like to run another coin toss simulation?(Y/N): ")
        if yn != 'Y':
            print("Ok have a nice day!")
            return

main()

这段代码是为python3编写的。在Python2上,您应该使用raw_input代替input,并且还应该将

未来导入打印功能

在脚本的顶部,这样您就得到了python3print函数,而不是旧的python2print}\u语句。在


可以对该代码进行一些改进。特别是,它应该处理为计数提供的非整数。如果输入错误,这个版本就会崩溃。要了解如何修复此问题,请参见Asking the user for input until they give a valid response。在

我想你应该说在第6行if yn == 'Y',而不是if yn == Y。将Y视为变量,而它实际上是输入中的字符串。在

相关问题 更多 >