Python Program for Monty Hall Game

This program implements Monty Hall game in Python language.

Here is the rule for Monty Hall game:

Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice? For more detail please check Monty Hall Problem on Wikipedia

Python Source Code: Monty Hall Game


# Monty Hall Game in Python
import random

def play_monty_hall(choice):
    # Prizes behind the door
    # initial ordering doesn't matter
    prizes = ['goat', 'car', 'goat']
    
    # Randomizing the prizes
    random.shuffle(prizes) 
    
    # Determining door without car to open
    while True:
        opening_door = random.randrange(len(prizes))
        if prizes[opening_door] != 'car' and choice-1 != opening_door:
            break
    
    opening_door = opening_door + 1
    print('We are opening the door number-%d' % (opening_door))
    
    # Determining switching door
    options = [1,2,3]
    options.remove(choice)
    options.remove(opening_door)
    switching_door = options[0]
    
    # Asking for switching the option
    print('Now, do you want to switch to door number-%d? (yes/no)' %(switching_door))
    answer = input()
    if answer == 'yes':
        result = switching_door - 1
    else:
        result = choice - 1
    
    # Displaying the player's prize 
    print('And your prize is ....', prizes[result].upper())
    
# Reading initial choice
choice = int(input('Which door do you want to choose? (1,2,3): '))

# Playing game
play_monty_hall(choice)

Python Output: Monty Hall Game

PLAY 1:
---------------------
Which door do you want to choose? (1,2,3): 2
We are opening the door number-1
Now, do you want to switch to door number-3? (yes/no)
yes
And your prize is .... CAR

PLAY 2:
---------------------
Which door do you want to choose? (1,2,3): 1
We are opening the door number-2
Now, do you want to switch to door number-3? (yes/no)
no
And your prize is .... GOAT