0

Possible Duplicate:
how can I force division to be floating point in Python?

I'm very sorry if this question has been asked already.

timothy_lewis_three_pointers_attempted = 4
timothy_lewis_three_pointers_made = 2

print 'three pointers attempted: ' + str(timothy_lewis_three_pointers_attempted)
print 'three pointers made: ' + str(timothy_lewis_three_pointers_made)
print 'three point percentage: ' + str(timothy_lewis_three_point_percentage)

I'm getting 0 for the percentage. How do I get it to say .5? I know that if I type the numbers as 4.0 and 2.0, I'll get the desired result, but is there another way of doing it?

Community
  • 1
  • 1
dylan
  • 51
  • 1
  • 1
  • 4
  • BTW, you can write `print 'three pointers made:', timothy_lewis_three_pointers_made` to do the same thing -- this is how `print` is normally used – Mike Graham Feb 26 '14 at 02:38

3 Answers3

2

The other option you have (although I don't recommend it) is to use

from __future__ import division

and then

>>> 7 / 9
0.7777777777777778

This is based on PEP 238.

Ryan O'Neill
  • 3,617
  • 21
  • 27
1

Make one of them a float:

float(timothy_lewis_three_pointers_made) / timothy_lewis_three_pointers_attempted
Ry-
  • 209,133
  • 54
  • 439
  • 449
1

You are doing integer division. Make at least one of them a float value

percentage = float(_made) / float(_attempted)

You can also get nicer looking output for percentages by using the new string format method.

"Three point percentage: {:.2%}".format(7.0/9)
# OUT: ' Three point percentage: 77.78%'
Keith
  • 40,128
  • 10
  • 53
  • 74