What the algorithm seeks is to count the number of "@" characters in a string. To do this, use a while
loop, which iterates (repeating a block of code) while its control condition (which follows it when it is declared) is evaluated as true.
What we want therefore is to iterate over the characters of the chain one by one, see if the character is an "@" ( if mail[x]=='@'
) and if affirmative increase the counter of "@" in one ( cantidad=cantidad+1
).
The variable x
represents the index that has the character in the string, the indexes in Python start at 0 and we want to iterate from the first character (index 0) to the last one (whose index is the length of the string minus 1, having begun to count on 0). That's why the condition of while
is:
x<len(mail)
The built-in len
returns the length or number of items in an iterable , in this case returns the number of characters in the string mail
.
Therefore x
is initialized to 0 before while
(to start with the first character) and in each iteration it increases by 1 to move to the next character, that's what x=x+1
does, this it does not initialize the cycle again, it only increases the control variable of it. while x<len(mail)
is "translated" into " as long as x is less than the mail length ".
If we do not increase x
within the cycle the condition x>len(mail)
would always be true given that x
would always be 0 (initial value) and we would have an infinite cycle (unless mail
was an empty string) .
To understand how the characters are obtained, let's see an example:
>>> cad = "Hola"
>>> len(cad) # Longitud de la cadena, 4 caracteres
4
>>> cad[0] # Carácter en posición 0
'H'
>>> cad[1] # Carácter en posición 1
'o'
>>> cad[2] # Carácter en posición 2
'l'
>>> cad[3] # Carácter en posición 3
'a'
>>> cad = "Hola"
>>> indice = 0
>>> while indice < len(cad):
print("indice: {} - cad[indice]: {}".format(indice, cad[indice]))
indice += 1
indice: 0 - cad[indice]: H
indice: 1 - cad[indice]: o
indice: 2 - cad[indice]: l
indice: 3 - cad[indice]: a
The comparison is if cantidad==1:
because we want to validate that the string only contains one @ , neither less nor more, any other possibility is an invalid email.
It should be noted that this is a very bad way to iterate over a string in Python, it is inefficient and "ugly". Python allows you to iterate over a string (or any iterable when we do not plan to modify its length while iterating over it) with a for in
, much more efficient and readable than a while
and indexed. We can do something similar but more efficient and "python" therefore:
contador = 0
for caracter in mail:
if caracter == "@":
contador += 1
Or use a generator with sum
:
contador = sum(caracter == "@" for caracter in mail)
Or directly use str.count
which would be logical:
contador = mail.count("@")