# 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("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 = ()
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:
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:
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:
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:
continuar = input("Desea continuar? SI/NO ")
``````

asked by Carlos Code 08.12.2018 в 07:20
source

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
# 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: ")
if operacion == 1:
elif operacion == 2:
elif operacion == 3:
elif operacion == 4:
# 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
"\nEstas son las operaciones que puedes realizar"
"\n1 - Suma"
"\n2 - Resta"
"\n3 - Multiplicación"
"\n4 - División")
# 2 - Ejecutamos la 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.

source
1

I would try something like this:

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

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:
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:
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:
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:

if __name__ == '__main__':

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: "))

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 .