How do I repeat an algorithm in Python?

Asked

Viewed 159 times

-4

I’m starting to study programming and I’m making a simple Python calculator in Pycharm, and I wanted to know how to repeat an algorithm when the user decides to continue using the calculator. I tried to use if and exec, but I’m pretty sure I’m doing something wrong. (Ps: Test.py is the name of my file.)

print()
print()
print("-----> Calculadora <-----")
print()

valor1 = int(input("Insira o primeiro valor: "))
operação = input("Insira a operação a ser usada (+ ; -; *; /; **) ")
valor2 = int(input("Insira o segundo valor: "))

if operação == "+":
    print(valor1, " somado a ", valor2, " é igual a ", valor1 + valor2)

if operação == "-":
    print(valor1, " subtraindo ", valor2, " é igual a ", valor1 - valor2)

if operação == "*":
    print(valor1, " multiplicado por ", valor2, " é igual a ", valor1 * valor2)

if operação == "/":
    print(valor1, " dividido por ", valor2, " é igual a ", valor1 / valor2)

if operação == "**":
    print(valor1, " elevado a ", valor2, " é igual a ", valor1 ** valor2)

saída = input("Desejar continuar usando a calculdora? Responda sim ou não: ")
if saída == "sim":
    exec('Teste.py')
  • 1

    Have you studied algorithms? Repetition structures?

  • I started studying the algorithm chair last week, I was doing some simple exercises and when I finished I decided to play a little with some commands to make a calculator. About repetition structures I only got to see some things on the internet with while, but no practice. So I wanted to have a basic notion just to repeat this algorithm that I just did (it’s nothing serious, I’m just playing with the commands, if it’s too much you can ignore me kkkk).

  • Does that answer your question ? https://answall.com/a/291832/157404

2 answers

1


Put your if’s inside a while with a variable conditioning the loop.

print()
print("-----> Calculadora <-----")
print()

loop = ""
while loop != "não":

    valor1 = int(input("Insira o primeiro valor: "))
    operação = input("Insira a operação a ser usada (+ ; -; *; /; **) ")
    valor2 = int(input("Insira o segundo valor: "))

    if operação == "+":
        print(valor1, " somado a ", valor2, " é igual a ", valor1 + valor2)

    if operação == "-":
        print(valor1, " subtraindo ", valor2, " é igual a ", valor1 - valor2)

    if operação == "*":
        print(valor1, " multiplicado por ", valor2, " é igual a ", valor1 * valor2)

    if operação == "/":
        print(valor1, " dividido por ", valor2, " é igual a ", valor1 / valor2)

    if operação == "**":
        print(valor1, " elevado a ", valor2, " é igual a ", valor1 ** valor2)

    loop = input("Desejar continuar usando a calculdora? Responda sim ou não: ")

print("Calculadora finalizada")

1

You don’t need a variable to control the loop (as suggested in another answer). You can make a loop and interrupt it with break:

while True:
    valor1 = int(input("Insira o primeiro valor: "))
    operação = input("Insira a operação a ser usada (+ ; -; *; /; **) ")
    valor2 = int(input("Insira o segundo valor: "))

    if operação == "+":
        print(valor1, " somado a ", valor2, " é igual a ", valor1 + valor2)
    elif operação == "-":
        print(valor1, " subtraindo ", valor2, " é igual a ", valor1 - valor2)
    elif operação == "*":
        print(valor1, " multiplicado por ", valor2, " é igual a ", valor1 * valor2)
    elif operação == "/":
        print(valor1, " dividido por ", valor2, " é igual a ", valor1 / valor2)
    elif operação == "**":
        print(valor1, " elevado a ", valor2, " é igual a ", valor1 ** valor2)

    if 'não' == input("Desejar continuar usando a calculdora? Responda sim ou não: "):
        break # sai do loop

Note also that I used elif instead of just one if. The difference is that if you enter one of them, the other conditions are not tested. Already using only if (like you were doing), all the alternatives will be checked at all times, which is redundant and unnecessary (because if you enter one, you don’t need to check the others).

For more details, your code:

if operação == "+":
    # faz a soma

if operação == "-":
    # faz a subtração

if operação == "*":
    # faz a multiplicação
# etc...

If the chosen operation is the sum, it enters the first if. Only then he’ll test the second if, then go test the third, and so on. But if you have entered the first if, do not need to test others, because surely will not enter them.

Using if/elif I guarantee that if you entered one of the conditions, the others that comes after are no longer checked, avoiding unnecessary checks.


Note that the code has some very repetitive things: it prints the values and makes an operation with them, changing only the text and the operation done.

Therefore, you can generalize, keeping the parts that vary in a dictionary (the text and the operation done):

operacoes = {
    '+': ('somado a', lambda x, y: x + y),
    '-': ('subtraindo', lambda x, y: x - y),
    '*': ('multiplicado por', lambda x, y: x * y),
    '/': ('dividido por', lambda x, y: x / y),
    '**': ('elevado a', lambda x, y: x ** y)
}

while True:
    valor1 = int(input("Insira o primeiro valor: "))
    operacao = input("Insira a operação a ser usada (+ ; -; *; /; **) ")
    valor2 = int(input("Insira o segundo valor: "))

    if operacao in operacoes:
        texto, op = operacoes[operacao]
        print(f'{valor1} {texto} {valor2} é igual a {op(valor1, valor2)}')
    else:
        print('Operação inválida')

    if 'não' == input("Desejar continuar usando a calculdora? Responda sim ou não: "):
        break

The dictionary operacoes maps each operation (+, -, etc) with their respective text and with the account to be made with the numbers (both stored in a tuple).

Within the loop just check if the entered operation exists in the dictionary, and if it exists, use the text and the respective account to display the result.


For arithmetic operations, an option not to create Amble is to use the module operator:

from operator import add, sub, mul, truediv, pow

operacoes = {
    '+': ('somado a', add),
    '-': ('subtraindo', sub),
    '*': ('multiplicado por', mul),
    '/': ('dividido por', truediv),
    '**': ('elevado a', pow)
}

# restante do código igual

Browser other questions tagged

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