Calculator in Python

Asked

Viewed 61 times

-1

I made a calculator in Python as a practical exercise, I didn’t use functions or research anything, I just did what I know. I would like to know if the code is good, even without the use of functions (after I will use also to practice :D). if you can help me tell me if it’s clean code, well-commented and easy to understand. I am still learning and I would like to know if I am on the right path. I thank you very much already!

# Calculadora 1.0

# importa a função sleep() para criar pausas
from time import sleep as sl


# Da start no programa - OK
while True:
    while True:
        try:
            rodar = int(input("Deseja iniciar o programa? [1- sim  2- não] : "))
            break
        except:
            print("Erro: Você deve digitar um número")
            sl(2)
            continue

    # caso sim - OK
    if rodar == 1:
        Roda = True
        break
        sl(2)

    # caso não - OK
    elif rodar == 2:
        print("\nBeleza então!")
        Roda = False
        break
        sl(2)
    
    # verifica erro - OK
    elif rodar != 1 or rodar != 2:
        print("Erro: Opção inválida, tente novamente!")
        sl(2)
        continue

# Loop principal - OK
while Roda:
    # Entrada de dados - OK
    while True:
        try:
            pn = float(input("Primeiro número: "))
            sn = float(input("Segundo  número: "))
            break
        except:
            print("Erro: você deve digitar um número!")
            sl(2)
            continue

    # Loop de operções com os números passados - OK
    sim = True
    while sim:
        # testa se o usuario inseriu mesmo um número - OK
        while True:
            try:
                print("""
                Qual operração matemática você gostaria de realizar?
                1- soma
                2- subtração
                3- divisão
                4- multiplicação

                5- sair
                """)
                opc = int(input(">: "))
                break
            except:
                print("Erro: valor inválido tente novamente!")
                sl(2)
                continue

        # Saída de dados/Programa - OK
        # soma - OK
        if opc == 1:
            soma = pn + sn
            print(f"\n{pn} + {sn} = {soma}")
            
        # subtração - OK
        elif opc == 2:
            sub = pn - sn
            print(f"\n{pn} - {sn} = {sub}")

        # divisão - OK
        elif opc == 3:
            div = pn / sn
            print(f"\n{pn} / {sn} = {div}")

        # multiplicação - OK
        elif opc == 4:
            mult = pn * sn
            print(f"\n{pn} x {sn} = {mult}")

        # sair do programa - OK
        elif opc == 5:
            print("Até a próxima!")
            exit()

        # Erro - OK
        else:
            print("Erro: Você deve escolher uma das opções disponíveis!")
            sl(2)
            continue
        
        # verifica se o usuario ainda vai usar os mesmos números - OK
        while True:
            while True:
                try:
                    esc = int(input("Deseja realizar mais alguma operação com estes números [1- sim  2- não] : "))
                    break
                except:
                    print("Erro: escolha apenas entre as duas opções!")
                    sl(2)
                    continue

            # caso sim - OK
            if esc == 1:
                sim = True
                break
                sl(2)

            # caso não - OK
            elif esc == 2:
                print("\nBeleza então!")
                sim = False
                break
                sl(2)
            
            # verifica erro - OK
            elif esc != 1 or esc != 2:
                print("Erro: Opção inválida, tente novamente!")
                continue
        
        # Testa se o usuario ainda quer usar o programa
        while True:
            while True:           
                try:
                    rodar = int(input("\nDeseja continuar no programa? [1- sim  2- não] : "))
                    break
                except:
                    print("Erro: Você deve digitar um número!")
                    sl(2)
                    continue

            # caso sim - OK
            if rodar == 1:
                Roda = True
                break
                sl(2)

            # caso não - OK
            elif rodar == 2:
                print("\nAté a próxima!")
                Roda = False
                break
                sl(2)
            
            # verifica erro - OK
            elif rodar != 1 or rodar != 2:
                print("Erro: Opção inválida, tente novamente!")
                continue
  • I forgot to mention that I did everything in Google Colab, so I did not put any code that cleans the terminal. There is no way :(

  • Book: Clean Code. Your code is not legal no bro. It could have some methods there to avoid code rethought, among other things.

  • The part of the methods I quoted in the question, I did without using the functions only as practical test.

1 answer

1

Here are some things that hinder the understanding of the code.

  • You named the Sleep library team as Sl, but I think it would be good not to name it, because it will be better for understanding, especially in larger codes.

  • Some comments have to improve. Like the "yes case". What "yes case"? And the "no case". If not what? It would be better if they were something like "if you want to start the program" and "if not".

  • Improve variable names, and try not to do things like "run" and "Wheel" to name variables. Variable names must by convention be in lower case, and you better make it clear what they are. An example:

while True:
    try:
        n1 = float(input("Entre um número: "))
        n2 = float(input("Entre outro número: "))
        
        soma = n1 + n2
        break
        
    except ValueError:
        print("\nVocê precisa digitar um número!\n")
    
print(soma)

  • If you can, lower the while. Try to leave the while True clear or try to change for things like while estiver_rotating or while not ended.

  • There are some Sleep that are not working because they are coming after a break, that is, are being ignored.

These are some things that hinder the understanding of the code. My tip is that now that you have an overview of how the program works, rewrite it from scratch by consulting this one. It always helps me.

Browser other questions tagged

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