Search code examples
pythonstringreturnmessagedigits

Return/print amount of digits in a sentence OR an error message


I'm new to the site and to python so I hope I'm giving all the required information. I've already searched for this question but none of the solutions seem to work for me.

I'm trying to create a function that reads some text and returns the amount of digits it contains. For example:

"It is 2012" , should return "Text has 4 digits"

If there are no digits, it should return a different message such as:

"It is Monday" , should return "Text does not contain digits"

So I wrote this:

def CountNumbers(txt):
    sum = 0

    for n in txt:
        if n.isdigit() == False:
            print ("Text does not contain digits")

        else:
            sum += 1


    print("Text has", sum, "digit(s)")


txt = str(input("Write some text: "))
(CountNumbers(txt))

The functions seem to be OK however, the prints turn out wrong, for example:

Write some text: 65
Text has 2 digit(s) #this is ok, but...

When I only input text:

Write some text: sd 
Text does not contain digits
Text does not contain digits
Text does not contain digits
Text has 0 digit(s)

When I input text and numbers (but text first):

Write some text: sd 564
Text does not contain digits
Text does not contain digits
Text does not contain digits
Text has 3 digit(s)

I know my error lies in the blocks, (I think), but I haven't figured out a way because when I use return, it stops before it finished to read the text. I've tried about 20+ different things, please help me !

Thank you !!

P.S. I need this to work as a .py and not just in the IDLE (Python Shell) window, that's why I'm writing the blocks like this.


Solution

  • I just solved your codes problems:

    def CountNumbers(txt):
        sum = 0
    
        for n in txt:
            if n.isdigit():
                sum += 1
    
        if sum:
            print("Text has", sum, "digit(s)")
        else:
            print ("Text does not contain digits")
    
    
    CountNumbers(input("Write some text: "))