Like isalpha()
returns True
only if all characters are letters, and the name can have letters and spaces, then the way is to check the characters one by one. So:
while True:
name = input("Digite seu nome: ")
if all(c.isalpha() or c.isspace() for c in name):
break # sai do while
else:
print("Por favor digite um nome válido (somente letras e espaços)")
I use all
, returning True
if all the characters in the strings meet the condition (which in this case is c.isalpha() or c.isspace()
, i.e., "is a letter or a space".
If all characters are in this condition, the break
interrupts the loop. Otherwise, the error message is printed and asked to type again.
Just remembering that isalpha
is very comprehensive and also considers letters from other alphabets (Japanese, Russian, Arabic, etc.), and isspace
also considers line breaks, TAB, among others.
If you want to be more restricted, just create a string containing only the valid characters and use it in the test:
from string import ascii_letters
# acrescentei o espaço e algumas letras acentuadas, adicione tudo que precisar aqui
validos = ascii_letters + ' áéíóú'
while True:
name = input("Digite seu nome: ")
if all(c in validos for c in name):
break # sai do while
else:
print("Por favor digite um nome válido (somente letras e espaços)")
In the above example I used the letters ASCII (all letters from "a" to "z", uppercase and lowercase), and added the space and some accented letters. So just add all the characters you need there.
The use of isalpha was not to receive numbers or special characters in the name, I was not aware that isalpha nullified the spaces. As for the True problem I noticed this too and I already tidied up this part of the code, but in this case, how I would make this input receive only letters and spaces?
– Italo Almeida
I think it’s become clearer now.
– Italo Almeida