我做错什么了?在Python中尝试

2024-03-28 12:30:10 发布

您现在位置:Python中文网/ 问答频道 /正文

请阅读我的代码,以便更好地理解我的问题。我正在用python创建一个待办事项列表。在有try和except的while循环中,我想将用户输入类型设置为string。如果用户输入一个整数,我想在“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()

Tags: theto代码inputyourifsoshow
3条回答

你的假设有两个问题:

  1. 对整数调用str不会引发ValueError,因为每个整数都可以表示为字符串。你知道吗
  2. input(无论如何,在python3上,它看起来像是您正在使用的)返回的所有内容都已经是一个字符串了。将字符串转换为字符串将绝对不会抛出错误。你知道吗

如果要抛出所有数字输入,可能需要使用^{}。你知道吗


“全数字”这个词的注释似乎有些混乱。我指的是一个完全由数字组成的字符串,这是我对OP不想在待办事项列表中出现“整数”的解释。如果您想抛出一些更广泛的字符串化数字类(有符号整数、浮点数、科学记数法),isdigit不是适合您的方法。:)

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

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

所以str不会抛出ValueError在本例中它已经是一个字符串了。你知道吗

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

input返回一个字符串。有关input函数,请参见the docs。将此函数的结果强制转换为字符串不会起任何作用。你知道吗

可以使用^{}检查字符串是否为数字。你知道吗

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

这与您现有的else子句非常吻合。你知道吗

相关问题 更多 >