Reputation:
I'm writing a program on Python 3.6.1 that counts the number of digits of a given number by the user. I'm using the sentence "while True" and not functions or strings because I haven't learned to use them yet. Here is my code:
number=int(input("Write number: "))
cont=0
while True:
number=number/10
cont=cont+1
if number==0:
break
print("The number of digits is: ", cont)
My problem is the the above code isn't working because when I put, let's say 123, the program gives me the value 326. I don't know what is wrong with my code, so how could I fix this?
Upvotes: 1
Views: 182
Reputation: 11
you can try this way
number = int(input("Write Number:"))
b = len(str(number))
print(b)
or you can change '/' into '//' , it does work
update
b = len(str(abs(number)))
Upvotes: 0
Reputation: 18916
Is there a specific reason you don't convert the number to a string and use len(string)?
len(str(number))
Update (thanks to comment):
len(str(abs(number)))
Upvotes: 1
Reputation: 881623
Have a look at this:
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 123 / 10
12.3
Yes, /
is floating point division in Python so it's not doing what you expect.
You can see what's actually happening if you insert print(number)
immediately after the division-by-ten. It does division continuously until it gets a number so small it cannot tell the difference between it and zero:
12.3
1.23
0.123
0.0123
0.00123
0.000123
1.23e-05
1.23e-06
1.23e-07
1.2300000000000001e-08
1.23e-09
1.2300000000000001e-10
1.2300000000000002e-11
1.2300000000000002e-12
1.2300000000000003e-13
1.2300000000000003e-14
1.2300000000000003e-15
:
1.2299999999999997e-307
1.2299999999999997e-308
1.23e-309
1.23e-310
1.23e-311
1.23e-312
1.23e-313
1.23e-314
1.23e-315
1.23e-316
1.23e-317
1.23e-318
1.23003e-319
1.23e-320
1.23e-321
1.24e-322
1e-323
0.0
You can fix this by changing:
number=number/10
into either of:
number = int(number / 10)
number = number // 10
This will do integer division so will stop after the correct number of steps.
Upvotes: 1
Reputation: 7187
Python 3 does floating point division by default. You need to use integer division. number = number // 10
.
Upvotes: 0