我已经模拟了Monty Hall游戏,我想通过用户输入的内容重复以下代码。我是一个非常新手的程序员,所以请耐心等待。我只是不知道我是否正确放置了for循环。
下面是我的代码,我想告诉它通过for循环运行剩余代码v
的次数,用户之前输入。在这种情况下v
是2.我得到一个TypeError,然而,它只运行一次,这种情况随时发生v>1
:
表示范围内的t(1,v + 1)
print('Game',t)
doors = [1,2,3]
prizes = ['C','G1','G2']
while valid == True:
random.shuffle(prizes)
initial_doors = list(zip(doors,prizes))
doors = initial_doors[:]
print('Doors are Set Up as:',doors)
user = int(input('Select door 1, 2, or 3:\n'))
user = user - 1
(a,b)=doors[0]
(c,d)=doors[1]
(e,f)=doors[2]
if user == 0:
selected_door = a
print('You selected door', selected_door)
elif user == 1:
selected_door = c
print('You selected door', selected_door)
elif user == 2:
selected_door = e
print('You selected door', selected_door)
user_door = doors.pop(user)
valid = False
monty_door = [i for i, j in doors if 'G' in j] # This is where the error occurs
monty_door = str(monty_door)
monty_door = monty_door[1]
monty_door = int(monty_door)
print('Monty selected door', monty_door)
car_door = [i for i, j in initial_doors if 'C' in j]
car_door = str(car_door)
car_door = car_door[1]
car_door = int(car_door)
if car_door != selected_door:
win = 'switch'
print('Player should', win, 'to win.')
elif car_door == selected_door:
win = 'stay'
print('Player should', win, 'to win')
输出在下面,它应该在下面有另一个迭代。在询问用户要运行多少测试后,您会看到v=2
,并在最后打印错误:
How many tests should we run? Type Exit to exit: 2
Game 1
Doors are Set Up as: [(1, 'G1'), (2, 'C'), (3, 'G2')]
Select door 1, 2, or 3:
2
You selected door 2
Monty selected door 1
Player should stay to win
Game 2 # Error message below, line 58 is commented above
Traceback (most recent call last):
File "python", line 58, in <module>
File "python", line 58, in <listcomp>
TypeError: 'int' object is not iterable
答案 0 :(得分:1)
你的问题似乎是你在第一场比赛结束时设置valid = False
,然后在第二场比赛中你没有进入你的while循环而且门只是[1,2,3]这解释了你得到的错误。