如何防止python中的ValueError

时间:2015-12-28 21:21:44

标签: python

我在输入一个字符串作为输入的响应时,有一个关于如何防止ValueError的问题。

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("--------------------")

我希望我的程序在被要求两个时阻止只输入一个字符串。与检查 name.isaplha() len(name)> = 1 类似,我希望程序检查是否插入了两个字符串。如果只有一个,我希望它打印("错误:选择一个至少有一个字符的名字和姓氏,请只用字母!"),基本上 else:块就像输入中的其他错误一样。

Screenshot

谢谢!

1 个答案:

答案 0 :(得分:3)

我建议使用tryexcept

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")