Hamza Mirza Hamza Mirza - 4 months ago 10
Python Question

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. 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()

Answer

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.