In Python 3.x input
always return a string. You do not need to cast str
, it already is. If you want the input
to not contain numeric characters you must validate the chain and act accordingly (throwing an exception or asking for the data again). Depending on what you want you can use str.isalpha
, str.isnumeric()
or regular expressions for more complex things.
class Nomina:
def __init__(self):
self.nombre_empleado = ""
def obtenerDatos (self):
nombre = input("EL NOMBRE DEL EMPLEADO ES : ")
if nombre.isalpha():
self.nombre_empleado = nombre
else:
print("pasa")
def mostrarDatos (self):
print("-----------------------------------------")
print("LOS DATOS PARA SU LIQUIDACION SON :")
print("-----------------------------------------")
print("Nombre del Empleado :", self.nombre_empleado)
In this case with isalpha
any text entered that contains a character that is not between A-Z and a-z including the space will be invalid. With isnumeric
texts like 'Ramon1' are valid but not '123' would not be.
Generally the most flexible option is regular expressions, for example, to validate names of the type 'Antonio Jesús Cañamero' you will need to include the accents, the ñ and the spaces in the validation:
import re
class Nomina:
def __init__(self):
self.nombre_empleado = ""
def obtenerDatos (self):
nombre = input("EL NOMBRE DEL EMPLEADO ES : ")
if re.match("^[A-Za-z áéíóúÁÉÍÓÚñÑ]*$", nombre):
self.nombre_empleado = nombre
else:
print("pasa")
def mostrarDatos (self):
print("-----------------------------------------")
print("LOS DATOS PARA SU LIQUIDACION SON :")
print("-----------------------------------------")
print("Nombre del Empleado :", self.nombre_empleado)
a = Nomina()
a.obtenerDatos()
You can create your customized expression to accept or not other things like _
, -
, @
, .
, ,
etc.
Edit:
If you want to ask for the name until it is valid you must use an infinite cycle to ask for input
until it is validated:
import re
class Nomina:
def __init__(self):
self.nombre_empleado = ""
def obtenerDatos (self):
while not self.nombre_empleado:
nombre = input("EL NOMBRE DEL EMPLEADO ES : ")
if re.match("^[A-Za-z áéíóúÁÉÍÓÚñÑ]*$", nombre):
self.nombre_empleado = nombre
else:
print("NOMBRE INVÁLIDO")
def mostrarDatos (self):
print("-----------------------------------------")
print("LOS DATOS PARA SU LIQUIDACION SON :")
print("-----------------------------------------")
print("Nombre del Empleado :", self.nombre_empleado)
a = Nomina()
a.obtenerDatos()