简体   繁体   中英

How do you prevent user from entering gibberish into user input and prevent them from using all caps or all lower case letters?

I am trying to make an input that would prevent a user entering an input like this "QWERTY" this "qwerty" or this "QW3RTY" The input is for names so I want to make sure that it would need the user to have a capital letter at the start of their name "John" not "john"

I have tried to loop the question using while True: try and attempted to use .isalpha and .title but I couldnt seem to make it work

while True:
    try:
        name = input(str("What is your name? "))
    if name is not name.isalpha:
        print("Please Enter a Valid name")
        continue
    if name is not name.title:
        print("Please have a capital letter at the start of your name!")
        continue
    else:
        break

I expected for the if statements to work but it comes up with invalid syntax.

Your logic is faulty ... but you've replicated it, even though the first if failed. Correct your problems one at a time, rather than trying to write the whole program at once.

name is a string; name.isalpha is a function.
A string cannot ever be identical to a function.

I think what you want is

if name.isalpha():

Also, try requires an except clause to catch exceptions. Again, add program features individually. That way, when you hit an error, you'll be fixing only that one error.

See this lovely debug blog for help.

Implementing features one at a time is a much better place to start than to try to catch everything all at once. Also, make sure to call your functions, otherwise, they will be truthy:

if str:
    print("True!")
else:
    print("False!")

True!

# compared to 
if str():
    print("True!")
else:
    print("False!")

False!

Functions are objects, and will not act Falsey.

while True:
    name = input("What is your name? ") # no need for str function here

    # you can wrap this whole thing in a
    # try/except for ValueError
    try:
        if name.isupper() or name.islower() or not name == name.title():
            raise ValueError("Please include proper capitalization")
        elif not name.isalpha():
            raise ValueError("Use only alphabetical characters, please")
        else:
            break
    except ValueError as e:
        print(e)

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