Doubt in the logic of the script

Asked

Viewed 43 times

1

Guys, I was wondering why the number 2 is not the first to be printed in this script, I’m not getting the logic.

altura = 5
linha = 1

while linha <= altura:
    print ('1', end = '')
    coluna = 2

    while coluna < altura:

        if linha == 1 or linha == altura:
            print ('2')

        else:
            print(end = '')
        coluna = coluna + 1

    print ('3')
    linha = linha + 1
  • 2

    Knows the table test?

  • no friend, study by account

  • Read on and try to apply it. It will be easier to understand what the code does;

2 answers

2


Leandro, to understand this script is good to understand how the while loop works.

The first while will only run if your condition is met,:

while linha <= altura: #linha(1) é de fato menor que altura(5) 
print ('1', end = '')
coluna = 2

When there is a loop inside another, the subsequent loop is also executed and only after its end the external loop returns to its normal execution, so:

    while coluna < altura:

    if linha == 1 or linha == altura:
        print ('2')

    else:
        print(end = '')
    coluna = coluna + 1

Your second while has to run until your condition is satisfied to subsequently fall back into the outer loop.

Anderson’s tip is valid, table tests can help you debug these simpler code errors, but a good understanding of programming logic is also required, keep studying.

1

In your code you have two while. The while from the outside is executed before and its contents are executed as well. The code does not start with while internal, I believe this has confused you.

Therefore, doing a simulation of the first execution and the values:

altura = 5                                   # altura = 5
linha = 1                                    # linha = 1

while linha <= altura:                       # 1 <= 5
    print ('1', end = '')                    # imprime 1, aqui já explica o motivo
    coluna = 2                               # coluna = 2

    while coluna < altura:                   # 2 < 5

        if linha == 1 or linha == altura:    # 1 == 1 or 1 == 5
            print ('2')                      # imprime 2, formando 12, o primeiro valor

Browser other questions tagged

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