I need help understanding this code

Asked

Viewed 80 times

0

I’m starting in python watching video lessons on youtube,the following exercise has been passed:

if 10 <= saque <= 600:
    notas_cem = saque // 100
    saque = saque % 100

I DIDN’T UNDERSTAND THESE PARTS, because the variable "notas_cem" is attributed to the plunder divided by 100? and because the plunder is equal to the rest of this division?

The program should not worry about the amount of notes in the machine.

Example 1: To withdraw the amount of 256 reais, the program provides two 100 banknotes, a 50 banknote, a 5 banknote and a 1 banknote;

Example 2: To withdraw the amount of 399 reais, the program provides three 100 banknotes, a 50 banknote, four 10 banknote, a 5 banknote and four banknotes of 1.

saque = int(input("Digite o valor do saque: "))

if 10 <= saque <= 600:
    notas_cem = saque // 100
    saque = saque % 100

    notas_cinquenta = saque // 50
    saque = saque % 50

    notas_dez = saque // 10
    saque = saque % 10 

    notas_cinco = saque // 5
    saque = saque % 5

    notas_um = saque // 1

    if notas_cem > 0:
        print(notas_cem, "notas de R$ 100")
    if notas_cinquenta > 0:
        print(notas_cinquenta, "notas de R$ 50")
    if notas_dez > 0:
        print(notas_dez, "notas de R$ 10")
    if notas_cinco > 0:
        print(notas_cinco, "notas de R$ 5")
    if notas_um > 0:
        print(notas_um, "notas de R$ 1")
              
else:
    print("Nao é possivel fazer o saque")

1 answer

1

because the variable "notas_cem" is attributed to the serve divided by 100? and because the serve is equal to the rest of this division?

Well, let’s assume that the value of the withdrawal is 256 reais. How do you know how many 100s will be needed? Dividing by 100.

And in the case was used the entire division operator (//), so the result is already rounded. In this case, 256 divided by 100 gives 2 (so I need 2 notes of 100).

But 2 notes of 100 gives a total of 200, only the value of the withdrawal is 256. That is, I still need to know the quantity of the other notes. Then I take the value of the serve (in our example, 256) and calculate the rest of the split by 100. That comes to 56, which is what’s left if we cash the 100.

Then the algorithm continues, using the same reasoning with the other notes: note that it does the same with 50, 10, 5 and 1 - although with 1 notes is unnecessary, because dividing by 1 does not change anything (unless the value also had the cents, but it does not seem to be the case).

At the end we have the amount of each note.

And the algorithm also works if the value is less than 100. For example, if it’s a 90 draw, the split by 100 is zero (because you don’t need a 100 note), and the rest of the split by 100 is 90 (and then you proceed with the 50 notes, etc).

Taking advantage, here has other different options for this same algorithm.

Browser other questions tagged

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