【发布时间】:2015-12-28 21:21:44
【问题描述】:
我有一个问题,关于在仅输入 一个 字符串作为对 input 的响应时如何防止 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 我希望我的程序检查是否插入了两个字符串。如果只有一个,我希望它print("错误:请选择一个至少包含一个字符并且只使用字母的名字和姓氏!"),所以基本上else: 像输入中的其他错误一样阻止。
谢谢!
【问题讨论】:
-
@l'L'l 会尝试并报告。谢谢!
-
将
split()的结果分配给单个列表变量,并在分配给name1和name2之前检查其长度。
标签: python