-2

in this video(at 7min30seconds), the code bellow I copied from this video returns 3, although mine returns 4.04. I do not understand why codes in the video returns Int, though mine returns Float.

https://www.youtube.com/watch?v=HWW-jA6YjHk&list=UUNc-Wa_ZNBAGzFkYbAHw9eg&index=29

def num_coins(cents):
    if cents < 1:
        return 0
    coins = [25, 10, 5, 1]
    num_of_coins = 0
    for coin in coins:
        num_of_coins += cents / coin
        cents = cents % coin
        if cents == 0:
            break
    return num_of_coins

print(num_coins(31))
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 4
    In Python 3, diving ints using `/` produces a float. In Python 2, diving ints using `/` produces an int. If you want to produce an int, use `//` instead. – khelwood May 29 '20 at 13:51
  • Adding to @khelwood's answer, you can type cast the division `int(cents / coin)` – Abhishek May 29 '20 at 13:53
  • @Abhishek why type `int( )` (5 extra symbols) when just 1 more, `/`, suffices? – John Coleman May 29 '20 at 13:54
  • 1
    @JohnColeman It help me be specific about where type conversions are happing – Abhishek May 29 '20 at 13:56
  • 1
    @Abhishek But `cents//coin` involves no implicit type conversion. Those are two integer variables and `//` is an integer operation. It is not an alias for `int( / )`. The only reason the YouTube code worked as it did is because in that case Python 2 was in fact using the operation which is known as `//` in Python 3, so using `//` is the way to make more explicit what is happening. – John Coleman May 29 '20 at 13:59

1 Answers1

-1

Use this to get the right answer :

def num_coins(cents):
    if cents < 1:
        return 0
    coins = [25, 10, 5, 1]
    num_of_coins = 0
    for coin in coins:
        num_of_coins += int(cents / coin)
        cents = cents % coin
        if cents == 0:
            break
    return num_of_coins

print(num_coins(31))

/ operator is not similar for python 2 and python 3

sau
  • 1,316
  • 4
  • 16
  • 37