【发布时间】:2022-01-15 11:29:01
【问题描述】:
如果用户输入字母(字符串)而不是数字(整数),我正在寻找处理用户在列表中输入的方式,它会提示用户他输入了无效值并提示用户再试一次。 这里有一些代码:
def get_list_from_user(): # Prompt the user for a list of number
while True:
user_list = input(f"Enter {difficulty} number separated by space: ")
user_list = user_list.split()
user_list = [int(i) for i in user_list]
if not len(user_list) == difficulty:
print(f"Please chose {difficulty} number separated by space: ")
else:
break
saved_user_list = user_list
return saved_user_list
【问题讨论】:
-
将
user_list = [int(i) ...]行包装在try: except ValueError: continue部分中(在 continue 语句之前打印可选的错误消息。
标签: python python-3.x list