Problem with calculator in Python 3.7

1

I have a question I'm doing an exercise of a calculator in Python 3.7. I have the logic created and the calculator works correctly but I have the following doubt: How do I ask the user if he wants to perform another operation and in the case of being IF he returns to choose the number of the operation he wants to perform and if he does not circulate the program?

I leave the code I have made. I apologize if the code is too long but I am learning this language and I am really new to programming.

Thanks in advance to the people who respond

#Calculadora
print("Bienvenido a la calculadora")
print("Estas son las operaciones que puedes realizar")
print("1 - Suma")
print("2 - Resta")
print("3 - Multiplicación")
print("4 - División")

numero_uno = ()
numero_dos = ()
resultado = ()
operacion = int(input("Introduce el numero de la operación que deseas 
realizar: "))
if operacion == 1:
    try:
    numero_uno = int(input("Ingrese el primer número: "))
    numero_dos = int(input("Ingreso el segundo número: "))
except ValueError:
    print("Ese no es un número")
else:
    resultado = numero_uno + numero_dos
    print("El resultado de la suma es : " + str(resultado))
elif operacion == 2:
try:
    numero_uno = int(input("Ingrese el primer número: "))
    numero_dos = int(input("Ingreso el segundo número: "))
except ValueError:
    print("Ese no es un número")
else:
    resultado = numero_uno - numero_dos
    print("El resultado de la resta es : " + str(resultado))
elif operacion == 3:
    try:
    numero_uno = int(input("Ingrese el primer número: "))
    numero_dos = int(input("Ingreso el segundo número: "))
except ValueError:
    print("Ese no es un número")
else:
    resultado = numero_uno * numero_dos
    print("El resultado de la multiplicacion es : " + str(resultado))
elif operacion == 4:
    try:
    numero_uno = int(input("Ingrese el primer número: "))
    numero_dos = int(input("Ingreso el segundo número: "))
except ValueError:
    print("Ese no es un número")
else:
    resultado = numero_uno / numero_dos
    print("El resultado de la división es : " + str(resultado))
continuar = input("Desea continuar? SI/NO ")
    
asked by Carlos Code 08.12.2018 в 07:20
source

2 answers

1

I have created an auxiliary function that creates an infinite loop that asks you if you want to continue or not (this is what you asked for, I think), but although Ale's answer is valid, I think it can be improved in many aspects.

Good habits:
There is a lot of code repeated, but very much. Try to get in the habit of not repeating the same line so many times, especially when you are learning to program. As a general rule, if you need to repeat it 3 times or more, it is better to create a function and call it several times.
I have taken the liberty to re-structure your code by improving the parts that I thought needed to be improved to demonstrate the latter.

The first thing is to create auxiliary functions to eliminate the use of repetitions in the code. But instead of just encapsulating that code, I have eliminated the try/except because although it is common to use it, it can give way to unexpected errors. As a tip, always look for a way that you do not need to use try/except . In this case it is as simple as seeing if the string contains only digits: string.isdigit

Important note : I have been adding numbered notes so that you know in what order exactly each part of the code is executed. Any questions, tell me.

# 5 - Funcion que evalua si una string consiste solo en números,
# y sino, entra en bucle hasta que lo sea
def valida_que_sean_numeros(texto):
    numero = input(texto)
    while not numero.isdigit():
        print("Ese no es un número, prueba de nuevo.")
        numero = input(texto)
    return int(numero)

# 8 - Funcion auxiliar que evalua si quieres continuar usando la calculadora o no
def continuar(texto):
    respuesta = input(texto)
    while not respuesta.lower() == "no":
        if respuesta.lower() == "si":
            return True
        else:
            print("Esa no es una opción, prueba de nuevo.")
            respuesta = input(texto)
    return False

# 3 - Funcion principal
def calculadora():
    # 4 - Nos aseguramos de que nuestras 3 variables vayan a ser numeros
    operacion = valida_que_sean_numeros("Introduce el numero de la operación que deseas realizar: ")
    numero_uno = valida_que_sean_numeros("Ingrese el primer número: ")
    numero_dos = valida_que_sean_numeros("Ingrese el segundo número: ")
    # 6 - Seleccionamos la operación adecuada y damos el resultado.
    if operacion == 1:
            resultado = numero_uno + numero_dos
            print("El resultado de la suma es : " + str(resultado))
    elif operacion == 2:
            resultado = numero_uno - numero_dos
            print("El resultado de la resta es : " + str(resultado))
    elif operacion == 3:
            resultado = numero_uno * numero_dos
            print("El resultado de la multiplicacion es : " + str(resultado))
    elif operacion == 4:
            resultado = numero_uno / numero_dos
            print("El resultado de la división es : " + str(resultado))
    # 7 - Usamos la función auxiliar en bucle de Continuar para obtener una respuesta válida
    continuamos = continuar("Desea continuar? SI/NO ")
    if continuamos:
        calculadora() # 9 - Si la respuesta es válida, ejecutamos la funcion calculadora de nuevo,
                      # esto es lo que mantiene el bucle activo de forma infinita hasta que queramos cerrarlo

# 1 - Instrucciones
print("Bienvenido a la calculadora"
      "\nEstas son las operaciones que puedes realizar"
      "\n1 - Suma"
      "\n2 - Resta"
      "\n3 - Multiplicación"
      "\n4 - División")
# 2 - Ejecutamos la calculadora
calculadora()

Curiosities:
You can do line breaks by typing \n , so you do not have to call the function print 5 times, just call it once but with line breaks, which will make it run faster because we are not using it 5 different functions, only one.

I purposely left one thing unfixed so that you look for the best way to do it: Try placing a 5 as an operation and you will see the problem hehe.

    
answered by 08.12.2018 / 14:31
source
1

I would try something like this:

def calculadora(operacion):
    numero_uno = ()
    numero_dos = ()
    resultado = ()

    if operacion == 1:
    try:
        numero_uno = int(input("Ingrese el primer número: "))
        numero_dos = int(input("Ingreso el segundo número: "))
    except ValueError:
        print("Ese no es un número")
    else:
        resultado = numero_uno + numero_dos
        print("El resultado de la suma es : " + str(resultado))
    elif operacion == 2:
    try:
        numero_uno = int(input("Ingrese el primer número: "))
        numero_dos = int(input("Ingreso el segundo número: "))
    except ValueError:
        print("Ese no es un número")
    else:
        resultado = numero_uno - numero_dos
        print("El resultado de la resta es : " + str(resultado))
    elif operacion == 3:
        try:
        numero_uno = int(input("Ingrese el primer número: "))
        numero_dos = int(input("Ingreso el segundo número: "))
    except ValueError:
        print("Ese no es un número")
    else:
        resultado = numero_uno * numero_dos
        print("El resultado de la multiplicacion es : " + str(resultado))
    elif operacion == 4:
        try:
        numero_uno = int(input("Ingrese el primer número: "))
        numero_dos = int(input("Ingreso el segundo número: "))
    except ValueError:
        print("Ese no es un número")
    else:
        resultado = numero_uno / numero_dos
        print("El resultado de la división es : " + str(resultado))

if __name__ == '__main__':
    print("Bienvenido a la calculadora")

    while True:
        print("Estas son las operaciones que puedes realizar")
        print("1 - Suma")
        print("2 - Resta")
        print("3 - Multiplicación")
        print("4 - División")

        operacion = int(input("Introduce el numero de la operación que deseas 
        realizar: "))

        calculadora(operacion)

        continuar = input("Desea continuar? SI/NO ")

        if continuar == "NO":
            break

This restructuring isolates the functionality of the calculator in an independent function. To ask the user if he wants to start over, a while True is used, which will repeat the whole process until the user answers NO .

If you need more information about the condition __name__ == '__main__' you have it in this answer .

    
answered by 08.12.2018 в 09:16