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?

5
  • what did you try? Commented Oct 12, 2017 at 15:38
  • Very well, so there is only one thing you have to do: write the program :) Commented Oct 12, 2017 at 15:38
  • How about something simple like not mystr[0].isdigit()? Commented Oct 12, 2017 at 15:39
  • or all(char.isalpha() or char == ' ' for char in mystr)? Commented Oct 12, 2017 at 15:40
  • Does this answer your question? Asking the user for input until they give a valid response Commented Nov 2, 2020 at 10:49

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Also, check out Falsehoods Programmers Believe About Names. There are people with numbers in their names.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.