From 775d2d4957535c66f1f2328d0c7a522ef1070a4e Mon Sep 17 00:00:00 2001 From: Mark Pilgrim Date: Thu, 25 Jun 2009 16:47:57 -0400 Subject: [PATCH] clarify variable/value typing, mention isinstance() --- native-datatypes.html | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/native-datatypes.html b/native-datatypes.html index 8fa0ba0..5893d58 100644 --- a/native-datatypes.html +++ b/native-datatypes.html @@ -20,7 +20,7 @@ body{counter-reset:h1 2}

 

Diving In

-

Cast aside your first Python program for just a minute, and let’s talk about datatypes. In Python, every variable has a datatype, but you don’t need to declare it explicitly. Based on each variable’s original assignment, Python figures out what type it is and keeps tracks of that internally. +

Cast aside your first Python program for just a minute, and let’s talk about datatypes. In Python, every value has a datatype, but you don’t need to declare the datatype of variables. How does that work? Based on each variable’s original assignment, Python figures out what type it is and keeps tracks of that internally.

Python has many native datatypes. Here are the important ones:

  1. Booleans are either True or False. @@ -59,14 +59,17 @@ body{counter-reset:h1 2}
     >>> type(1)                 
     <class 'int'>
    ->>> 1 + 1                   
    +>>> isinstance(1, int)      
    +True
    +>>> 1 + 1                   
     2
    ->>> 1 + 1.0                 
    +>>> 1 + 1.0                 
     2.0
     >>> type(2.0)
     <class 'float'>
    1. You can use the type() function to check the type of any value or variable. As you might expect, 1 is an int. +
    2. Similarly, you can use the isinstance() function to check whether a value or variable is of a given type.
    3. Adding an int to an int yields an int.
    4. Adding an int to a float yields a float. Python coerces the int into a float to perform the addition, then returns a float as the result.