0

Python freeze without error by a simple program if you enter a number with a comma .

-Example for a number: 3.51

the task: Write a program that names an amount entered as the minimum number of coins making up this amount.

-Code made with Python 3.7.1:

print("please enter one euro amount!")
x=float(input())
a=[]
while x>0:
    if x>=2:
        a.append("2€")
        x=x-2
    elif x>=1:
        a.append("1€")
        x=x-1
    elif x>=0.50:
        a.append("50c")
        x=x-0.50
    elif x>=0.20:
        a.append("20c")
        x=x-0.20
    elif x>=0.10:
        a.append("10c")
        x=x-0.10
    elif x>=0.05:
        a.append("5c")
        x=x-0.05
    elif x>=0.02:
        a.append("2c")
        x=x-0.02
    elif x>=0.01:
        a.append("1c")
        x=x-0.01
print("You need at least",len(a),"coins:",a)

no result python freezed /:

Johnny C.
  • 9
  • 2

2 Answers2

1

The problem is that at some point the variable x is taking a value smaller than 0.01 and at this point your while loop will run forever because you don't have an "else:" statement to break that loop and with that value the code will never enter into any of the "elif ... :" statement you wrote. This is your same code but with an "else" at the end of the loop (assuming that a value that is less than 0.01 is irrelevant to your problem), try it:

print("please enter one euro amount!")
x=float(input())
a=[]
while x>0:
    print(x)
    if x>=2:
        a.append("2€")
        x=x-2
    elif x>=1:
        a.append("1€")
        x=x-1
    elif x>=0.50:
        a.append("50c")
        x=x-0.50
    elif x>=0.20:
        a.append("20c")
        x=x-0.20
    elif x>=0.10:
        a.append("10c")
        x=x-0.10
    elif x>=0.05:
        a.append("5c")
        x=x-0.05
    elif x>=0.02:
        a.append("2c")
        x=x-0.02
    elif x>=0.01:
        a.append("1c")
        x=x-0.01
    else:
        break

print("You need at least",len(a),"coins:",a)
Jorge Morgado
  • 1,148
  • 7
  • 23
0

Binary floating point numbers can't represent 0.1 so using floating point numbers can have unexpected results. When you subtract 2.0 the result isn't 1.51 as you would expect.

>>> 3.51 - 2.0
1.5099999999999998

The best thing to do is to multiply the users input by 100 and then do integer math (rounding the original result to ensure it is an integer).

Lianne
  • 108
  • 7