Python Forum

Full Version: Assistance with making functions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Howdy, this is not homework rather I want to know if its possible regardless of how inefficient the process is. Im attempting to create a function that checks if a string contains a digit and if it does prints out saying "Has no Digits: False" and allows to user to indefinitely.

I just cant quite work out how to loop back so the "s" input to make in indefinite

def strchk():
    s = input(("Enter a string: "))
    x = str.isdigit(s)
    while x == True:
        print(("Has no Digits: False"))
    if x == False:
        print(("Has no Digits: True"))

strchk()
Loop over the characters in the string (for char in s:). Check each character to see if it is a digit. If it is, return True. If you get to the end of the loop, none of the characters are digits. So just return False after the loop.
Hello,

You mean that you need something like the following code?

def strchk():
    s = input(("Enter a string: "))
    dig = False
    for x in s:
        if x.isdigit():
            dig=True
    return dig

while True:
    if strchk()== True:
        print("Has no Digits: False")
    else:
        print("Has no Digits: True")
@bobfat that's different from ichabod's suggestion because ichabod's will short-circuit. You see how you complete the whole loop even if the first character is a digit? What you can do instead is to just return True within your if, and return False if the loop exits without the inner return.

Also, this looks like homework, so even though the OP says it isn't, I'd recommend not providing a full function to do what they're looking for, unless it's trivial...

And if the OP isn't doing this as homework, and they can use whatever module they want, they can have a one-liner:
import re

def contains_digit(string):
   return re.match(r'.*\d', string) is not None
In use:
Output:
>>> contains_digit('abc 123') True >>> contains_digit('abc one two three') False
You're right :)