简体   繁体   English

我在这里做错了什么? 尝试使用Python

[英]What am I doing wrong here? Try and Except in Python

Please read my code for better understanding of my question. 请阅读我的代码以更好地理解我的问题。 I'm creating a to do list in python. 我在python中创建一个待办事项列表。 In the while loop where there's try and except, I want to set the user input type as string. 在try和else的while循环中,我想将用户输入类型设置为字符串。 And if the user types in an integer I want to print out the message in the "except" block. 而且如果用户输入一个整数,我想在“ except”块中打印出该消息。 But it doesn't execute the ValueError if the I type in an integer when I run the code. 但是,如果我在运行代码时输入整数,则不会执行ValueError。

Here's the code: 这是代码:

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 returns a string. input返回一个字符串。 See the docs for the input function. 有关input功能,请参阅文档 Casting the result of this function to a string won't do anything. 将此函数的结果强制转换为字符串将不会执行任何操作。

You could use isdecimal to check if the string is a numeric. 您可以使用isdecimal来检查字符串是否为数字。

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

This would fit in nicely with your existing else clause. 这将非常适合您现有的else子句。

Two problems with your assumptions: 您的假设有两个问题:

  1. Calling str on an integer will not raise a ValueError because every integer can be represented as a string. 在整数上调用str不会引发ValueError因为每个整数都可以表示为字符串。
  2. Everything coming back from input (on Python 3 anyway, which it looks like you're using) is already a string. input返回的所有内容(无论如何在Python 3上,似乎都在使用)都已经是字符串。 Casting a string to a string will definitely not throw an error. 将字符串强制转换为字符串绝对不会引发错误。

You might want to use isdigit if you want to throw out all-numeric input. 如果要isdigit全数字输入,则可能要使用isdigit


There seems to be some confusion in the comments over the word 'all-numeric'. 关于“全数字”一词的评论似乎有些混乱。 I mean a string that is entirely composed of numbers, which was my interpretation of the OP not wanting "integers" on his to-do list. 我的意思是一个完全由数字组成的字符串,这是我对OP的不希望在他的待办事项列表中使用“整数”的解释。 If you want to throw out some broader class of stringified numbers (signed integers, floats, scientific notation), isdigit is not the method for you. 如果您想丢掉一些更广泛的字符串类型(带符号的整数,浮点数,科学计数法), isdigit不是适合您的方法。 :) :)

In Python, input always returns a string. 在Python中, input始终返回一个字符串。 For example: 例如:

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

So str won't throw a ValueError in this case--it's already a string. 因此,在这种情况下str不会引发ValueError,它已经是字符串。

If you really want to check and make sure the user didn't enter just numbers you probably want to check to see if your input is all digits, and then error out. 如果您确实要检查并确保用户输入的不是数字,则可能要检查一下您的输入是否为全数字,然后输入错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM