0

I'm creating a program where it collects data from the user, I have finished the basic inputs of collecting their first name, surname, age etc; however I wanted the user to have no numbers in their first name or surname.

If the user types a number in their first name such as "Aaron1" or their surname as "Cox2"; it would repeat the question asking for their name again.

Attempt 1

firstname=input("Please enter your first name:  ")
     if firstname==("1"):
          firstname=input("Your first name included a number, please re-enter your first name")
     else:
          pass

Attempt 2

firstname=input("Please enter your first name:  ")
try:
    str(firstname)
except ValueError:
    try:
        float(firstname)
    except:
        firstname=input("Re-enter your first name: ")

Any suggestions?

William
  • 942
  • 2
  • 12
  • 25
  • This might help: https://stackoverflow.com/questions/19859282/check-if-a-string-contains-a-number – Alex Dubrovsky Feb 01 '18 at 12:12
  • Check here: https://stackoverflow.com/questions/19859282/check-if-a-string-contains-a-number – nocab Feb 01 '18 at 12:13
  • Obligatory: [Falsehoods Programmers Believe About Names](http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/) – tobias_k Feb 01 '18 at 12:14

2 Answers2

0

First create a function that checks if there are any digits in the string:

def hasDigits(inputString):
    return any(char.isdigit() for char in inputString)

Then use a loop to keep asking for input until it contains no digits.

A sample loop would look like the following:

firstname=input("Please enter your first name:  ")

while hasDigits(firstname):
    firstname=input("Please re-enter your first name (Without any digits):  ")

Live Example

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
0

You can check if the name contains letters only with isalpha method.

#The following import is only needed for Python 2 to handle non latin characters
from __future__ import unicode_literals

'Łódź'.isalpha() # True
'Łódź1'.isalpha() # False
ElmoVanKielmo
  • 10,907
  • 2
  • 32
  • 46