Python 未完成 for 循环

标签 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 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 AND 玩家的选择。但是,如果玩家的选择不是汽车,而是山羊怎么办? while 循环永远不会中断。

我认为您的 while 循环需要 and 而不是 or 。这样,如果任一条件不满足,循环就会中断。

关于Python 未完成 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44511845/

相关文章:

Ruby:重构一个复杂的嵌套循环方法

Rails 加密凭证功能的 Python 世界模拟(安全存储 secret )

java - 增强for循环空检查优化

bash - 使用 jq 遍历 JSON 对象

javascript - 将 VisuAlgo 冒泡排序代码翻译成 Javascript

c# - for循环背后的逻辑

c# - 您如何将其转换为迭代函数而不是使用嵌套循环递归?

python - 什么是正则括号的非分组版本

Python:太多 join()?

python - 为多类道路分割实现 U-net