[Tutor] Verification of variable input
Andrei Kulakov
ak@silmarill.org
Fri, 28 Sep 2001 19:01:32 -0400
On Fri, Sep 28, 2001 at 05:43:51PM -0500, runsun wrote:
> 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
I guess you'll just have to test for it:
if isBoldFace not in ("true", "True", "1", "5"):
print "Error!"
>
> [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)
> ======================================
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org