hmm, little question here from a slightly new user.

sblakey at freei.net sblakey at freei.net
Thu Mar 23 18:53:33 EST 2000


On 23 Mar, Falknor wrote:
> How can I check to see if a value is an int type? ie something like
> 
> int = raw_input("Enter your int value.")
> 
> if is_int(int):
>     floater = int(int)
> 
> or
> 
> if len(sys.argv) > 1:
>     if not is_int(sys.argv[1]):
>         print "Syntax is blaat [port number]"
>    else:
>        port = int(sys.argv[1])
> 
> that type of thing... :)
> 
> JD
> 
> ______________________________________________________________
> Get free Internet service and email at http://www.worldspy.com
> 
Look at the built in type function and the types library.  For example:
if type(int_value) == type(1):
    floater = int_value
or
import types
if type(int_value) == types.IntType:
    floater = int_value
Note that if your int_value (don't want to clobber the name int) is
already an integer, there is no need to use the int function to convert
it into an int.

Your second example is a bit more complex.  The values in sys.argv will
always be strings, so checking to see if it is an int would be
pointless.  You can try to convert it into an integer, then catch the
error if the string in sys.argv cannot be coerced into an int.
if len(sys.argv) > 1:
    try:
        port = int(sys.argv[1])
    except ValueError:
    	print 'Syntax is blaat [port number]'

You can even do this like:
try:
    port = int(sys.argv[1])
except ValueError:		# argv[1] cannot be coerced to integer
    print 'Syntax is blaat [port number]'
except IndexError:		# There is no argv[1]
    port = DEFAULT_PORT		# or whatever else you want





More information about the Python-list mailing list