Python没有完成for循环

2024-10-02 12:28:38 发布

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

我刚开始学习python,为了好玩,我想看看我是否能把montyhall的问题写成python版本。当我使用1或2次迭代时,所有的东西似乎都在小范围内工作,但在过去的时间里,什么都不工作。for循环没有完成我想要的迭代量。你知道吗

import random

def problem(tests):

    wins = 0
    losses = 0
    doors = ["goat", "car", "goat"]

    for test in range(tests):
        #we shuffle the doors
        random.shuffle(doors)
        #the player picks a door
        choice = random.choice(doors)
        #monty chooses a door
        montychoice = random.choice(doors)
        while montychoice != 'car' or montychoice == choice:
            montychoice = random.choice(doors)

        #if the player's door is a car, he losses
        if choice == 'car':
            losses += 1
            print 'goat'
        elif choice == 'goat':
            wins += 1
            print 'car'

    print "Switching wins: %d" % wins
    print "Switching loses: %d" % losses

problem(100)

Tags: thefortestsrandomcarprintproblemshuffle
2条回答

问题不在于for循环,而在于while循环。你知道吗

为了让while循环中断,montychoice必须等于car和玩家的选择。但是如果玩家的选择不是car,而是goat,那会怎样呢?while循环永远不会中断。你知道吗

我认为您希望while循环使用and,而不是or。这样,如果任何一个条件都不满足,循环就会中断。你知道吗

问题是这个循环

while montychoice != 'car' or montychoice == choice:
        montychoice = random.choice(doors)

一旦玩家选择了一辆车,这意味着无论蒙蒂选择一辆车还是不选择一辆车,他必须选择另一种选择。所以他一直在挑选,而你在剧本里再也找不到了。你知道吗

相关问题 更多 >

    热门问题