PYTHON BASIC CALCULATOR
Objective:
Build a basic Python calculator that can perform addition, subtraction, multiplication, and division. It provides flexible modes: one-time calculation, repeating the same operation with fixed inputs, or running continuously until the user exits.
How it works:
Define calculator function: Create a function that takes two numbers and an operator, then performs the corresponding calculation with error handling for division by zero.
Collect user input: Ask the user to enter two numbers and an operator, then call the calculator function to display the result.
Simplify repeated operations: Allow the program to automatically perform all four operations (+, −, *, /) using the same two input numbers without re-entering values.
Enable continuous mode: Use a loop that repeatedly asks the user for two numbers, allows them to type «salir» to quit, and validates input to ensure it’s numeric.
Handle invalid inputs: If the user enters non-numeric values, catch the error and prompt them again, ensuring the program doesn’t crash.
Repeat calculations automatically: In continuous mode, the program performs addition by default after each valid pair of numbers, making the calculator always available until the user exits.
# Objetivo: crear una calculadora básica
print("¡Bienvenido a mi calculadora básica! Puedes sumar (+), restar (-), multiplicar (*) o dividir (/).")
def calculadora(num1, operador, num2):
print("¡Oh, calcular eso es muy fácil!")
if operador == "+":
print(num1 + num2)
elif operador == "-":
print(num1 - num2)
elif operador == "*":
print(num1 * num2)
elif operador == "/":
if num2 == 0:
print("Error: has dividido por 0")
else:
print(num1 / num2)
else:
print("Algo ha ido mal")
numero1 = float(input("Número 1: "))
operación = input("Operación: ")
numero2 = float(input("Número 2: "))
calculadora(numero1, operación, numero2)
# SIMPLIFICAR SI SIEMPRE QUIERO HACER SIEMPRE LA MISMA OPERACIÓN:
numero1 = float(input("Número 1: "))
numero2 = float(input("Número 2: "))
calculadora(numero1, "+", numero2)
calculadora(numero1, "-", numero2)
calculadora(numero1, "*", numero2)
calculadora(numero1, "/", numero2)
# ¿QUIERO HACERLO CONSTANTEMENTE?:
while True:
entrada1 = input("Número 1 (o pulsa salir): ").lower()
if entrada1 == "salir":
break
entrada2 = input("Número 2 (o pulsa salir): ").lower()
if entrada2 == "salir":
break
try:
numero1 = float(entrada1)
numero2 = float(entrada2)
except ValueError:
print("Error. Ingresa numeros válidos o sal del programa.")
calculadora(numero1, "+", numero2)