[Tutor] Newbie - mixing floats and integers (first post)

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Apr 12 16:26:17 EDT 2004


> > So the conversion issues between strings and the primitive types are
> > also similar in Java --- the string-to-integer routines on both are a
> > bit strict. Please feel free to ask more questions.  Hope this helps!
>
> I really liked the idea of checking for a '.' and then casting
> appropriately (does casting mean anything in python)?


Hi Adam,

Not really --- the int(), float(), and str() functions aren't typecasts,
but are more 'function'-like.  In Python terminology, they are
'callables':

###
>>> int
<type 'int'>
>>> float
<type 'float'>
>>> callable(int)
True
>>> callable(float)
True
###

So you can think of them as functions that take any input, and they either
return their namesake, or raise an exception if they have problems.
Because they're callables, it makes sense to call str() on anything:

###
>>> str('hello world')
'hello world'
>>> str(42)
'42'
>>> str([1, 2, 3, 4, 5])
'[1, 2, 3, 4, 5]'
###



In Java, one of the most frequent occurences of typecasting is when we we
use Java's generic container classes:

/*** Pseudo-Java ***/
for(int i = 0; i < someListOfNames.size(); i++) {
    String name = (String) someListOfNames.get(i);
    ...
}
/******/


In Python, though, we don't have to worry about typecasting:

### Pseudo-Python -- (purposely structured similar to Java code: better to
###                   use 'for name in someListOfNames:...')
###
for i in range(len(someListOfNames)):
   name = someListOfNames[i]
   ...
###


An object's 'type' is attached to the value, and not to the name.

###
>>> def printType(thing):
...      print "the type of", thing, "is:", type(thing)
...
>>> printType(42)
the type of 42 is: <type 'int'>
>>> printType("adam")
the type of adam is: <type 'str'>
###


> I'm also glad to report that my experience here (albeit a short one) is
> much more positive than the brief experiences I had within the java help
> community (although, I imagine that they are normally helpful).

The forums at:

    http://forum.java.sun.com/

do seem active; have you asked your questions there?



Hope this helps!




More information about the Tutor mailing list