[英]What am I doing wrong here? Try and Except in Python
請閱讀我的代碼以更好地理解我的問題。 我在python中創建一個待辦事項列表。 在try和else的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()
在Python中, input
始終返回一個字符串。 例如:
>>> input('>')
>4
'4'
因此,在這種情況下str
不會引發ValueError,它已經是字符串。
如果您確實要檢查並確保用戶輸入的不是數字,則可能要檢查一下您的輸入是否為全數字,然后輸入錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.