[Tutor] declarations

alan.gauld@bt.com alan.gauld@bt.com
Mon, 8 Apr 2002 11:27:31 +0100


> Can you declare variable types like in C++ in Python.
> example:
>
> int variableName = 0
> float variableName = 0.0

No. Python variables are references to objects. The objects 
all have a type but the variables themselves are essentially 
typeless. Thus you can change the type of object a Python 
variable references:

foo = 7       # initially foo is an integer
foo = "baz"   # now foo is a string....

This is one of the ways that Python is much more flexible 
than C++. C++ tries to eliminate some errors at compile 
time by checking that the types passed to functions are 
consistent, Python performs this check at runtime so we 
need to use try/except handling to catch and handle the 
errors.. There are pros/cons with each approach.

Alan g.