1

I am at the part where I ask the user for their name. So far I got this:

# Import stuff
import time

# Create empty variable
Name = ""

# Ask their name
while Name = ""
    Name = input("What is your name? ")
    print("")
print(Name)
print("")
time.sleep(3)

So if the user inputs nothing, it repeats the question. But when the user inputs an integer or a float it registers this as a valid name.

How will I be able to make it so that if the Name variable is an integer or a float, it will respond with "Please enter a valid name" and repeat the question?

Caeruleas
  • 21
  • 1
  • 4

5 Answers5

2

I'm updating my answer to simplify the code and make it more readable.

The below function is a function that I would use in my own code, I would consider it to be more "proper" than my old answer.

from string import ascii_letters

def get_name():
    name = input("What is your name?\n: ").strip().title()

    while not all(letter in ascii_letters + " -" for letter in name):
        name = input("Please enter a valid name.\n: ").strip().title()

    return name

To break this down, the line all(letter in ascii_letters + " -" for letter in name) means "if each letter in name is not an alphabetical character, a space, or a hyphen".

The part letter in ascii_letters + " -" checks to see if a letter is in the string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -".

This is repeated by the next part, for letter in name, for every character in the string. This will effectively return a list of booleans, [True, True, True, ...] where any False is a character that did not pass the conditional. Next, this list is passed to the all() function, which returns True if all of the list items are True.

After the all() is executed, conditional is reversed, allowing the loop to continue on the existence of a single failed character.


Old answer is as follows, it will still be useful.

This function should work well for you. Simply check if the string the user entered is alpha characters only, otherwise ask again.

Notice the use of str.isalpha().

def get_name():
    name = input("What is your name?\n: ").strip().title()

    while not (name.replace("-", "") and
               name.replace("-", "").replace(" ", "").isalpha()):
        name = input("Please enter a valid name.\n: ").strip().title()

    return name

Checking if name will check if the string is empty, and using str.strip() on the values returned will remove any surrounding whitespace (stray spaces) to the left or right of the user input.

The str.replace("-", "") eliminates hyphens while checking validity. Thanks for pointing this out @AGN Gazer.

Now you can just call the function later in your script, or store it for later.

name = get_name().title()

print("You said your name was " + name + ".)

The str.title() converts the letter of each word in a string to uppercase. For example, if I entered my name "jacob birkett", the output (and subsequent value of name would be "Jacob Birkett".

Take a look at the documentation for str.isalpha(), str.strip(), str.replace() and str.title().

Jacob Birkett
  • 1,927
  • 3
  • 24
  • 49
  • Wow thanks a lot, although I have come across a problem when testing your code. It only seems to work the second time I input something. The first time it asks the question nothing seems to work. – Caeruleas Jun 08 '18 at 06:09
  • @Caeruleas Fixed. Thanks for pointing that out. See my edited answer. – Jacob Birkett Jun 08 '18 at 06:15
  • Well, although this is the accepted answer, I don't think it's the correct way to check. Names like Mary-Ann would not be accepted, same for names like Kim Robert. – Tobias Brösamle Jun 08 '18 at 06:21
  • @spikespaz Thanks a lot! This solved my question. I appreciate the extra info to help better explain your answer as well :) – Caeruleas Jun 08 '18 at 06:22
  • @TobiasBrösamle Reload your page and see my edit. This is fixed. – Jacob Birkett Jun 08 '18 at 06:22
  • Sorry, missed that. But you would also have to add spaces. And then, the code looks a little messy. – Tobias Brösamle Jun 08 '18 at 06:23
  • @TobiasBrösamle What do you mean "add spaces"? The strings are not mutable; the result will pass the check because the replacement is performed only within the conditional evaluation. The output would include the hyphens. – Jacob Birkett Jun 08 '18 at 06:25
  • @spikespaz sorry to bother you again but typing "Jacob Grey" is not a valid name because it has the space in the middle? "Jacob-Grey" works though. – Caeruleas Jun 08 '18 at 06:46
  • @Caeruleas Fixed. That was a stupid oversight of me. – Jacob Birkett Jun 08 '18 at 06:50
  • @Caeruleas I've updated the answer with a much less convoluted function at the top. Either will work, but I don't know which one is more performant. Probably the bottom one, because the `str.isalpha()` is executed in C, but the top one is much nicer to read. – Jacob Birkett Jun 08 '18 at 07:12
0

You can use a function like .isalpha() as this will return True if all the string contains all the alphabets:

while True:
    Name = input("Please enter a valid name.\n: ")
    if name.isalpha()
        break
    else:
        print("Please enter a valid name.")
        continue

    print(Name)

Or You can try exception handling in python as (but this should be prevented):

try :
    int(Name)
    print("Please enter a valid name")
    ...

except:
    print("Accepted")
    ...

This will check if the input is an integer print the error.

Rajat Jain
  • 1,339
  • 2
  • 16
  • 29
  • You shouldn't be using try/except for these things. This is simple enough to do without catching a thrown error, and suppressing errors should not be your first line-of-attack when validating user input. – Jacob Birkett Jun 08 '18 at 05:57
  • Thank You, I have edited the answer accordingly. – Rajat Jain Jun 08 '18 at 06:01
0

You can try this :

while Name == "" or Name.isnumeric() == True:
    Name = input("What is your name? ")
    print("")

Here if the Name is any numeric value it will ask again, But if the name is like alphanumeric it will accept.

Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33
0

You can try: This will check if variable Name containing numeric data or not.

import time
Name = ""
while Name == "" :
    Name = input("What is your name? ")
    if not Name.isalpha():
        print "It is containing numberic characher or characters"
        Name = ""
    print("")

print(Name)
print("")
time.sleep(3)

You also can try if name is like "harsha-biyani":

import time
Name = ""
while Name == "" :
    Name = input("What is your name? ")
    if any(i.isdigit() for i in Name):
        print "It is containing numberic characher or characters"
        Name = ""
    print("")

print(Name)
print("")
time.sleep(3)
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
-2

You can use:

Name.isalpha()

"3".isalpha()

False

"anna".isalpha()

True

Cezar Cobuz
  • 1,077
  • 1
  • 12
  • 34