I don't know what I've done wrong. And I don't understand about the new last function since this is an answer that the teacher gave me and it still doesn't work.
def validate(s):
if len(s) != 8:
return 0
else:
counter = 0
for element in s:
if element in "0123456789":
counter = counter + 1
return counter == 2
counter = 0
for element in l:
if validate(element):
counter = counter + 1
return counter
def countChoose(s)
counter = 0
for c in s:
if validate(element):
counter = counter + 1
return counter
The statement says to have 8 characters and 2 numbers. It sounds like you've interpreted "8 characters in total, of which 2 must be digits". Although it could also be understood that with 8 characters he meant 8 letters. So the string would have length 10 (8 letters and 2 numbers).
For now I'll stick with your interpretation. Then:
So let's analyze your function step by step:
So far it starts well.
s
is the string to parse, and if it doesn't have exactly 8 letters it no longer meets a condition, so you return 0.In another case:
We were doing well until the return. You have a counter, which starts at zero. For each character in
s
, you check to see if it is a digit, and in that case you add 1 to the counter and return a boolean that checks if itcounter
is 2 .Therefore, when it finds the first digit, it
counter
will become 1 and you will returnFalse
(since itcounter
is 1 and not 2).This is wrong for two reasons. First, because you return prematurely (you don't know if there will be more digits) and second, because you return a boolean, when the function should return 0 or 2, but never
True
orFalse
.What follows no longer matters, since you have already returned anyway. Therefore, it never gets executed. Anyway, it was also wrong and I don't see the point:
Why do you reset the counter to zero? Then you iterate over another variable
l
that actually doesn't even exist. It doesn't give you an error because as I said, this part never gets executed. And then you call avalidate()
for each element ofl
.validate()
it's the actual function you're writing, so it would be calling itself, but this time you're not passing it a string, but an element ofl
(I don't know what you had in mind, but this can't be right , since in this calllen(elemento)
it will certainly not be 8, so the function will always returnFalse
.At the end you return the counter. If that instruction were to be executed (which would only happen if you have not found any digits in the string, because if you find one we have already seen that you return immediately), the counter would still be zero, so in that case you would return zero.
I don't know why you complicated the loop so much, it was working fine at first. All you had to do was count how many digits there were and, after counting them, you would check if they were exactly two.
Namely
As for the other function that you put, I do not understand its purpose or what you are asking.