How can I convert a string to an int in Python?

Since you’re writing a calculator that would presumably also accept floats (1.5, 0.03), a more robust way would be to use this simple helper function:

def convertStr(s):
    """Convert string to either int or float."""
    try:
        ret = int(s)
    except ValueError:
        #Try float.
        ret = float(s)
    return ret

That way if the int conversion doesn’t work, you’ll get a float returned.

Edit: Your division function might also result in some sad faces if you aren’t fully aware of how python 2.x handles integer division.

In short, if you want 10/2 to equal 2.5 and not 2, you’ll need to do from __future__ import division or cast one or both of the arguments to float, like so:

def division(a, b):
    return float(a) / float(b)

Leave a Comment