Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys, os
- # ============================================================================================================ #
- def fun_SO_es_windows():
- from platform import system
- return system().lower()=="windows" # Windows / Linux / Darwin
- def fun_input(str_mensaje="", typ_retorno=int, str_aceptar="", str_omitir="", int_longitud=0,
- lst_rango=[-9999999,9999999], str_default="", str_mostrar="" ):
- """fun_input............ Iniciado el 25/09/2020 by UCLA
- Función fun_input() Captura datos desde el teclado
- Python en español (principiantes)
- Autor: Luis A. Urbalejo
- Parámetros:
- str_mensaje tipo string, el mensaje a mostrar
- typ_retorno El valor a retornar
- str_aceptar Caracteres que solo aceptará la captura
- str_omitir Caracteres que omitirá al capturar
- int_longitud Tamaño límite de la captura
- lst_rango Una lista de 2 elementos, valor mínimo y máximo
- str_default: (str) Valor por defecto a aparecer en la captura
- str_mostrar (str) Caracter a mostrar en lugar del presionado
- """
- # Para que la función funcione O_o? para windows y linux
- if fun_SO_es_windows():
- from msvcrt import getch, kbhit, putch
- # import msvcrt # Para capturar las teclas presionadas
- int_tecla_enter = 13
- int_tecla_retroceso = 8
- else: # para linux pip install getch
- from getch import getch # , kbhit pta madre.. no existe kbhit en linux
- int_tecla_enter = 10
- int_tecla_retroceso = 127
- def kbhit(): # Así le vamos a hacer para usar kbhit en linux
- return True
- # --------------------------------------------------------------------------------------------------- #
- def fun_teclazo(): # Función que captura una tecla presionada
- bol_espera = True # bandera activa esperando se pulse una tecla...
- while bol_espera: # esta bandera se usará después... paciencia
- if kbhit(): # Si se presionó una tecla
- tecla = getch() # Se guarda en variable tecla
- tecla = tecla.decode("ascii") # tecla decodificada
- if ord(tecla) == int_tecla_enter or ord(tecla) == int_tecla_retroceso:
- return tecla # retorna enter o retroceso (luego veo flechas )
- elif tecla in str_aceptar or str_aceptar == "": # es tecla válida?
- if typ_retorno == int or typ_retorno == float: # Si debe ser numérica, validamos
- if tecla in "+-" and len(str_capturado) != 0: continue
- if tecla == "." and str_capturado.count(".") != 0: continue
- return tecla # retornamos la tecla presionada
- else:
- continue
- # --------------------------------------------------------------------------------------------------- #
- def fun_sololetras():
- str_abc = "".join(chr(str_letra) for str_letra in range(65,91)) + " ."
- str_abc += "".join(chr(str_letra) for str_letra in range(97,123))
- return str_abc
- # --------------------------------------------------------------------------------------------------- #
- def fun_solonumeros():
- return "0123456789.-+"
- # --------------------------------------------------------------------------------------------------- #
- if str_aceptar == str: str_aceptar = fun_sololetras()
- if str_aceptar == int: str_aceptar = fun_solonumeros()
- if str_omitir == str: str_omitir = fun_sololetras()
- if str_omitir == int: str_omitir = fun_solonumeros()
- if typ_retorno == int or typ_retorno == float:
- if str_aceptar == "": # Si no se pasa parámetro de caracteres a aceptar
- str_aceptar = fun_solonumeros() # Solo debe aceptar números
- if 2 < len(lst_rango) > 2:
- input(lst_rango)
- lst_rango = [-9999999,9999999]
- str_capturado = str(str_default) # Inicializamos lo que se va a capturar
- while "Mientras no se presione enter...":
- if str_mostrar == "":
- str_captura2 = str_capturado
- else:
- str_captura2 = len(str_capturado) * str_mostrar
- print("\r" + (" " * len(str_mensaje + str_captura2)), end="") # Limpia la línea
- print(f"\r{str_mensaje}{str_captura2}", end="") # Imprime mensaje + lo capturado
- # La sgte línea verifica si hay parámetro de longitud y ha llegado al límite
- if int_longitud > 0 and len(str_capturado) == int_longitud:
- tecla = chr(int_tecla_enter)
- else:
- tecla = fun_teclazo() # Esperar que se presione una tecla
- if tecla in str_omitir: continue # Si no es válido el caracter, regresa al inicio del while
- if ord(tecla) == int_tecla_enter:
- if typ_retorno == int or typ_retorno == float:
- if str_capturado == "": str_capturado = "0" # si nada capturado, ponemos cero
- str_capturado = typ_retorno(float(str_capturado)) # Convertimos entrada en entero o flotante según el caso
- if not (lst_rango[0] <= str_capturado <= lst_rango[1]):
- str_capturado = str(str_capturado)[:-1]
- continue
- break # tecla enter presionada... fin
- if ord(tecla) == int_tecla_retroceso: # tecla back space presionada
- str_capturado = str_capturado[:-1] # Borramos el ultimo caracter
- else: # de lo contrario se agregará la tecla preionada
- str_capturado += tecla
- print(f"\r{str_mensaje}{str_captura2}", end="")
- print() # El salto de línea final
- return str_capturado # Retorna la cadena capturada
- str_NIP = fun_input("NIP: ", typ_retorno=int, int_longitud=4, str_mostrar="*" )
- print(str_NIP)
- sys.exit()
- # Pedir 4 calificaciones parciales
- # Obtener Promedio General e imprimirlo
- flt_promedio = 0
- for i in range(4):
- flt_parcial = fun_input(f"Calificación parcial {i + 1} (5-10): ",
- typ_retorno=float, lst_rango=[5,10], str_default=9 )
- flt_promedio += flt_parcial
- flt_promedio /= 4
- print(f"Promedio: {flt_promedio}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement