Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding print statement to ValueError exception

New to Python, so I'm sure this is a noob question, but Googling isn't availing me of a clear answer.

Given the following function which is intended to ensure that the user input is a string, why can't I (or how can I) add a print statement when the exception is triggered? The print statement I've inserted there doesn't work.

def string_checker(action):
    try:
        check = isinstance(action, basestring)
        if check == True:
            return True
    except ValueError:
        print "We need a string here!"
        return None

action = "words"
string_checker(action)
like image 905
SeanJarp Avatar asked Dec 21 '25 18:12

SeanJarp


2 Answers

This may do what you want:

def string_checker(action):
    try:
        assert isinstance(action, basestring)
        return True
    except AssertionError:
        print "We need a string here!"
        return None

action = "words"
string_checker(action)
string_checker(21)

But you could also return "We need a string here!" instead of printing it, or return False, for consistency.

like image 60
rofls Avatar answered Dec 23 '25 15:12

rofls


The problem is that you're never raising a value error if action isn't a string. Try this:

def string_checker(action):
    try:
        check = isinstance(action, basestring)
        if check:
            return True
        else:
            raise ValueError
    except ValueError:
        print "We need a string here!"
        return None

But really, I don't think you need an exception. This should work fine:

def string_checker(action):
    try:
        check = isinstance(action, basestring)
        if check:
            return True
        else:
            print "We need a string here!"
            return None
like image 40
ezig Avatar answered Dec 23 '25 13:12

ezig