this is my code:
from math import *
import os
import time
import sys
salir = False
print("por favor no escribir cosas no relacionadas o el programa dara error")
print("cargando...")
time.sleep(3)
os.system('cls')
while not salir:
numero_uno = float(input("introduce un número:"))
os.system('cls')
operacion = (input("\n\n'a' para realizar una suma(ejemplo: 9 + 6 = 15)\n\n'b' para realizar una resta(ejemplo: 7 - 3 = 4)\n\n'c' para realizar una multiplicación(ejemplo: 5 * 6 = 30)\n\n'd' para realizar una división 'normal'(ejemplo: 9 / 5 = 1.8)\n\n'e' para obtener el cociente(entero) de la división(ejemplo: 9 // 5 = 1)\n\n'f' para obtener solo el resto de una división(ejemplo: 9 % 5 = 4)\n\n'g' para elevar a una potencia(ejemplo: 3 ** 3 = 27)\n\nintroduce la operación a realizar:"))
os.system('cls')
numero_dos = float(input("introduce otro número:"))
os.system('cls')
if operacion == 'a':
print(numero_uno + numero_dos)
if operacion == 'b':
print(numero_uno - numero_dos)
if operacion == 'c':
print(numero_uno * numero_dos)
if operacion == 'd':
print(numero_uno / numero_dos)
if operacion == 'e':
print(numero_uno // numero_dos)
if operacion == 'f':
print(numero_uno % numero_dos)
if operacion == 'g':
print(numero_uno ** numero_dos)
input()
os.system('cls')
reiniciar = input("desea realizar otra operación? si/no: ")
if reiniciar == "si":
os.system('cls')
elif reiniciar == "no":
salir = True
I want that when it asks you for a letter it only accepts certain letters and asks for it again.
You can do the following:
I just defined a function
input_float
that what it does is ask the user to enter a data until it is a value that can be converted to afloat
. We achieve this by using an infinite loop (while True:
) that will only exit if the input value can be converted. To treat the entered string we use an Exceptions control, (blocktry: .. except .. else
) in case a string cannot be transformed into afloat
(valor = float(cadena)
) an exception will be thrownValueError
that we control to be able to report that the entered value is incorrect, and we repeat the cycle again. If the entered value is correct, we will exit the function returning the value already converted tofloat
.All you have to do is replace the input instructions in your code: