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!

David
  • 33
  • 1
  • 5
  • 1
    Possible duplicate of [Asking the user for input until they give a valid response](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – l'L'l Dec 28 '15 at 21:25
  • @l'L'l will try that and report. Thanks! – David Dec 28 '15 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`. – Barmar Dec 28 '15 at 21:32

1 Answers1

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")
Caridorc
  • 6,222
  • 2
  • 31
  • 46
  • 1
    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. =) – David Dec 28 '15 at 22:11