pq the while True loop accesses if and Else in sequence to every complete loop in that code?

Asked

Viewed 5,400 times

2

#! /usr/bin/python3

valor = int(input("Digite o valor a pagar: "))

cedulas = 0
atual = 50
apagar = valor

while True:
    if atual <= apagar:
        apagar = apagar - atual
        cedulas += 1
    else:
        print("%d cedula(s) de R$%d" %(cedulas, atual))
        if apagar == 0:
            break
        elif atual == 50:
            atual = 20
        elif atual == 20:
            atual = 10
        elif atual == 10:
            atual = 5
        elif atual == 5:
            atual = 1
        cedulas = 0

I don’t understand how the loop accesses the first if and Else in the sequence within while True. Else should not be accessed only when the first if of the code is false? how does this code work line by line? , could someone explain to me? , remembering that I am a beginner in programming.

1 answer

1


It does not enter the two (if and Else) in the same round of the cycle.

The "problem" is that since while True... it will do several laps, entering if (if the condition is verified) and descending 50 (initial value of atual) to the value of apagar, until such time as apagar is less than atual, you can test this by making a print(valor, apagar) within the cycle, and putting the value delete to 200 for example.

If you want to break the first time you enter if, you should explain.

Visual explanation:

valor = int(input("Digite o valor a pagar: "))

cedulas = 0
atual = 50
apagar = valor

while True:
    print(valor, atual, apagar) # acrescentei isto para perceberes o que se passa
    if atual <= apagar:
        apagar = apagar - atual
        cedulas += 1
    else:
        print("%d cedula(s) de R$%d" %(cedulas, atual))
        if apagar == 0:
            break
        elif atual == 50:
            atual = 20
        elif atual == 20:
            atual = 10
        elif atual == 10:
            atual = 5
        elif atual == 5:
            atual = 1
        cedulas = 0

The output of the program with apagar being 200:

200 50 200
200 50 150
200 50 100
200 50 50
200 50 0 <-- only here after this print, on the same turn, will you enter Else
4 cedula(s) of R$50

Here you can see that in the first 4 laps we enter the if, because apagar in these 4 laps was even greater or equal than atual.

Remembering that current also changes from the moment we meet in the else, so in this case, sooner or later we will stop in the if apagar == 0: which is what 'makes' break to the cycle

If you want to exit the cycle when entering the if:

...
if atual <= apagar:
    apagar = apagar - atual
    cedulas += 1
    break
...

Browser other questions tagged

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