1

I'm having a little problem to understand why python won't cast a float to an int. The following is a code snippet.

import time

now = time.time()
print type(now)
int(now)
print type(now)

And this is the result I get, I can't quite figure out why. Any ideas? Thanks in advance

<type 'float'>
<type 'float'>
wind85
  • 487
  • 2
  • 5
  • 11

3 Answers3

8

You have to reassign now like so:

now = int(now)

The int() conversion does not operate in place - it merely returns the result of the conversion, which is why you need to reassign now to the new value.

As a general rule, functions return a new value, while methods operate in place. For the difference between functions and methods, see this question.

Community
  • 1
  • 1
Volatility
  • 31,232
  • 10
  • 80
  • 89
  • Thanks a lot I couldn't quite understand why, now I do. – wind85 Jan 15 '13 at 03:27
  • 1
    The important thing to remember here is that `int()` is not a C-style cast; it's the `int` constructor and it returns an integer object, so you gotta store that somewhere. – kindall Jan 15 '13 at 03:58
  • That explains why! I studied C till a couple of weeks ago. Thanks again. – wind85 Jan 15 '13 at 04:59
3

int() doesn't operate in-place. You still have to overwrite now:

now = int(now)

Although I'd just do it all at once:

now = int(time.time())
Blender
  • 289,723
  • 53
  • 439
  • 496
3

You never set now to the int version

import time
now = time.time()
print type(now)
now = int(now) # set now to int version
print type(now)
Zimm3r
  • 3,369
  • 5
  • 35
  • 53