5

I would like to be able to validate that the user has entered a valid name within my program. If they have not entered a valid name i want the program to continue to prompt them to enter their name again. If the name entered is valid i would like the program to greet the user.

So far i have:

import re

user_name = input("Please enter your name: ")
if not re.match("^[A-Za-z]*$", user_name):
    print ("Error! Make sure you only use letters in your name")
else:
    print("Hello "+ user_name)

How would i loop this if their name is not valid??

3
  • If you don't want to allow an empty input, I would recommend using ^[A-Za-z]+$ instead of ^[A-Za-z]*$. Commented Nov 23, 2015 at 21:53
  • Limiting your input to ASCII letters does users around the world a disservice. If there are characters you truly can't handle, like spaces, blacklist them, but let your users choose names that are meaningful to them. Commented Nov 24, 2015 at 17:24
  • What are the rules for names that you are trying to enforce, can you enumerate them? Commented May 20, 2021 at 2:54

4 Answers 4

5

Using a while True loop only break out with break if you got a right answer:

while True:
    user_name = input("Please enter your name: ")
    if not re.match("^[A-Za-z]*$", user_name):
        print ("Error! Make sure you only use letters in your name")
    else:
        print("Hello "+ user_name)
        break
Sign up to request clarification or add additional context in comments.

Comments

2
user_name = '1'  #something that doesn't validate
while not re.match("^[A-Za-z]*$", user_name):
    user_name = input("Please enter your name: ")
    print ("Error! Make sure you only use letters in your name")
else:
    print("Hello! "+ user_name)

Comments

0

put everything in a while loop and have the condition your matching statement:

user_name = input("Please enter your name: ")
while not re.match("^[A-Za-z]*$", user_name):
    print ("Error! Make sure you only use letters in your name")
    user_name = input("Please enter your name: ")
print("Hello "+ user_name)

Edit:

using str.isalpha()

while not user_name.isalpha():

2 Comments

Fantastic thank you! I was thinking along those lines but was not sure if i could use not with while. Are their other methods that can be used to validate users only enter letters?
you could use str.isalpha()
0

WARNING: In Python, use "\Z" not "$" to mean "end of string".

In Python the "$" is permissive - it allows at least an extra newline.

Use this pattern instead: "^[A-Za-z]*\Z"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.