0

How can I write the below code, in a way that it only accepts names instead of integers or floats?

try:
    name = input("What is your name?: ")
    print("Your name is " +name)
except:
    print("That isn't a valid name")
wjandrea
  • 28,235
  • 9
  • 60
  • 81
mantsenii
  • 1
  • 1
  • 2
    Maybe regular expressions (module "re") can help if you can formulate a regex rule what a valid name is. – Michael Butscher Jan 24 '22 at 20:52
  • 3
    Honestly, it shouldn't be up to you to decide what constitutes a "name". You may never have met 3.7, but that doesn't mean he doesn't exist. – Tim Roberts Jan 24 '22 at 21:08
  • 1
    Reject the input if `int(name)` and `float(name)` ***don't*** throw an exception (requires nested `try`/`except ValueError:`). Also see [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) for repeatedly asking them for something valid. – martineau Jan 24 '22 at 21:09
  • 2
    [Falsehoods Programmers Believe About Names](https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/) – chepner Jan 24 '22 at 21:12
  • @Tim Very true. I can't think of anyone whose name is *only* a number, but I did find a ["Number 16 Bus Shelter" from New Zealand](https://nationalpost.com/news/new-zealand-reveals-a-list-of-banned-baby-names-4real-was-one-of-them). Also notable is ["X Æ A-12 Musk"](https://www.washingtonpost.com/technology/2020/05/08/musk-grimes-baby-name/), though California rejected it. – wjandrea Jan 24 '22 at 21:57
  • 2
    @Jakob `str.isalpha()` goes beyond just rejecting any numbers; it'll also reject punctuation and spaces, like for example: `'Jakob Schödl'.isalpha()` -> `False` – wjandrea Jan 24 '22 at 22:02
  • 1
    Beside the point, but [a bare `except` is bad practice](/q/54948548/4518341). Instead, use the specific exception you're expecting like `except ValueError`, or at least `except Exception`. – wjandrea Jan 24 '22 at 22:04
  • Why do you need to reject string representations of integers and floats? If you don't actually need to, you might just be making this more difficult for yourself, but I can imagine situations where you really do need to. – wjandrea Jan 24 '22 at 22:19
  • I edited the title to try to clarify what you're asking. If you'd like to clarify further, you can [edit] it yourself of course. Check out [ask] for tips on writing a good title. – wjandrea Jan 25 '22 at 19:57

2 Answers2

1

Here's an example using exceptions for checking whether given name could be a float or int, and looping until a valid name is given:

# Loop until break out
while True:
    name = input("What is your name?: ")

    try:
        int(name)
        print("An int is not a valid name")
        # Go to start of loop
        continue
    except ValueError:
        # Continue to next check
        pass

    try:
        float(name)
        print("A float is not a valid name")
        # Go to start of loop
        continue
    except ValueError:
        # Break loop if both exceptions are raised
        break

print(f"Hello {name}!")
Tzane
  • 2,752
  • 1
  • 10
  • 21
  • 1
    Ideally, you should have as little as possible in a `try`-statement, so I recommend moving the `print()` and `continue` into an `else`-block. – wjandrea Jan 25 '22 at 19:08
0

The Problem Here With Try-Except

If you want to do it using try-except, an approach is to turn the input to an int or a float and then in the except print that the name is valid, like this:

try:
    name = input("What is your name?: ")
    test = float(name)
    print("this is not a valid name")
except:
    print("your name is " + name)

The problem is that the name can be 'foo2' and it still works and to treat exceptions like that you need to write a lot of code.

Isalpha Function

As @JakobSchödl said just use name.isalpha() which return true if the name contains anything that isn't a letter. Implementation below:

name = input("What is your name?: ")
if name.isalpha():
    print("Your name is " +name)
else:
    print("not a valid name")

This is much simpler.


Using a Regex

You can also use a regex if you want but it's a bit more complicated, example below.

import re
match = re.match("[A-Z][a-z]+", name)
if match is not None:
    print("your name is " + name)
else:
   print("this is an invalid name")
wjandrea
  • 28,235
  • 9
  • 60
  • 81
S H
  • 415
  • 3
  • 14
  • Thanks, I corrected it, would you know how to make it also work with spaces? – S H Jan 25 '22 at 13:40
  • To allow spaces, you'd just put a space in the second character class: `[a-z ]` – wjandrea Jan 25 '22 at 19:06
  • It's worth noting that `.isalpha()` and that regex aren't quite the same. The regex is a lot more strict (only ASCII, specific casing), which disallows names like "Étienne", "bell hooks", "McDonald", etc. Though both disallow names like "Waller-Bridge" because of the hyphen. – wjandrea Jan 25 '22 at 20:09
  • Ideally, you should have as little as possible in a `try`-statement, so the input should go before it, and the print should go in an `else`-block. Also, [a bare `except` is bad practice](/q/54948548/4518341); instead, use the specific exception you're expecting like `except ValueError`. – wjandrea Jan 25 '22 at 20:12
  • thanks everyone! I am still learning and this has been thorough and very helpful feedback. Very very much appreciated. – mantsenii Jan 26 '22 at 01:28
  • Happy it did! Please consider the answer as accepted if it solved your problem – – S H Apr 18 '22 at 13:36