Python没有完成循环
我刚开始学习python,为了好玩,我想看看我是否能把monty hall问题变成python版本。当我使用1或2次迭代时,一切似乎都在小范围内工作,但过去什么都不工作。for循环没有完成我希望它完成的迭代量Python没有完成循环,python,for-loop,iteration,Python,For Loop,Iteration,我刚开始学习python,为了好玩,我想看看我是否能把monty hall问题变成python版本。当我使用1或2次迭代时,一切似乎都在小范围内工作,但过去什么都不工作。for循环没有完成我希望它完成的迭代量 import random def problem(tests): wins = 0 losses = 0 doors = ["goat", "car", "goat"] for test in range(tests): #we sh
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)
问题不在于for循环,而在于while循环 为了使while循环中断,
montychoice
必须等于car
和玩家的选择。但是如果玩家的选择不是汽车,而是山羊呢?while循环永远不会中断
我想你想要
和
而不是或
作为你的while循环。这样,如果任何一个条件都不满足,循环就会中断。问题在于这个循环
while montychoice != 'car' or montychoice == choice:
montychoice = random.choice(doors)
一旦玩家选择了汽车,这意味着无论蒙蒂选择汽车还是不选择汽车,他必须选择另一种选择。因此,他总是不断地选择,而您的脚本中不会有任何进一步的内容。尝试在您的while循环中添加print语句。这是我看到的唯一一段阻塞代码。因此,无论出于何种原因,如果退出条件不满足,它将永远留在while循环中。您不希望为此使用random.choice()。对于这个问题,了解选择了哪些门非常重要,而不仅仅是门后面是什么,所以使用random.randint(0,2)或random.randrange(len(doors))来获取实际的门索引。