Are you abusing the elif
. It is not because it has several conditions that everything should be grouped together. It has to do this according to the need.
The validation of each note should be independent, it makes no sense to put a elif
there, except to complicate the code, it could in a different way but it complicates the code a lot and it would be less readable. The most correct when an invalid data is entered is to close. If it were in a function it would be enough to use a return
, if it were in a loop, could use a continue
or even a break
in some situations. As in script pure must come out with exit()
.
The average should only be calculated when it has valid data and continued execution.
N]ao it is necessary to check if the average is up to 10 because if the data are valid it has been calculated to the correct limit.
And finally you don’t need to check anything on the disapproval because it’s the opposite of approval, just one else
simple.
import sys
n1 = int(input('digite nota 1: '))
n2 = int(input('digite nota 2: '))
if n1 > 10:
print('{} não é uma nota válida!'.format(n1))
sys.exit(0)
if n2 > 10:
print('{} não é uma nota válida!'.format(n2))
sys.exit(0)
media = (n1 + n2) / 2
if media >= 7:
print('Você foi aprovado com média {}'.format(media))
else:
print('Você foi reprovado com média {}'.format(media))
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Can you do it the way you were doing without forcing yourself out? Yes, but logic would be too confusing for an experienced person to imagine for a starting person. And I would risk learning in a confusing way for the rest of my life. Otherwise it would be less efficient, although it is not something relevant to this case could be one day and already accustomed to do more correct.
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).
– Maniero