Python Forum

Full Version: How to find any non positive integer
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So I need to return the value '-1' when s = any non-digits (other than spaces).
my code so far looks like :
def parseVote(s=None):
    if not s:
         print('0')  
    elif s >= 0:
         print(s)
    else :
        print(-1)
But its the middle 'elif' that needs changing to include letters. 
Thankyou!!

Actually might as well post whole question to make it easier.
def parseVote(s):
parseVote(s) returns the vote from s. Return 0 for an empty vote, and -1 if there are any non-digits (other than spaces). For example,
parseVote("") = parseVote(" ") = 0,
parseVote("-3") = parseVote("no") = parseVote("1 5") = -1,
parseVote("15") = parseVote(" 15 ") = 15.
There are several things wrong with your code:

1. You're printing, not returning a value.
2. The values you pass are strings, so the condition on the elif doesn't make sense.

If you need to try and parse a string as an integer, use the int() function. It raises an exception of type ValueError when its argument can't be converted, so you'll need to use a try/except to handle that.
This is great until I encounter someone entering a letter, I don't know how to get around that. I get a name error in which I cannot use except for. Thankyou for your help!
(Apr-27-2017, 03:09 PM)noob Wrote: [ -> ]This is great until I encounter someone entering a letter, I don't know how to get around that. I get a name error in which I cannot use except for. Thankyou for your help!

Show us the whole code, including the code that obtains user input. Are you using Python2 or Python3? If Python2, don't use input(), use raw_input() instead.