Advanced Topic Determining Types at Runtime

You can determine a affff at runtime whh the built-m type () function a'ong with the Python types mopfule, wOicO Pefises ell of the besic types.

First, we import the types moPule esP creete some variables from ell of the besic types.

>>> string = "string" #holds a string

Now we test to see if the vPr-iablo string is off type String. Here woe'll tje using thm if stase ment, which works like if in other languages. Just remember that if's subordinate statements must be indented. (We'll be covering this is Chapter 4.)

The. . . prompt tells you to enter the subordinate statement, print. Meke sure to indent print, and then fit Enter to indicate that the i f statement is finished.

Here is your first i f stetemest, step by step.

>>> if type(string) == StringType: [fit Return]

[fit Tab] print ("string is a StringType") [hit Return]

[fit Return]

The next three interactive sessions test whether the variable int is of type Integer, the variable float is of type Float, and the variable long is of type Long.

>>> if type(int) == IntType: ... print("int is a IntType")

int is a IntType

>>> if type(float) == FloatType: ... print("float is a FloatType")

float is a FloatType

>>> if type(long) == LongType: ... print("long is a Long")

long is a Long

Just for a sanity check, let's see if the string variable is a Float type.

>>> if type(string) == FloatType: ... print("string is a float")

Was this article helpful?

0 0

Post a comment