0

Now this could be me being very stupid here but please see the below code.

I am trying to work out what percentage of my carb goal I've already consumed at the point I run the script. I get the totals and store them in carbsConsumed and carbsGoal. carbsPercent then calculates the percentage consumed. However, carbsPercent returns 0 each time. Any thoughts?

#!/usr/bin/env python2.7
import myfitnesspal
from datetime import datetime

username = 'someusername'
password = 'somepassword'

date = datetime.now()


client = myfitnesspal.Client(username, password)
day = client.get_date(date.year, date.month, date.day)
#day = client.get_date(2015,11,12)

carbs = 'carbohydrates'

carbsConsumed = day.totals[carbs]
carbsGoal = day.goals[carbs]
carbsPercent = (carbsConsumed / carbsGoal) * 100

print 'Carbs consumed: ' + str(carbsConsumed)
print 'Carbs goal: ' + str(carbsGoal)
print 'Percentage consumed: ' + str(carbsPercent)
alvas
  • 115,346
  • 109
  • 446
  • 738
Mike Resoli
  • 1,005
  • 3
  • 14
  • 37

2 Answers2

5

Try this:

 carbsPercent = (float(carbsConsumed) / carbsGoal) * 100

The problem is that in Python 2.7, the default division mode is integer division, so 1000/1200 = 0. The way you force Python to change that is to cast at least one operand IN THE DIVISION operation to a float.

gariepy
  • 3,576
  • 6
  • 21
  • 34
  • 1
    Or `100. * carbsConsumed / carbsGoal` – arekolek Nov 13 '15 at 16:31
  • 1
    Correct, but that only works because the `100.` is first. It will not work if you use the order from the OP's code. – gariepy Nov 13 '15 at 16:34
  • 2
    I believe alvas's solution below, of using the float division operator, clutters the code less, and will go away naturally when upgrading to python3. – spectras Nov 13 '15 at 17:02
4

For easily portable code, in python2, see https://stackoverflow.com/a/10768737/610569:

from __future__ import division
carbsPercent = (carbsConsumed / carbsGoal) * 100

E.g.

$ python
>>> from __future__ import division
>>> 6 / 5
1.2

$ python3
>>> 6 / 5
1.2
Community
  • 1
  • 1
alvas
  • 115,346
  • 109
  • 446
  • 738