3

I've got a question on how to prevent ValueError when inputting only one string as a response to input.

elif choice == "2":
    #Input of both name and last name
    while True: #Checks for name and last name characters and their length
        name, name2 = input("Please tell me your name and last name separated by space ").split()
        if name.isalpha() and name2.isalpha() and (len(name) >= 1) and (len(name2) >= 1): 
            print("--------------------")
            print("Nice to meet you! So " + (str(name) + " " + str(name2)) + ", are you ready to begin?")
            break

        else:
            print("ERROR: Choose a name and last name with at least one character and use only letters, please!")
            print("--------------------")

I want my program to prevent the input of only one string when asked for two. Similar to checking for name.isaplha() and len(name) >= 1 I want my program to check if there are two strings inserted. If there's only one, I want it to print("ERROR: Choose a name and last name with at least one character and use only letters, please!"), so basically the else: block like for other errors in input.

Screenshot

Thanks!

3
  • 1
    Possible duplicate of Asking the user for input until they give a valid response Commented Dec 28, 2015 at 21:25
  • @l'L'l will try that and report. Thanks! Commented Dec 28, 2015 at 21:29
  • 2
    Assign the result of split() to a single list variable, and check its length before assigning it to name1 and name2. Commented Dec 28, 2015 at 21:32

1 Answer 1

6

I suggest using try and except:

try:
    name, name2 = input("Please tell me your name and last name separated by space ").split()
except ValueError:
    print("Error: you must enter two string")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this solved my problem. I just needed to figure out where to put the if statement for checking the length and alpha, but solved it all out. Thanks once again. =)

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.