When you need to request something from the user and validate the information, it is natural that we do not know how many times the user will need to enter a valid information. There may be a user who will respond correctly in the first, but there may be one that will take dozens of attempts. This tells us that the code should be based on an infinite loop and stop it only when the user responds correctly "yes" or "no". The code I suggest is:
peso = 0
while True:
resposta = input('Você tem sensibilidade à luz? [sim|não] ').lower()
if resposta not in {'sim', 'não'}:
continue
if resposta == 'sim':
peso += 10
break
print('Peso:', peso)
See working at Repl.it
Explaining
- We set the variable
peso
to zero;
- We start a loop of infinite repetition;
- We asked the user for the answer, converting it to the lower case for easy comparison;
- We checked whether the answer was "yes" or "no". If not, continue the loop by prompting the user again;
- If yes, check if the answer is "yes". If yes, we increase% with% by 10;
- We have closed the loop of repetition;
- We display the final value of
peso
;
And why this solution would be better?
Enjoying that you already have an answer, we can compare them.
Using the infinite loop we were able to prompt the user only once in the code; using peso
repeatedly for the same function is unnecessarily repeating code.
When converting to lower case, we make comparisons easier, since we only need to verify if it is equal to "yes" or "no", even if the user types any variation: "YES", "Yes", "sIm" "No", "NO", etc.
Using the input
operator to check the answer eliminates the need for multiple logical operators. Defining the values between keys we use a set, which practically does not interfere with the code performance, because you will have O (1) .
It is interesting to use the in
operator to increment the value of +=
instead of setting it to 10, so if the variable has an initial value other than zero.
li>
Another way would be to create a dictionary relating the user's response to the value that should be incremented by peso
:
incrementos = {
'sim': 10,
'não': 0
}
And do:
peso = 0
while True:
resposta = input('Você tem sensibilidade à luz? [sim|não] ').lower()
incremento = incrementos.get(resposta, None)
if incremento is None:
continue
peso += incremento
break
print('Peso:', peso)
See working at Repl.it
If the answer does not exist in the dictionary it will return peso
and continue the loop until the user enters a valid value.