You have to convert the int
object from your for
loop to a str
object because if a in b
only works for a
and b
as an string (str
) object. And you have to remove one return
from the loop. Otherwise the method isDigit
will end with true
or false
at the first letter of your string.
def has_digits(string):
for r in range(0, 10):
if str(r) in string:
return true
return false
print(has_digits("Python3"))
>> true
Now the method will return true
if your string contains a digit. Otherwise it will loop further through the string and check the next letters. At the end the method returns false
because the string ends and the method doesn´t return with true
from the loop.
How does this code works now?
Assume that you pass the string Python3
into the method has_digits
then the first for
loop iterate over the numbers 0
to 9
. So during the first loop r
is equal 0
. Now the conditional check if str(r) in string
will occur. The if
statement checks if str(0)
("0"
the string version of the number 0
) is in the string string
(which is your Python3
). There is no "0"
in it, so the condition is false
and the for
loop continues with 1
. The whole procedure repeat until 3
. For 3
the if
statement returns true
, because "3"
is in Python3
and now the method will return true
which signal that your string has at least one digit.