3

I have a function that takes an optional argument like so:

myProgram -n 8

I want to add in error handling that will exit the program and print an error message if the argument that the user enters is a float. How would I test for this if the argument always comes in as a string?

1
  • 1
    You say function but your example is a program. Which is it? Commented May 5, 2015 at 3:32

4 Answers 4

2

It may seem heavy-weight at first, but the argparse module can do exactly what you want. The first example on the page shows an integer-only argument (notice the type=int part):

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')

Calling that example with python deleteme.py 3.5 (i.e. 3.5 is the argument that should be an integer) gives the following output:

usage: scriptname.py [-h] [--sum] N [N ...]
scriptname.py: error: argument N: invalid int value: '3.5'
Sign up to request clarification or add additional context in comments.

Comments

1

Use str.isdigit():

>>> '12345'.isdigit()
True
>>> '12.345'.isdigit()
False

If you want to support negative numbers, strip the sign off first:

>>> '+12345'.strip(' -+').isdigit()
True
>>> '-12345'.strip(' -+').isdigit()
True

Comments

1

To parse command line arguments, you should be using argparse.

import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-n", type=int)
    args = parser.parse_args()

    print args

if __name__ == '__main__':
    main()

Usage:

[10:39pm][wlynch@watermelon /tmp] python blah.py
Namespace(n=None)
[10:39pm][wlynch@watermelon /tmp] python blah.py -n 4
Namespace(n=4)
[10:39pm][wlynch@watermelon /tmp] python blah.py -n 4.0
usage: blah.py [-h] [-n N]
blah.py: error: argument -n: invalid int value: '4.0'

Comments

0

You could perhaps do something like this:

from math import modf

if modf(float(args.n))[0] != 0.0:
    # ERROR: Float entered!

From the math.modf docs:

math.modf(x)¶ Return the fractional and integer parts of x. Both results carry the sign of x and are floats.

Or alternatively (as @dawg mentioned):

"." in args.n  # A possible float

# or

args.n.isdigit()  # Returns False if args.n does not contain all digits only

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.