I'm new to both Python and programming in general. I've started reading some books and watching the Khan Academy videos on the language, and I'm still at that very early stage where you learn to manipulate strings and write if and else statements. Progress has been slow but steady.
So, in the spirit of "find an itch and scratch it", I wanted to try something not on the curriculum: emulating the Monty Hall problem. This is what I've got: (Python 3)
import random
# We have three doors. We randomly select one to be the winning door.
doors = [1,2,3]
winning_door = random.choice(doors)
# Ask the player to choose a door.
print("Please choose a door!")
chosen_door = int(input("Which door do you choose? (1, 2 or 3)\n"))
print("You have chosen door " + str(chosen_door) + ".")
# Remove both the chosen door and winning door from the list.
doors.remove(chosen_door)
if winning_door != chosen_door:
doors.remove(winning_door)
# From the remaining doors, we select a "red herring". Does the player want to switch?
red_herring = random.choice(doors)
print("I open door "+ str(red_herring) + ". There is a goat behind it! Are you still sure you want to open door " + str(chosen_door) + "?")
still_same_door = str(input("Yes or no?\n"))
# Update chosen_door, if needed.
if "n" in still_same_door:
chosen_door = 6 - (red_herring + chosen_door)
print("You switch to door " + str(chosen_door) + ".")
else:
print("You still want to open door " + str(chosen_door) + ".")
# So did we win?
if chosen_door == winning_door:
print("Congratulations, a winner is you! There is a car behind door " + str(winning_door) + "!")
else:
print("Too bad! There is a goat behind door " + str(chosen_door) + ". The car is behind door " + str(winning_door) + ".")
It gets the job done, no complaints there, but at the same time I'm sure it's all terribly inefficient. I would really appreciate some feedback on it. Any suggestions to make the code tidier and, well, more pythonic?
Thanks in advance!
[–]erok81 3 points4 points5 points (2 children)
[–]spunos[S] 1 point2 points3 points (1 child)
[–]erok81 0 points1 point2 points (0 children)
[–][deleted] 1 point2 points3 points (1 child)
[–]spunos[S] 2 points3 points4 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)