本帖最后由 tommyyu 于 2022-11-13 17:23 编辑 from random import randrange
def init():
result={i:"goat"for i in range(3)}
r=randrange(3)
result[r]='car'
return result
def start():
doors = init()
while True:
try:
firstDoorNum=int(input("choose a door:"))
assert 1<=firstDoorNum<=3 #这一句原来 assert 后面少了一个空格
firstDoorNum -= 1 # 由于后面字典的键都是从 0 开始的,所以要和后面对应。
break
except:
print("door number must be 1,2,3")
for door in doors.keys()-{firstDoorNum}:
if doors[door]=="goat":
print('"goat" behind the door',door+1) #door 要加一
thirddoor=(doors.keys()-{door,firstDoorNum}).pop() #这一句的 doors.keys() 写成了 door.keys()
change=input('switch to {}?(y/n)'.format(thirddoor+1)) #thirddoor也要加一
finaldoornum=thirddoor if change=='y' else firstDoorNum
if doors[finaldoornum]=='goat':
return 'I win'
else:
return 'you win'
while True: #循环部分都多了一个缩进
print('='*30)
print(start())
r=input('do you want to try once more?(y/n)')
if r =='n':
break
|