-2

Here is my code, its supposed to tell me the count number of the decimal digits in a positive and negative integers.

def num_digits(n):
    count = 0
    for i in range(0, len(str(n))):
        count += n % 10
        n = n // 10
    return count


num_digits(2)
print()
print()
num_digits(12)
print()
print()
num_digits(123)

When I run the program I get nothing
Can you please show me the full code written correctly

  • 3
    You are ignoring the value returned from the function and doing empty print. Try `print(num_digits(2))` – Moinuddin Quadri Jan 13 '18 at 19:07
  • 2
    Why not: `len(str(abs(number)))` ? – Nir Alfasi Jan 13 '18 at 19:08
  • You are right now it prints a the number of digits but it adds one to them so like for print(num_digits(2)) --- it prints 2 when its supposed to print 1 – HIKMAT BITTAR Jan 13 '18 at 19:09
  • ... Or assign the return value and print it: `n = num_digits(2); print(n)`. – wwii Jan 13 '18 at 19:09
  • You do understand that `print()` is just printing an empty line, right? ;) – Nir Alfasi Jan 13 '18 at 19:10
  • Can you please rights the full code I'm a beginner to python – HIKMAT BITTAR Jan 13 '18 at 19:11
  • the print() is to add line breaks – HIKMAT BITTAR Jan 13 '18 at 19:11
  • `num_digits(2)` returns a value- which is not saved nor printed anywhere – Nir Alfasi Jan 13 '18 at 19:12
  • add `print(f'count:{count} n:{n} n%10:{n%10}')` as the first line in the for loop. It will help you visualize the process. – wwii Jan 13 '18 at 19:13
  • 2
    Welcome to SO. Unfortunately this isn't a discussion forum or tutorial service. Please take the time to read [ask] and the other links on that page. You should invest some time working your way through [the Tutorial](https://docs.python.org/3/tutorial/index.html), practicing the examples. It will give you an introduction to the tools Python has to offer and you may even start to get ideas for solving your problem. – wwii Jan 13 '18 at 19:14
  • I just need someone to right the full correct code and then I would see what I did wrong – HIKMAT BITTAR Jan 13 '18 at 19:16
  • Possible duplicate of [Length of an integer in Python](https://stackoverflow.com/questions/2189800/length-of-an-integer-in-python) – Darkonaut Jan 13 '18 at 20:09

2 Answers2

0
def num_digits(n):
    count = 0
    for i in range(0, len(str(n))):
        print(f'count:{count} n:{n} n%10:{n%10}')
        count += n % 10
        n = n // 10
    return count


num_digits(2)
print()
print()
num_digits(12)
print()
print()
num_digits(123)

This kind of works but I need it to be better

0

correct code for your requirment

def num_digits(n):
    count = 0
    while n>0:
      count+=1
      n=n//10
    return count

print(num_digits(2))
print(num_digits(12))
print(num_digits(123))
Jay Shankar Gupta
  • 5,918
  • 1
  • 10
  • 27