0
votes

I am writing a program, part of it requires the input of a name. The name can only be alpha and spaces (eg. John Smith) it cannot be John Smith1 If an invalid character IS entered, I need the program to display an error message and reask the questions. I have got everything but the validation. I'm guessing it goes something like this?

name = str(input("What is the customers name? "))
while True:
    if ??????????????????? :
        print("You have entered an invalid character. Enter only name."
        name = str(input("What is the customers name? "))
    else:
          break

Can someone please fill in the ?????s to make the program work?

5
Tim O'Reilly will not be pleased if he tries to use your program. Neither will 毛澤東. - Tim Pietzcker
@TimPietzcker I think that would be a question for the teacher that proposed the assignment. - Burhan Khalid
I would use a while loop over the if construct in the sample code. - Alex
It only needs to be simple. It doesn't need to have any of those functions. The teacher does not know the answer. - Daniel Nitschke

5 Answers

3
votes

Try the isalpha() method of strings.

Since the person will enter names with spaces, you have two options:

  1. Split the input by the space (use split())
  2. Take advantage of string.letters

For example:

   >>> import string
   >>> string.letters
   'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

Combine that with a ' ' to get your list of allowed characters. Since this is homework, the rest is up to you.

1
votes

You can use the replace method of strings to get rid of white-spaces and then use the isalpha() method.

An example:

>>> def get_name():
...     name = raw_input('name: ')    # use a simple "input" in python3
...     if not name.replace(' ', '').isalpha():
...             print('Bad name!!!')
...     else:
...             print('Good name!')
... 
>>> get_name()
name: My name
Good name!
>>> get_name()
name: Bad Nam3
Bad name!!!
>>> get_name()
name: Jon Skeet
Good name!

Note that this works also with non ascii-letters in python3:

#python3
>>> get_name()
name: Accented è
Good name!
>>> get_name()
name: Bad Nam3
Bad name!!!

Regular expressions are too complicated for this simple task. Also because using [A-Za-z ]+ or similar wont match names with non ASCII letters. And using \w includes digits.

If you don't want to match non-ASCII letters(such as 'è'), then you can try something like this:

>>> def get_name():
...     name = raw_input('name: ')   #input in python3
...     try:
...             name.encode('ascii')
...     except UnicodeDecodeError:
...             print('Bad name!!!')
...             return
...     if not name.replace(' ', '').isalpha():
...             print('Bad name!!!')
...     else:
...             print('Good name!')
... 
>>> get_name()
name: Accented è
Bad name!!!
>>> get_name()
name: The nam3
Bad name!!!
>>> get_name()
name: Guido Van Rossum
Good name!

Finally, an other way to check is this one:

>>> import string
>>> def good_name(name):
...     return not set(name).difference(string.letters + ' ')
... 
>>> good_name('Guivo Van Rossum')
True
>>> good_name('Bad Nam3')
False

And you can use it in this way:

name = raw_input('name: ')   #input in python3
if good_name(name):
   #stuff for valid names
else:
   #stuff for invalid names
0
votes

You might want to look into regular expressions:

^[A-Za-z ]*$

is a regex that only matches strings if they consist entirely of ASCII letters and spaces.

To also allow letters of your current locale:

^[^\W\d_]*$

which is basically the set of alphanumeric characters including accented characters (in the current locale) minus digits and underscore.

0
votes

Use Regular Expressions, something like [A-Za-z ]+

It would translate into something like this, if I use Tim's expression:

match = re.match(r'^[A-Za-z ]*$', name )
if match :
    print("Correct name");
else:
    print("Invalid chars");
-1
votes

To Check the string for alpha I generally use this one. Hope this can help you.

import re
def is_alpha_space(name):
    name_nospace = ''.join((name.split()))
    if re.search(r"\W", name_nospace) or len(name_nospace) < 1:
        return False
    return True
name = "Mark Zumkoff"
print(is_alpha_space(name))  # True
name = "Mark Zumkoff@"
print(is_alpha_space(name))  # False
name = "    "
print(is_alpha_space(name))  # False