why does the loop while True access the if and the else in sequence to each complete loop in that code?

1
#! /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 do not understand how the loop accesses the first if and the else in the sequence within the while True. Should not the else be accessed only when the first if of the code is false? how does this code work line by line ?, could someone explain?, remembering that I'm a beginner in programming.

    
asked by anonymous 28.03.2017 / 17:35

1 answer

1

Do not enter both (if and else) on the same cycle loop.

The "problem" is that since it is while True... it will do several laps, entering if (if the condition is) and decreasing 50 (initial value of atual ) to the value of apagar , until at the moment that apagar is less than atual , then it will enter the else. You can test this by doing a print(valor, apagar) within the loop, and setting the delete value to 200 for example.

If you want to make a break the first time you enter the if, you should make it explicit.

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

28.03.2017 / 17:47