I’m not getting loops while nested

Asked

Viewed 385 times

3

I’m having trouble understanding this code, because I don’t understand how it behaves in loops while, follow the instructions after the code.

Note 1: I am learning programming logic yet, so I am "bumping heads" with simple codes.

Note 2: The code is correct, I just need to understand the flow of the code.

Note 3: #with the number in the code represent the questions.

#!/usr/bin/python3

primeira = []
segunda = []
terceira = []

while True:
    e = int(input("Digite um valor para a primeira lista (0 para terminar):"))
    if e==0:
        break
    primeira.append(e)
while True:
    e = int(input("Digite um valor para a segunda lista (0 para terminar):"))
    if e==0:
        break
    segunda.append(e)

duas_listas = primeira[:]
duas_listas.extend(segunda)

x=0
while x < len(duas_listas): #1
    y = 0
    while y < len(terceira): #2
        if duas_listas[x] == terceira[y]:
            break;
        y=y+1 #3
    if y == len(terceira): #4
        terceira.append(duas_listas[x])
    x=x+1
x=0
while x < len(terceira): #5
    print("%d: %d" % (x, terceira[x]))
    x=x+1

1 - In this first check I understood why the list contains data, so for me it makes sense x be less than the length of the list.

2 - Here, how y which is 0 (zero) may be less than the length of the "third" list and the "third" list is empty? , that is, zero is less than zero?

3 - Why the code did not increment the y=y+1 whereas y=y+1 is the next line after the break.

4 - If the method len() count from number 1 when containing data within a list, when a list does not contain data its value and zero?

5 - Here I understood, the loop while passes through each item in the "third" list and prints the value of each item.

1 answer

2


1 - In this first check I understood why the list contains data, so for me it makes sense x be less than the length of the list.

okay

2 - Here, how y which is 0 (zero) may be less than the length of the "third" list and the "third" list is empty? , that is, zero is less than zero?

In the first pass this is true in the second may be no more since just below may have a append() on the list:

if y == len(terceira): #4
    terceira.append(duas_listas[x])

I put in the Github for future reference.

3 - Why the code did not increment the y=y+1 whereas y=y+1 is the next line after the break.

It is increasing, as long as it enters this loop

4 - If the method len() count from number 1 when containing data within a list, when a list does not contain data its value and zero?

That.

5 - Here I understood, the loop while passes through each item in the "third" list and prints the value of each item.

okay.

Make a table test in the algorithm and will understand better. Can do with a Debugger and see step by step what is happening.

Browser other questions tagged

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