I need an if statement that will run if the value is not a number.
I am unsure how to do this in python I have tried looking around and I can't seem to find what I need.

If Input is not <a number>

Also if you can help me restrict this to positive numbers that would be appreciated as well.

Recommended Answers

All 16 Replies

There are a few possibilities I can think of, but probably the most straight forward:

>>> li = [ 1, 2.3, 4e-5, 'hey!' ]
>>> for item in li:
...     test = str(item)
...     if test == item:
...         print item, 'String!'
...     else:
...         print item, 'Not String!'
...     
1 Not String!
2.3 Not String!
4e-005 Not String!
hey! String!
>>>

Now when you say restrict this to positive numbers, do you mean:
If Input is not <a positive number>:
perform action

commented: Good example +8

yep exactly, if they input a negative number it will return differentiate that form a positive number.
Also thanks alot for what you have given me.

yep exactly, if they input a negative number it will return differentiate that form a positive number.
Also thanks alot for what you have given me.

>>> li = [ 1, -2, 2.3, 't', -5.3e5, -0.1, 4e-5, 'hey!' ]
>>> for item in li:
...     test = str(item)
...     if test == item:
...         print item, 'String!'
...     else:
...         if item < 0:
...             print item, 'Not string... negative!'
...         else:
...             print item, 'Not string... positive!'
...     
1 Not string... positive!
-2 Not string... negative!
2.3 Not string... positive!
t String!
-530000.0 Not string... negative!
-0.1 Not string... negative!
4e-005 Not string... positive!
hey! String!
>>>

Simply check if the number is less than zero to determine if it is negative.
Just remember to do this only after you've verified that the item is not a string or else you will run into some strange results.

This is just jlm699's code wrapped into a function ...

def isPositiveNumber(n):
    """returns True if n is a positive number, else returns False"""
    # check if n is a string
    q = str(n)
    if q == n:
        return False
    if n > 0:
        return True
    else:
        return False

# test the function
if __name__ == '__main__':
    mylist = li = [ 1, -2, 2.3, 't', -5.3e5, -0.1, 4e-5, 'hey!' ]
    for item in mylist:
        print item, isPositiveNumber(item)

If you are using raw_input or the variable is already a string, then try isdigit(). This of course assumes that you aren't using floating point numbers. If you are then you will have to use a try/except converting the string to a float.

get_num=raw_input("Enter a number ")
print get_num,
if get_num.isdigit():
   if int(get_num) > 0:
      print "is integer and is positive"
   else:
      print "is integer and is NOT positive"
## this will never execute since a minus sign, "-", is not a digit
else:
   print "is NOT a number"

Or this:

try:
    val = int(item)
    if val > 0:
        do stuff for positive numbers
    elif val < 0:
        do stuff for negative numbers
    else:   # don't omit zero!
        do stuff for zero
except:
    pass

If you want to allow floating point numbers, you can change the int() to float()

Jeff

def valid(x):
    # check if n is a string
    q = str(x)
    if q == x:
        print "Error, Not valid input"
        break
    else:
    
        if x > 0:
            print ""
        else:
            print "Error, Not valid input"
            break

I am using this to break a loop if there is invalid input.

Thank you for all your help, it solved quite a big problem for me :D

Ok, Modules Idea is not working as it sets that as something different outside of the loop it is currently in so any variables (and break commands) seem to not work...
Is there a way I can make a variable global or somehow allow a module to break a loop.

Instead of the break have your function return False and respond to that in your loop.

Hey thanks for the help so far.

I am getting errors such as False is not defined.
When I made it try returning a counter in the modules that called it I get the error that the counter is not defined.

Sorry that I am unable to help myself with this and thank you to all who have helped me so far.

I am getting errors such as False is not defined.
When I made it try returning a counter in the modules that called it I get the error that the counter is not defined.

False is a reserved keyword in Python. Make sure you are capitalizing the F in False however.
If you are using a variable inside the function, make sure you return it and capture it outside the function as following:

>>> bool_list = [True, True, 1, 'Hi', False, 0, '']
>>> len( bool_list )
7
>>> def retFalseIndx( list ):
...     my_counter = 0
...     for item in list:
...         if not item:
...             return my_counter
...         else:
...             my_counter += 1
...     
>>> retFalseIndx( bool_list )
4
>>> ret = retFalseIndx( bool_list )
>>> ret
4
>>>

Ok, thanks for that, I have got it working now. The only other issue I have has been a persistant issue which I kinda gave up on.

This module which has been giving me the most hardship is designed to interface with the user.
Now my values are being entered by the input command. This causes a type issue if it is not a number or defined variable.
I have tried using raw_input but that gives me errors with my maths as it won't let me multiply and does not allow for me to process them properly.

>>> usr_inp = eval( raw_input ('Enter a number: ') )
Enter a number: 5.78
>>> usr_inp
5.7800000000000002
>>> usr_inp = eval( raw_input ('Enter a number: ') )
Enter a number: 14e-5
>>> usr_inp
0.00013999999999999999
>>>

You can use the eval() method to convert your raw_input (saved as a string) to int or float. You should also work into your code a check after that input to make sure that the user did not enter a string, as that will mess up your "maths" as you put it.
A simple try: except: clause wrapping your maths should do it.

I have tried your method and with a string input I immediatly get an error. In this case the input was hi
Error:
NameError: name 'hi' is not defined

Once again thank you for so much help you are giving me.

If this program was for personal use the number thing would not be an issue however other people are going to be using this and it would be inelegent of the program crashes everytime they input a string due to a typo. This human interface part has been the most difficult part, the rest has been just understanding syntax.
(It probably doesn't help that this is the first thing of any significance I am doing in python)

You can create a relatively safe numeric input with a function:

def get_num(prompt="Enter a number: "):
    """
    the function will loop until a number has been entered,
    accepts int or float, returns a float
    """
    while True:
        try:
            return float(raw_input(prompt))
        except ValueError:
            print "Numeric value required!"

print get_num()
print get_num("Enter the price: ")

Thank you for that :)
That has really helped me and now I think I shall mark my problems as solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.