簡體   English   中英

我在這里做錯了什么? 嘗試使用Python

[英]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()

input返回一個字符串。 有關input功能,請參閱文檔 將此函數的結果強制轉換為字符串將不會執行任何操作。

您可以使用isdecimal來檢查字符串是否為數字。

if user_input.isdecimal():
    print("Strings only!")

這將非常適合您現有的else子句。

您的假設有兩個問題:

  1. 在整數上調用str不會引發ValueError因為每個整數都可以表示為字符串。
  2. input返回的所有內容(無論如何在Python 3上,似乎都在使用)都已經是字符串。 將字符串強制轉換為字符串絕對不會引發錯誤。

如果要isdigit全數字輸入,則可能要使用isdigit


關於“全數字”一詞的評論似乎有些混亂。 我的意思是一個完全由數字組成的字符串,這是我對OP的不希望在他的待辦事項列表中使用“整數”的解釋。 如果您想丟掉一些更廣泛的字符串類型(帶符號的整數,浮點數,科學計數法), isdigit不是適合您的方法。 :)

在Python中, input始終返回一個字符串。 例如:

>>> input('>')
>4
'4'

因此,在這種情況下str不會引發ValueError,它已經是字符串。

如果您確實要檢查並確保用戶輸入的不是數字,則可能要檢查一下您的輸入是否為全數字,然后輸入錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM