Process character string with while loop

1

Someone could explain the logic of this exercise is not very clear to me

It's about entering an email and checking if it has the "@" character

mail=input("Ingrese un email")
cantidad=0
x=0

while x<len(mail): #<-Esto no me queda claro lo que hace
   if mail[x]=='@'
      cantidad=cantidad+1 #Aqui es donde se guarda en la variable cantidad el caracter '@" ?
   x=x+1 #porque se vuelve a iniciar el bucle?

if cantidad==1: # Porque cantidad se compara a 1?
     print("Contiene solo un caracter @ el mail introducido")
else:
     print("Incorrecto")

Thanks for your time ...

    
asked by Rebc3sp 01.05.2018 в 14:19
source

3 answers

0

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("@")
    
answered by 01.05.2018 / 15:10
source
0

We will analyze and explain your code line by line

1.- enter the email from the command line
2.- set the flag "amount" = 0
3.- set the flag "x" = 0;
4.- as long as the value of "x" is less than the length of characters of the repeat mail,

  

this line is a block of code that when it reaches the end will return here and repeat the previous condition, if the condition is valid the code block will be repeated, if it is not valid it will jump to the end of the block

5.-if mail [x] is equal to "@" then

  

mail is a string or arrangement of characters, to access a position of the array or the string in specific you can use the brackets [], as initial x is = 0, then the first position of the array will be analyzed

6.- quantity = quantity + 1, if condition ends | 7.- x = x +, End cycle while

    
answered by 01.05.2018 в 15:46
-2
email = '[email protected]'

validate = email.split('@')
if(len(validate) == 2):
    print('Contiene solo un caracter @ el mail introducido')
else:
    print("Incorrecto")

the variable email contains a string with the mail and with method str.split() , email.split('@') breaks the string where it finds a '@' and returns a list with the strings divided in this case ['user', 'correo.com'] and finally we validate, si the list has length equal to 2 that means that the mail only has one @ and is a correct email, otherwise else is if the mail has no @ or has more than one @

    
answered by 01.05.2018 в 22:47