【发布时间】:2016-07-22 21:44:41
【问题描述】:
请阅读我的代码以更好地理解我的问题。我正在 python 中创建一个待办事项列表。在有try和except的while循环中,我想将用户输入类型设置为字符串。如果用户输入一个整数,我想在“except”块中打印出消息。但是,如果我在运行代码时输入整数,它不会执行 ValueError。
代码如下:
to_do_list = []
print("""
Hello! Welcome to your notes app.
Type 'SHOW' to show your list so far
Type 'DONE' when you'v finished your to do list
""")
#let user show their list
def show_list():
print("Here is your list so far: {}. Continue adding below!".format(", ".join(to_do_list)))
#append new items to the list
def add_to_list(user_input):
to_do_list.append(user_input)
print("Added {} to the list. {} items so far".format(user_input.upper(), len(to_do_list)))
#display the list
def display_list():
print("Here's your list: {}".format(to_do_list))
print("Enter items to your list below")
while True:
#HERE'S WHERE THE PROBLEM IS!
#check if input is valid
try:
user_input = str(input(">"))
except ValueError:
print("Strings only!")
else:
#if user wants to show list
if user_input == "SHOW":
show_list()
continue
#if user wants to end the list
elif user_input == "DONE":
new_input = input("Are you sure you want to quit? y/n ")
if new_input == "y":
break
else:
continue
#append items to the list
add_to_list(user_input)
display_list()
【问题讨论】:
-
str([integer value])是值并且不会抛出错误 - 您只是将输入(已经是字符串)转换为字符串。
标签: python