[Tutor] Verification of variable input
runsun
runsun@bilbo.bio.purdue.edu
Fri, 28 Sep 2001 17:43:51 -0500
Hi all,
How do I make sure the values been passed into a variable is valid?
For example:
[1] a variable "isBoldface" will take:
"true", "True", "1", "5" ===> valid
"false", "fALSE", "0", anyother type ===> invalid
[2] a variable "borderWidth" will take:
"2", "2.5", 3 ====> valid
"a", any other type =====> invalid
[3] a variable "align" will take
"center", "CENTER", "Center", "Left", "right" ... ==> valid
any other values ===> invalid
I have written two functions for [1] and [2] and both work fine.
Just thinking if there's any builtin function that I can use.
For [1]:
def returnBoolean(b):
''' Reutrn 1 if b = "True", "tRue", "TRUE", "1", and any integer
other than 0 .....
Return 0 if b= 0, 0.00, 5.5, "false", "False", "FALSE", integer
0 ....
'''
if type(b)==type(1): # If b is an integer
if b!=0: return 1 # anythong other than 0 will set b
to true
elif type(b)==type("a"): # if b is a string
if b.strip().upper()=="TRUE": return 1
else return 0
For [2]
def returnInt(x):
try:
x=int(x) #"3", "-4", 3.5, -1 ...
return x
except:
try:
x=float(x) #for cases like "3.5"
return int(x)
except:
return 0 # "a", or any other data type
======================================
~~ Be like water, be shapeless ~~
Runsun Pan, PhD, Biological Sci. Purdue Univ
Email: runsun@bilbo.bio.purdue.edu
Url : http://bilbo.bio.purdue.edu/~runsun
Tel : 765-496-4186(H), 765-494-4947 (O)
Fax : 775-665-1494 (USA) 094-656-8001 (Taiwan)
(I can access both through my email)
======================================