Book » Variables and Types »

 

Variables and Types

Python is a very object-oriented language. All data values are objects and all types are defined by classes unlike in other languages such as C++ and Java in which some values are primitive and others are objects. Thus, all variables in Python are references to objects.

Variable Declarations

In Python, variables are not specifically created using a variable declaration. Instead, variables are created automatically when they are assigned a value. The variable’s data type is determined by the type of data to which it references.

In the following code segment, we create three variables by assigning each an initial value. Remember, that variables are actually assigned a reference to an object of the given type and not the value itself.

=python name = "John Smith" id = 42 gpa = 3.45

Variable names in Python may only consist of letters, digits, and the underscore. And it must begin with a letter or the underscore character.

Using Variables

Some important notes related to variables:

  • An error is generated if a variable is used before it has been created.
  • If a variable is created as one type, it can not be treated as a different type. For example, if variable id contains an integer, it can not be treated as a string.


Book

© 2006 - 2008: Rance Necaise - Page last modified on August 04, 2006, at 06:10 PM