Code Review: Program that simulates the "door game": either you win a car or a goat!

Asked

Viewed 244 times

-1

Write a program to simulate the door game. Make a program that has the output as the following:

Hello, welcome to our program! Let’s see if you will win a car or not! Choose one door: 3 You chose door 3, but I inform you that at door 2 there is a goat. You want to change port (1 - Yes/ 0 - No): 1 Won a car!

My solution:

import random #selecionar a porta
testes = int(input("Digite o número de testes: "))
bode =0
trocar =0 #nao trocar

for i in range(testes):
    porta = random.randrange(1,4) #portas de 1 a 3
    premio = random.randint(1,3) #randint inclui o extremo!
    bode = random.randint(1,3)
    if premio != bode and premio !=porta:
        print("A porta {} tem um bode. ".format(bode))

        trocar = int(input("Deseja trocar? "))
        if trocar == 1:
            porta = int(input("Digite a porta: "))


    if porta ==premio:
        print("Ganhou")
        break
    else:
        print("Não ganhou! Que pena!")

In my tests the program is working but would like a more pythonica solution to learn the style!

  • I don’t understand the downvote. I don’t see anything wrong in asking for a more pythonic way to a solution already presented. It’s just a code review.

  • @Piovezan: I agree! It’s just a code review!

  • What would be more pythonica solution? It would be something with less line of code?

  • 1

    Perhaps it is necessary to give an edited title, and put Code Review, be clearer so that outsiders can find their question to solve their problem.

  • 1

    @Sveen: https://answall.com/questions/192343/o-que-%C3%A9-c%C3%B3digo-pyth%C3%B4nico/192347

  • 1

    @Sveen , under pythonic code: https://answall.com/q/192343/64969

Show 1 more comment

1 answer

2


Formatting

The spacing of your code is not good. The code is too compact and this hinders reading. Also, there is no standard.

Example:

testes = int(input("Digite o número de testes: "))
bode =0

On the top line there is a space after the assignment signal, on the bottom line, no.

The Python community uses PEP 8 as a guide to format code. You should also use!

Comments on the code

There are too many unnecessary comments in your code. Only comment when the comment actually adds valuable information that is not explicit in the code itself.

Usability pt 1

If the user enters a non-numeric value, his program displays a very ugly error message. In addition, all the progress du user is lost and he has to start again. You can improve this by creating a new function that reads a keyboard number and only returns when a valid value is entered.

Example:

def ler_numero(mensagem, minimo, maximo):
    while True:
        try:
            valor = int(input(mensagem))
        except ValueError:
            print('Valor inválido')
            continue

        if valor >= minimo and valor <= maximo:
            return valor

        print(f'O valor deve estar entre {minimo} e {maximo}')

porta_escolhida = ler_numero('Número da porta: ', 1, 3)

Usability pt 2

The "Want to trade?" message suggests that the user should type "yes", "y" or something like that, but your code expects a number. For this case, create another function that keeps asking the user until he gives a valid entry, and that displays a more informative message.

Example:

def ler_opcao(mensagem, opcoes_validas):
    while True:
        entrada = input(mensagem)

        if entrada in opcoes_validas:
            return entrada

        print('Entrada inválida')

deseja_trocar = ler_opcao('Deseja trocar de porta? (s/n) ', ['s', 'n'])

Language resources

If you are using the latest version of Python, you can opt for f-strings instead of function format, as it generally makes the code more readable.

Good practice

Use the language if __name__ == '__main__'.

Consistency

You used two different functions (randint and randrange) to get a random number from 1 to 3. Why two different ways to do the same thing? Be consistent!

Logic and requirements

From what I could understand from the description of the game, the stages should be:

  1. User chooses one of the three ports
  2. The presenter reveals the goat of one of the remaining doors
  3. User chooses whether or not to change port
  4. The presenter reveals the content of the user port

What your show does:

  1. Automatically draw the user port without asking him
  2. If the door drawn is the car door, informs that the user has won and ends the round
  3. If the door is not the drawn one, asks if the user wants to change without even saying which door was his
  4. Report the result

That is, the flow of your program is quite different from what it should be.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.