简体   繁体   中英

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!

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM