Why does '-1' have to be placed right after a variable?

Asked

Viewed 197 times

2

Note: the code is from a book that teaches programming

Code:

def transação_salva(preço, cartão_de_crédito, descrição):
    arquivo = open("transactions.txt", "a")
    arquivo.write(" %s %16.2f \n %s %16s \n %s %17s \n ------ \n" % ("Preço:", preço, "Cartão de crédito:", cartão_de_crédito, "Produto:", descrição))  
    arquivo.close()
itens = ["DONUT", "LATE", "FILTER", "MUFFIN"]
preços = [1.50, 2.0, 1.80, 1.20]
r = True
while r:
    opção = 1
    for escolha in itens:
    print(str(opção) + ". " + escolha)
    opção = opção + 1
    print(str(opção) + ". Quit")
    escolha = int(input("Escolha uma opção: "))
    if escolha == opção:
        r = False
    else:
        desconto(preços[escolha -1])
        cartão_de_crédito = input("Número do cartão: ")
        transação_salva(preços[escolha -1], cartão_de_crédito, itens[escolha -1])

I want to understand why (for example) the 'choice' variable of the last line has to be followed by a '-1'

  • 1

    I believe the indentation of the first for, within the while, is incorrect. By logic, print and opcao = opcao+1 would be inside the for.

  • The identation is correct, the program needs to show numbers that are in the 'option' variable that needs to increase with each loop, so that the user can choose from them later. And print is also correct because the options that will change with each loop are shown on the screen as well. But thanks for the remark.

  • Exactly, they are at the same level of indentation, so they are not within the for.

  • It really is the identation is wrong. Thank you

  • Note: the word identation does not exist in the Portuguese language. When referring by text indents, the correct is indentation.

1 answer

13


In Python, as in many other programming languages, the index in vectors starts at zero. However, it is not common for you to provide the user with a list of options that starts at zero, usually starting at 1:

1 - Opção A
2 - Opção B
3 - Opção C

This is what happens in this case. Note that the option variable has initial value 1 and the options are printed as follows:

1. DONUT           # índice 0 de itens
2. LATE            # índice 1 de itens
3. FILTER          # índice 2 de itens
4. MUFFIN          # índice 3 de itens

Do you realize that for choice X, the respective index is X-1? This is why -1 is next to the variable escolha, within the variable index precos. If the user chooses option 1, access index 0, if option 2, index 1, so on.

Related question: Why the array index and other sequences start at zero?

Terminology

By vector, the general concept of vectors is applied in programming: a list of variables of the same type, accessible by a single name, differentiated by an index (roughly, not to go into too much detail). That is, in Python, the simplest vector is implemented by the data type: list:

v = ["maçã", "banana", "laranja"]

We have a list of string, accessed by the same name v, differentiated by the index, number referring to position: 0, for apple, 1 for banana and 2 for orange. At this point I mentioned earlier that the count does not start at 1 but at 0.

In addition, a string by itself can be considered a character vector and the indexing works in exactly the same way.

But what are these indices?

Let’s imagine that in our operating system, when we define an array, its values are stored in sequence in memory:

|       ...       |  <- Memória continua para cima
+-----------------+
| maçã            |
+-----------------+
| banana          |
+-----------------+
| laranja         |
+-----------------+
|       ...       |  <- Memória continua para baixo

When we create the instance of our vector, we store the memory address of the beginning of the vector in the variable that defines it. If we assume that our vector starts to be stored at address 120, we would have the following structure:

|       ...       | 119
+-----------------+
| maçã            | 120
+-----------------+
| banana          | 121
+-----------------+
| laranja         | 122
+-----------------+
|       ...       | 123

As we make:

v = ["maçã", "banana", "laranja"]

The memory address of the variable v would be 120, because that’s where the vector starts. To access a vector value, the system adds the index value to the initial address. For example, to access the value maçã, which is at index 0, the system would access the memory at the position 120+0 = 120. For the value banana, which is index 1, the system would access 120+1 = 121. Finally, for the value laranja, index 2, the system would access 120+2 = 122.

This is how the indexing of vectors works, explaining why the numbering does not start at 1, but rather at 0, because to access the first position, the system, sooner or later, would have to subtract 1 at the address to get the start of the vector and it would be an extra operation for the system to execute.

To the string, the logic is the same:

s = "Stack Overflow"

In memory, it would be:

+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| S | t | a | c | k |   | O | v | e | r | f | l | o | w |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
  a  a+1 a+2 a+3 a+4 a+5 a+6 a+7 a+8 a+9 ...

If the string is stored in the memory address a, the first character will be in the address a (s[0]), the second at the address a+1 (s[1]), the third in a+2 (s[2]), thus successively.

  • I can barely see your movements.

  • +1 for link :D

  • So, I had difficulty understanding when you say "the index in the vectors starts at zero", with 'vectors' you refer to strings ?. And when you refer to 'Dice' I also had a hard time understanding. Could I please explain this.

  • I added the "Terminology" part to the answer trying to explain it a little better. See if it’s clearer.

  • It’s become much clearer now with the explanation of the terminology... thank you

Browser other questions tagged

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