1

I want to have a program that print out error messages when an integer or float value is enter into a string input. Example:

Enter name: 1234
Invalid name entered. Please enter a new one.

Enter name: Joe
Enter no. phone:123456789

(and so on..)

now I only have this:

while True:
    try:
        # Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
        age = input("enter name: "))
    except ValueError:
        print("Invalid name.")
        continue
    else:
        break
if : 
    print("")
else:
    print("")

what do I need to put at the if else?

Joe han
  • 171
  • 11

2 Answers2

1

First create a string or set (sets are more efficient) of the forbidden characters and then just iterate over the input string and check if the chars aren't in the forbidden_chars set. If the string contains a forbidden character, set a flag variable (called invalid_found in the example below) to True and only break out of the while loop if the flag is False, that means if no invalid char was found.

forbidden_chars = set('0123456789')

while True:
    inpt = input('Enter a string: ')
    invalid_found = False
    for char in inpt:
        if char in forbidden_chars:
            print('Invalid name.')
            invalid_found = True
            break
    if not invalid_found:
        break

print(inpt)
skrx
  • 19,980
  • 5
  • 34
  • 48
  • Also, check out [Falsehoods Programmers Believe About Names](http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/). There are people with numbers in their names. – skrx Oct 12 '17 at 19:47
0
isdigit() - it is a string method which checks that whether a string entered is numeric(only numeric, no spaces, or alphabets) or not.
    while True:
        name = input("Enter your name : ")
        if name.isdigit():
            print("Invalid name please enter only alphabets.")
            continue
        else:
            phone_number = int(input("Enter Your phone number : "))
            print(f"Name : {name}")
            print(f"Phone_number : {phone_number}")
            break
ZF007
  • 3,708
  • 8
  • 29
  • 48
Aditya
  • 11
  • 1