It does not store the largest magically, this is an algorithm, so there are several steps being executed with a collection of data being input.
In such a step he will analyze whether what was typed is greater than x
, then if it is, at that time what was typed is the highest value, and within the if
he then says that x
is that value that was entered. The first time any number that was entered will be greater than x
because this variable is 0 and only enters the loop if what was typed is greater than 0.
Then he will perform once again the same thing, that’s the function of the while
. And again you will have to check if the new entered value is greater than x
, this time is worth the value previously entered. Once again only enter the if
if a higher value was entered, and then the x
would have a new value. If it is not a higher value it ignores this data (actually if it is equal has something to do there elif
, but that’s not the focus of the question).
And it does this until 0 or negative value is entered. Then the value of x
will be the last highest entered value, no matter if it was typed last, because if you enter smaller values after typing a larger one will never enter the if
and will not change the value of x
.
The secret is the if
which determines when the value of x
will be changed or not. And next restarts the amount of number repeated without interruption had for the last time. It does not keep all repeated or the other times that occur even the largest and how many were repeated has no relation at all, so I do not know if it was to happen that or is error of the algorithm.
I advise learning and making one table test and/or apply the execution using a debug to see the data being changed step by step.
I think x
is a bad name for what this variable does and impairs understanding. Although the exercise speaks in x
, would be a better name to understand the algorithm.
I hate having to read data in two different places and I find it more readable to do each thing in the right order, it doesn’t seem to be such a code Clever, I’m not saying it’s necessarily better, but I find it easier to understand like this:
maior = 0
quantos = 0
while True:
valor = int(input())
if valor < 1:
break
if valor > maior:
maior = valor
quantos = 1
elif valor == maior:
quantos += 1
print('X =', maior, 'quantos = ', quantos)
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Note that I preferred to put an end condition of the loop inside it, right after typing a number it decides whether it is to continue or break (break
) the tie.
preferred not to validate typed data, but typing something other than a number will break the application.