0
votes

Please read my code for better understanding of my question. I'm creating a to do list in python. In the while loop where there's try and except, I want to set the user input type as string. And if the user types in an integer I want to print out the message in the "except" block. But it doesn't execute the ValueError if the I type in an integer when I run the code.

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()
3
str([integer value]) is value and will not throw an error - you are simply converting the input (already a string) to a string. - Nick

3 Answers

3
votes

input returns a string. See the docs for the input function. 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.

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

This would fit in nicely with your existing else clause.

2
votes

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.
  2. Everything coming back from input (on Python 3 anyway, which it looks like you're using) is already a string. 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.


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. If you want to throw out some broader class of stringified numbers (signed integers, floats, scientific notation), isdigit is not the method for you. :)

0
votes

In Python, input always returns a string. For example:

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

So str won't throw a ValueError in this case--it's already a string.

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.