Python Forum
How to find any non positive integer
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to find any non positive integer
#1
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.
Reply
#2
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.
Reply
#3
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!
Reply
#4
(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.
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Positive integral solutions for Linear Diophantine Equation august 4 1,242 Jan-13-2023, 09:48 PM
Last Post: Gribouillis
  How to do bar graph with positive and negative values different colors? Mark17 1 5,163 Jun-10-2022, 07:38 PM
Last Post: Mark17
  Regex: positive lookbehind Secret 2 2,009 Sep-21-2020, 12:59 AM
Last Post: snippsat
  Positive to negative bernardoB 6 4,366 Mar-13-2019, 07:39 PM
Last Post: bernardoB
  negative to positive slices Skaperen 3 3,653 Jan-29-2018, 05:47 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020