Grace Parker
Grace Parker

Reputation: 1

User Input Against a List - Python

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!

Upvotes: 0

Views: 307

Answers (2)

ltd9938
ltd9938

Reputation: 1454

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:

Upvotes: 1

Patrick Haugh
Patrick Haugh

Reputation: 60944

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.")

Upvotes: 1

Related Questions