What’s behind the "go"?

Asked

Viewed 242 times

12

Day I came across a question from a user who wanted to print a string, but with time interval between each character, so I suggested that it use the following code:

from time import sleep
frase = ("Boa noite a todos!")
for i in range(len(frase)):
    print(frase[i],end = "")
    sleep(0.5)

Another user in the same forum suggested the following solution below:

from time import sleep
frase = 'Boa noite'
for letra in frase: 
    print(letra, end="")
    sleep(0.5)

I was curious especially with this line of code: for letra in frase:

How does Python know that that character is called a letter? Worst of all, when I replaced letra for for bola in frase: and the code kept working, so yes bugle for good.

4 answers

14


How does Python know that that character is called a letter?

The line is saying.

when I replaced the letter with for bola in frase: and the code continued to work

And why would it be different?

You are free to name any variable as you wish. It is advised to use a meaningful name, but you can write any valid name for a code identifier following the syntax rules defined for Python.

In fact your original code already shows this, you used i and it also worked, even though your code did a lot of unnecessary stuff. You tried to reproduce the for gross of other languages, which is rarely necessary. The for, also known as for each, is usually more suitable in most situations because it is used to "scan" a collection of data, it is rare that you need to use it as a counter, as was used in your reply in the mentioned forum. The for aims to pick up a collection and go throwing an element of it into a variable to be used in each step, much simpler and less chance to do something wrong.

To remedy the question posed below, if by chance the interpretation is other than the question, and nothing in the question indicates anything else, and if so the question is not clear, I will ask more about.

The for, at least in Python, it is a project pattern, like many others, that exist in the syntax of the language to facilitate the use of something very common avoiding errors, as I said before, and as it is a variable and other mechanisms.

That one Pattern design exists because it is common to need to go through a collection of data. In Python the most known collection is the list, another is the dictionary. But the most used is the collection string, which is nothing more than a list of characters. As it is so used it has a literal that lets you create a value with each character being written together without separators, only delimited by quotation marks (single or double).

Every data collection has some mechanisms to manipulate its content. One of them is the method __iter__(). It provides an object that controls access to the data list, and with this object you can do some things, among them the most important is to go to the next item, with the __next__().

So if you are going to create a type that is a collection it is your obligation to create these methods in this type for it to properly process the iteration.

Your code actually looks like writing:

tmp_iter = frase.__iter__()
while True:
    try:
        letra = tmp_iter.__next__()
        print(letra, end = "")
        sleep(0.5)
    except StopIteration:
        break

I put in the Github for future reference.

What is said in passing is not a very efficient way, but Python does not have this commitment.

Obviously there is simplification there and there are several other ways to deal with it and different methods in the process.

  • So basically he interpreted the string as a list?

  • 5

    One string is a list of characters. The translation of the word is string, which can be interpreted also as set, collection, sequence, something being put one after another.

  • 1

    I think his doubt was more related to finding that letter was a special member or function of the phrase object.

  • 1

    @Philip my interpretation is not this, and as the acceptance was given in this answer it seems to me that he agreed with my interpretation. Too bad I get a negative for a right answer. If I use the cri Erio of the interpretation of what the question is, I could negate yours for having interpreted it differently than I will but obviously I won’t do it because it would be voting for wrong reasons, as you did.

  • Fair. I think who has to solve this is who asked too, I changed my vote.

6

See documentation on the statement for and Iterators. In the statement for letra in frase: we have the following:

  1. for calls the function __iter__() of the object frase.
  2. The function __iter__() returns an object called iterator, that is able to access the successive objects of frase through the function __next__()
  3. The result of the __next__() is to be stored in letra.

Hence the magic you observed. The statement for does not know, at first, how to access the values of the object frase. So what she does is to ask for frase an object that knows. This object, called iterator, has a function called __next__() which is accessed by the loop for and returns next element of the sequence. letras is just a variable that receives the result of __next(), it could have any name and is not related in any way to the object frase.

To be less abstract, you can implement the statement for letra in frase: on the arm:

>>>frase = "Boa noite a todos!"
>>>iterador = frase.__iter__()
>>>iterator
<str_iterator object at 0x000001ADA25DCE80>
>>>letra = iterador.__next__()
>>>letra
'B'
>>>letra = iterador.__next__()
>>>letra
'o'
>>>letra = iterador.__next__()
>>>letra
'a'

See again what you could have called letra of anything. It is only the object that stores the result of iterador.__next__().

4

I believe you "bugged" to interpret this new code suggested by another forum user since the variable "phrase" is just a string, but a string is a string (char), then when you use the for (which in Python also serves as foreach) he takes the jail (array) of characters and then goes through each character ie and as if it were a array in this way:

['B', 'o', 'a', ' ', 'n', 'o', 'i', 't', 'e']

Now see the same code with this view, as it becomes simpler and more understandable:

from time import sleep
frase = 'Boa noite'
for letra in frase: 
    print(letra, end="")
    sleep(0.5)
  • I didn’t quite understand this second block, it seems identical to the question. That’s right?

  • 1

    But it’s the same as the question, as he already knows that it works and he was just doubting how it works, I explained and then put the code again for him to read with the new information.

  • I got it, @Bacco quiet.

  • 1

    @Cadu thought it best to ask. because it could be intentional (as confirmed), a mistake at the time of necklace, or even I have not noticed the difference. As clarified, I delete this comment here and the previous ones

3

python has the iteration protocol, where all the sequence is an iterable, the proof of this is the implementation of the method iter in the object

dir('teste')#vc vai achar __iter__ no meio dos métodos
dir([1,2,3])#__iter__ também esta presente aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.