[Tutor] declarations
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Mon, 8 Apr 2002 00:43:55 -0700 (PDT)
On Mon, 8 Apr 2002, dman wrote:
> On Sun, Apr 07, 2002 at 05:53:07PM -0500, Cameron Stoner wrote:
> | Hi all,
> |
> | Can you declare variable types like in C++ in Python.
> | example:
> |
> | int variableName = 0
> | float variableName = 0.0
> | char variableName = " "
Not quite --- what we think of as a "type" in Python is tied to the values
that we can compute or assign directly. In contrast, a static language
like C++ ties the "type" to the variable name.
As a concrete example, the following in Python:
###### Python
>>> x = 4
>>> x + 2
6
>>> x = "four"
>>> x + "two"
'fourtwo'
######
shows that 'x' can refer to different "types" of things.
In contrast, C++ forces variable names to hold only specific variable
types.
////// C++
int x = 4.2; // <-- Should probably produce a warning and truncate
// x to 4.
//////
If it helps, think of Python variable names as big arrows pointing at
values like "42":
x --------------> "42"
C++ variables would look more like rigid boxes that contain things:
x
+----+
| 42 |
+----+
and the rigidity comes into effect when we try stuffing in different
values like floats --- different types will either bend (if the compiler
like to be quiet), or will protest vehemently (if we turn on all
warnings).
To force values to bend into a variable's type in C++, we can use a
typecast... but if your teacher is a C++ guru, they'll yell at me for
saying that. *grin*
Hope this helps!