-3

I am taking the Python class at codecademy and I am supposed to print each item in a pair of dictionaries, followed by their prices and amount in stock. Here is the code I wrote:


prices = { 
    "banana" : 4,
    "apple"  : 2,
    "orange" : 1.5,
    "pear"   : 3,
}
stock = {
    "banana" : 6,
    "apple"  : 0,
    "orange" : 32,
    "pear"   : 15,
}

for fruit in prices:
    print fruit
    print "price: %d" % prices[fruit]
    print "stock: %d" % stock[fruit]

The output is correct for everything except the price of an orange. Using %d, it prints a value of 1. When I replace %d with %s, the correct value of 1.5 is printed, but I don't understand why %d does not work with decimal values. 1.5 is a number, so shouldn't I be using %d rather than %s in this case?

Marjona6
  • 13
  • 1
  • 4
  • 1
    I can only guess that the interpreter converts %d to int and %s to string prior to printing. But I am not sure. – Tony Tannous Mar 03 '17 at 12:00
  • @TonyTannous Guessing is not your only option. `%d` is for integers, `%f` is for floating point numbers. See [the documentation](https://docs.python.org/2/library/stdtypes.html#string-formatting). – Peter Wood Mar 03 '17 at 12:02
  • `%d` takes an *integer number*. Compare `int(1.5)` with `str(1.5)`. – Martijn Pieters Mar 03 '17 at 12:02

2 Answers2

1

%d convert to decimal, which doesn't have floating part

%s keep the float and display it entirely on screen

if you want to print floats, use %f

Romain Jouin
  • 4,448
  • 3
  • 49
  • 79
1

Because %d is Format for Digit Numbers like Integer, you should use %f instead ^^ this is for floating point numbers.

maxbit89
  • 748
  • 1
  • 11
  • 31