cjm2671
cjm2671

Reputation: 19476

How do I make a float in Python?

If I do:

width =  14
height = 6
aspect = width/height

I get the result aspect = 2 rather than 2.33. I'm new to Python and expected it automatically cast this; have I missed something? Do I need to explicitly declare a float?

Upvotes: 2

Views: 122

Answers (1)

unutbu
unutbu

Reputation: 879611

There are many options:

aspect = float(width)/height

or

width = 14.       # <-- The decimal point makes width a float.
height 6
aspect = width/height

or

from __future__ import division   # Place this as the top of the file
width =  14
height = 6
aspect = width/height

In Python2, division of integers returns an integer (or ZeroDivisionError). In Python3, division of integers can return a float. The

from __future__ import division

tells Python2 to make division behave as it would in Python3.

Upvotes: 8

Related Questions