Marc Chen - 3 months ago 13

Python Question

Please bear with my novice question as I just started learning Python (2.x).

I'm trying to run a script where user could enter any number (e.g. ints or float) and the expected output would be the total digit numbers of that input number.

However, I've encountered the following problems and wondered if you could kindly help guide me through solving them. Many thanks!! :)

(problems)

- In the printout message, the n value was always 0; whereas I wished to print out the original input number by the user.
- I wished it would also process the float number. For now, a 'ValueError' was returned and the script was halted whenever a float number was entered.
- If user enters any string or blank character, the script should ignore the input and repeat all over again asking for the user input until the number with correct format (i.e. either integer or float number) was entered.

`def num_digits(n):`

count = 0

while n:

count = count + 1

n = n/10

print 'The total digits for this number, ', n, ', are: ', count

return count

user_input = abs(int(raw_input('Enter a number:\n')))

num_digits(user_input)

Answer

Since you also want to be able to count the digits of floats, simply doing `n/10`

isn't enough. With float values, your loop will end up being infinite, since it will be doing float division instead of int division. (Ex. `16.3 / 10 = 1.63`

--> `1.63 / 10 = .163`

etc -- it will never reach `0`

)

To avoid this problem, I recommend treating the number as a string and counting the number of characters in the string which are digits.

```
def num_digits(n):
count = 0
curr = n # remaining string you're currently evaluating
while (curr != ''):
digit = curr[len(curr)-1] # get final char
curr = curr[:len(curr)-1] # trim last char off the string
if (not digit.isdigit()):
# ignore things like decimal points or negative signs
continue
count += 1
return count
while True:
value = raw_input('Enter a number:\n') # keep it in string form
try:
convert = float(value) # if it's a valid float, then it's also a valid int
break
except:
print "not a number. enter a valid number"
nd = num_digits(value)
print('{} has {} digits'.format(value, nd))
```

Sample output:

```
# float number, ignores negative sign and decimal point
$ python script.py
Enter a number:
-16.3
-16.3 has 3 digits
# asks for input until it has a valid number
$ python script.py
Enter a number:
foo
not a number. enter a valid number
Enter a number:
blah3
not a number. enter a valid number
Enter a number:
89
89 has 2 digits
```

Source (Stackoverflow)

Comments