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 the user who will respond correctly at 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 correctly answers "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 on Repl.it
Explaining
- We define the variable
peso
as zero;
- We initiate an infinite loop loop;
- We ask the user for the answer, converting to low box for easy comparison;
- We check whether the answer was "yes" or "no". If not, continue the loop by asking the user again;
- If yes, we check if the answer is "yes". If yes, we increase
peso
in 10;
- We close the loop of repetition;
- Display the final value of
peso
;
And why this solution would be better?
Since you already have an answer, we can compare them.
Using the infinite loop we can ask the user only once in the code; use several times the input
for the same function is to repeat unnecessarily code.
When converting to low box we facilitate comparisons, as it is enough to check if it is equal to "yes" or "no", even if the user type any variation: "YES", "Yes", "Sim", "No", "NO", etc.
Use the operator in
to verify the answer eliminates the need for multiple logical operators. Defining the values between keys we use a set, which hardly interferes with the performance of the code, as you will have access to O(1).
It is interesting to use the operator +=
to increase the value of peso
instead of setting it to 10, because if the variable has a non-zero initial value.
Another way would be to create a dictionary relating the user’s response to the value that should be incremented in peso
:
incrementos = {
'sim': 10,
'não': 0
}
And make:
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 on Repl.it
If the answer does not exist in the dictionary it will be returned None
and continued the loop until the user enters a valid value.
Convert to whole just do
valor = int(string_a_converter)
. What do you mean add weights?– Isac