【问题标题】:What am I doing wrong here? Try and Except in Python我在这里做错了什么?在 Python 中尝试和排除
【发布时间】: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


【解决方案1】:

input 返回一个字符串。有关input 功能,请参阅the docs。将此函数的结果转换为字符串不会做任何事情。

您可以使用isdecimal 来检查字符串是否为数字。

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

这很适合您现有的else 子句。

【讨论】:

    【解决方案2】:

    你的假设有两个问题:

    1. 对整数调用 str 不会引发 ValueError,因为每个整数都可以表示为字符串。
    2. input 返回的所有内容(无论如何都在 Python 3 上,看起来您正在使用)已经是一个字符串。将字符串转换为字符串肯定不会引发错误。

    如果您想丢弃全数字输入,您可能需要使用isdigit


    cmets 中似乎对“全数字”一词有些混淆。我的意思是一个完全由数字组成的字符串,这是我对 OP 的解释,他不希望在他的待办事项列表上出现“整数”。如果您想丢弃一些更广泛的字符串化数字(有符号整数、浮点数、科学记数法),isdigit 不适合您。 :)

    【讨论】:

    • 要丢弃数字输入,最好的方法是try 将其转换为某种数字(并处理该异常)...例如例如,isdigit 不处理 -50
    • isdigit 不会找到所有数字(只有字符串格式的整数)!
    【解决方案3】:

    在 Python 中,input 总是返回一个字符串。例如:

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

    所以str 在这种情况下不会抛出 ValueError ——它已经是一个字符串了。

    如果你真的想检查并确保用户没有只输入数字,你可能想检查你的输入是否全是数字,然后出错。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2016-03-03
      • 2013-06-28
      • 2023-01-19
      • 2016-06-02
      • 1970-01-01
      相关资源
      最近更新 更多