0
characters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
"o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "-", "'", " ", "*"]
def enter_first_name():
while True:
    first_name = input("Enter your first name: ").lower().rstrip().lstrip()
    for i in first_name:
        if i in characters:
            print(i)
            return first_name
        else:
            print("ERROR! Invalid entry.")

The print(i) is there to check that it's working properly but all it prints is the first letter from whatever the user inputs as their name. The purpose is so that if someone were for example to accidentally type a number in their name (any symbol not included in the list characters) that it returns "ERROR! Invalid entry." and prompts them to enter their name again.

What am I doing wrong and how can I go through each letter from the input to ensure it's a valid entry?

Thank you!

2
  • Try removing return first_name from the if-statement, and putting it outside of the for-loop Commented Jul 6, 2018 at 14:33
  • First, characters should be a set, for O(1) lookup, second, you are returning after the first iteration of your loop if the user has entered a valid character. Commented Jul 6, 2018 at 14:35

2 Answers 2

1

You can use all to check if all the characters from your input are in the whitelist.

from string import ascii_lowercase

characters = set(ascii_lowercase + " -*'")

def enter_first_name():
    while True:
        first_name = input("Enter your first name: ").lower().strip()
        if all(i in characters for i in first_name)
                return first_name
        else:
            print("ERROR! Invalid entry.")
Sign up to request clarification or add additional context in comments.

Comments

1

You need to remove return first_name. You should never call a return unless the function has finished 100%. Here you are calling it on the first loop iteration, meaning the function will finish after checking the first character in the first name.

characters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
"o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "-", "'", " ", "*"]
def enter_first_name():
    while True:
         first_name = input("Enter your first name: ").lower().rstrip().lstrip()
         for i in first_name:
             if i in characters:
                 print(i)
            else:
                 print("ERROR! Invalid entry.")

When you remove the return first_name it verifies each character as expected.

Output:

Enter your first name: trevor
t
r
e
v
o
r
Enter your first name: trevor!
t
r
e
v
o
r
ERROR! Invalid entry.
Enter your first name:

1 Comment

This never actually returns the validated input, which is presumably the point of the function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.