Validate a field in python

1

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 I ask you for a letter, I only accept certain letters and I ask you to ask for it again.

    
asked by ElAlien123 05.01.2018 в 07:25
source

1 answer

1

You can do the following:

def input_float(msg="Ingrese un número:"):
  """Valida que el input ingresado por el usuario sea un float 
     sino vuelve a solictar el ingreso"""

  while True:
       cadena = input(msg)
       try:
          valor = float(cadena)
       except ValueError:
          print("El valor ingresado '{0}' no es un número de coma flotante! Intente nuevamente.".format(cadena))
          continue
       else:
          return valor
          break 

numero_uno = input_float("introduce un número:")

I have just defined a input_float function that what it does is to request the user to enter a data until it is a value that can be converted to a float . We achieve this through an infinite cycle ( while True: ) that will only come out if the value entered can be converted. To treat the entered string we use an Exceptions control (block try: .. except .. else ) in case a string can not be transformed into a float ( valor = float(cadena) ) an exception ValueError that we control will be sent to be able to report that the value entered is incorrect, and we repeat the cycle again. In case the entered value is correct, we will leave the function returning the value already converted to float .

Simply replace the entry instructions in your code:

numero_uno = input_float("introduce un número:")
numero_dos = input_float("introduce otro número:")
    
answered by 05.01.2018 / 14:49
source