【发布时间】:2017-06-06 15:51:38
【问题描述】:
我所有的代码都在下面。
这周刚开始学习编程。我正在尝试制作一个 Monty Hall 模拟器(仅文本),其中玩家通过选择 1、2 或 3 来选择一扇门。但出于某种原因,Python 似乎无法识别输入!
以下是游戏的链接,适合初学者:
我的程序试图做的事情如下。首先玩家选择一扇门,1、2 或 3。然后程序检查以确保玩家确实输入了这三个数字之一。如果不是,则该人需要再次选择。
在此之后,游戏随机选择一个获胜门。然后,根据游戏规则,程序需要显示一个虚拟奖品(山羊)。所以程序随机选择其中一扇门作为“山羊门”。程序首先确定这扇门不是获胜门,也不是被选中的门。
这是我在运行代码时遇到的错误:
line 52, in <module>
doors()
line 14, in doors
while goatDoor == chosenDoor or goatDoor == winningDoor:
NameError: name 'chosenDoor' is not defined
我的问题是我不知道为什么它一直说 selectedDoor 没有定义!
代码如下:
import random
def chooseDoor(): # choose a door
chosenDoor = ''
while chosenDoor != 1 and chosenDoor != 2 and chosenDoor != 3:
print('Choose a door. (1, 2 or 3)')
chosenDoor = input()
return chosenDoor
print('You chose door number ' + str(chosenDoor) + '.')
def doors(): # the winning door and the dummy door are randomly selected
winningDoor = random.randint(1,3)
goatDoor = ''
while goatDoor == chosenDoor or goatDoor == winningDoor:
goatDoor = random.randint(1, 3)
def keepOrSwitch():
switchDoor = 1
if switchDoor == chosenDoor or switchDoor == winningDoor:
switchDoor = 2
if switchDoor == chosenDoor or switchDoor == winningDoor:
switchDoor = 3
print('Do you want to')
print('KEEP your choice of door number ' + str(chosenDoor) + '?')
print('...or...')
print('Do you want to')
print('SWITCH and choose door number ' + str(switchDoor) + '?')
print()
choice = ''
while True:
print('Type \'K\' for keep or type \'S\' for switch.')
choice = input()
if choice == 'K' or choice == 'k':
break
if choice == 'S' or choice == 's':
chosenDoor = switchDoor
break
def checkWin():
if chosenDoor == winningDoor:
print('You win!')
if chosenDoor != winningDoor:
print('You lose!')
# the rest of the code is the actual game
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
chooseDoor()
doors()
keepOrSwitch()
checkWin()
print('Do you want to play again? (yes or no)')
playAgain = input()
【问题讨论】: