我所有的代碼都在下面。Python3將無法識別代碼中的變量
本週剛剛開始學習編程。我試圖製作一個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
我的問題是,我不知道爲什麼它口口聲聲說chosenDoor沒有定義!
下面的代碼:
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()