Advertisement
uclagyl

fun_input( ) desde cero

Sep 17th, 2023 (edited)
936
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.20 KB | Source Code | 0 0
  1. import sys, os
  2.  
  3. # ============================================================================================================ #
  4. def fun_SO_es_windows():
  5.     from platform import system
  6.     return system().lower()=="windows"  # Windows / Linux / Darwin
  7.  
  8. def fun_input(str_mensaje="", typ_retorno=int, str_aceptar="", str_omitir="", int_longitud=0,
  9.               lst_rango=[-9999999,9999999], str_default="", str_mostrar="" ):
  10.     """fun_input............ Iniciado el 25/09/2020 by UCLA
  11.    Función fun_input() Captura datos desde el teclado
  12.    Python en español (principiantes)
  13.    Autor: Luis A. Urbalejo
  14.  
  15.    Parámetros:
  16.    str_mensaje     tipo string, el mensaje a mostrar
  17.    typ_retorno     El valor a retornar
  18.    str_aceptar     Caracteres que solo aceptará la captura
  19.    str_omitir      Caracteres que omitirá al capturar
  20.    int_longitud    Tamaño límite de la captura
  21.    lst_rango       Una lista de 2 elementos, valor mínimo y máximo
  22.    str_default:    (str)   Valor por defecto a aparecer en la captura
  23.    str_mostrar     (str)   Caracter a mostrar en lugar del presionado
  24.    """
  25.  
  26.     # Para que la función funcione O_o? para windows y linux    
  27.     if fun_SO_es_windows():
  28.         from msvcrt import getch, kbhit, putch
  29.         # import msvcrt  # Para capturar las teclas presionadas
  30.         int_tecla_enter = 13
  31.         int_tecla_retroceso = 8
  32.     else:   # para linux pip install getch
  33.         from getch import getch     # , kbhit pta madre.. no existe kbhit en linux
  34.         int_tecla_enter = 10
  35.         int_tecla_retroceso = 127
  36.         def kbhit():    # Así le vamos a hacer para usar kbhit en linux
  37.             return True
  38. # --------------------------------------------------------------------------------------------------- #
  39.     def fun_teclazo():  # Función que captura una tecla presionada
  40.         bol_espera = True   # bandera activa esperando se pulse una tecla...
  41.         while bol_espera:   # esta bandera se usará después... paciencia
  42.             if kbhit():     # Si se presionó una tecla
  43.                 tecla = getch() # Se guarda en variable tecla
  44.                 tecla = tecla.decode("ascii")  # tecla decodificada
  45.                 if ord(tecla) == int_tecla_enter or ord(tecla) == int_tecla_retroceso:
  46.                     return tecla    # retorna enter o retroceso (luego veo flechas )
  47.                 elif tecla in str_aceptar or str_aceptar == "":    # es tecla válida?
  48.                     if typ_retorno == int or typ_retorno == float:  # Si debe ser numérica, validamos
  49.                         if tecla in "+-" and len(str_capturado) != 0:  continue
  50.                         if tecla == "." and str_capturado.count(".") != 0: continue
  51.                     return tecla    # retornamos la tecla presionada
  52.                 else:
  53.                     continue
  54. # --------------------------------------------------------------------------------------------------- #
  55.     def fun_sololetras():
  56.         str_abc = "".join(chr(str_letra) for str_letra in range(65,91)) + " ."
  57.         str_abc += "".join(chr(str_letra) for str_letra in range(97,123))
  58.         return str_abc
  59. # --------------------------------------------------------------------------------------------------- #
  60.     def fun_solonumeros():
  61.         return "0123456789.-+"
  62. # --------------------------------------------------------------------------------------------------- #        
  63.     if str_aceptar == str:  str_aceptar = fun_sololetras()
  64.     if str_aceptar == int:  str_aceptar = fun_solonumeros()
  65.     if str_omitir == str:   str_omitir = fun_sololetras()
  66.     if str_omitir == int:   str_omitir = fun_solonumeros()
  67.  
  68.     if typ_retorno == int or typ_retorno == float:
  69.         if str_aceptar == "":   # Si no se pasa parámetro de caracteres a aceptar
  70.             str_aceptar = fun_solonumeros()   # Solo debe aceptar números
  71.         if 2 < len(lst_rango) > 2:
  72.             input(lst_rango)
  73.             lst_rango = [-9999999,9999999]
  74.     str_capturado = str(str_default)  # Inicializamos lo que se va a capturar
  75.    
  76.     while "Mientras no se presione enter...":
  77.         if str_mostrar == "":
  78.             str_captura2 = str_capturado
  79.         else:
  80.             str_captura2 = len(str_capturado) * str_mostrar
  81.         print("\r" + ("  " * len(str_mensaje + str_captura2)), end="") # Limpia la línea
  82.         print(f"\r{str_mensaje}{str_captura2}", end="")    # Imprime mensaje + lo capturado
  83.         # La sgte línea verifica si hay parámetro de longitud y ha llegado al límite
  84.         if int_longitud > 0 and len(str_capturado) == int_longitud:
  85.             tecla = chr(int_tecla_enter)
  86.         else:
  87.             tecla = fun_teclazo()      # Esperar que se presione una tecla
  88.         if tecla in str_omitir: continue    # Si no es válido el caracter, regresa al inicio del while
  89.         if ord(tecla) == int_tecla_enter:  
  90.             if typ_retorno == int or typ_retorno == float:
  91.                 if str_capturado == "": str_capturado = "0"  # si nada capturado, ponemos cero
  92.                 str_capturado = typ_retorno(float(str_capturado))    # Convertimos entrada en entero o flotante según el caso
  93.                 if not (lst_rango[0] <= str_capturado <= lst_rango[1]):
  94.                     str_capturado = str(str_capturado)[:-1]
  95.                     continue
  96.             break   # tecla enter presionada... fin
  97.         if ord(tecla) == int_tecla_retroceso:       # tecla back space presionada
  98.             str_capturado = str_capturado[:-1]  # Borramos el ultimo caracter
  99.         else:    # de lo contrario se agregará la tecla preionada
  100.             str_capturado += tecla
  101.            
  102.     print(f"\r{str_mensaje}{str_captura2}", end="")    
  103.     print() # El salto de línea final
  104.     return str_capturado    # Retorna la cadena capturada
  105.  
  106.  
  107. str_NIP = fun_input("NIP: ", typ_retorno=int, int_longitud=4, str_mostrar="*" )
  108. print(str_NIP)
  109.  
  110.  
  111. sys.exit()
  112. # Pedir 4 calificaciones parciales
  113. # Obtener Promedio General e imprimirlo
  114.  
  115. flt_promedio = 0
  116. for i in range(4):
  117.     flt_parcial = fun_input(f"Calificación parcial {i + 1} (5-10): ",
  118.                             typ_retorno=float, lst_rango=[5,10], str_default=9 )
  119.     flt_promedio += flt_parcial
  120. flt_promedio /= 4
  121. print(f"Promedio: {flt_promedio}")
  122.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement