How to increment the value of a variable according to the user’s response?

Asked

Viewed 1,545 times

1

I would like to ask the user a question to answer "yes" or "no". If the answer is "yes" add 10 weights to the variable peso and if "no", do not add.

I have a question about how to convert the string for whole.

fotossenbilidade = input('Você tem sensibilidade com relação a luz?')

The user would have to answer "yes" or "no", how do I add these options? And to add the weights I would have to use a if?

  • Convert to whole just do valor = int(string_a_converter). What do you mean add weights?

2 answers

4

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.

  1. 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.

  2. 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.

  3. 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).

  4. 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.

  • Got it, thank you so much for the help and the explanation, that’s exactly what I was wondering.

  • @Jsouza Favor accept this answer

  • For this type of cases it is not better to use case because we know all the possible cases?

  • @Pbras Python does not have switch/cas, if that’s what you said. If not, could you give an example?

  • @Andersoncarloswoss you’re right in Python you don’t have to make an array to be able to make a case and it’s not worth complicating here. I haven’t used python in a few years excuse the confusion.

  • 1

    @Pbras added a version using dictionary.

  • @Andersoncarloswoss Yes it seems to work like this, and if you want more options just add it to the dictionary. But as he said it was new programming did not want to confuse him too much. But if he realizes gets one more way to do.

Show 2 more comments

0

Just make a conditional to check what user input was!

fotossenbilidade = input('Você tem sensibilidade com relação a luz?')
Peso = 0 # inicializa variavel Peso

# loop para garantir que o input do usuário está de acordo com o esperado
while (fotossenbilidade != 'Sim' and fotossenbilidade != 'sim' and fotossenbilidade != 'Nao' and fotossenbilidade != 'nao:'):

    fotossenbilidade = input('Você tem sensibilidade com relação a luz?')

if (fotossenbilidade == 'Sim' or fotossenbilidade == 'sim'):
    Peso = 10
  • But if I answer No it will generate an infinite loop and keep asking the same question ?

  • No, on the contrary. It loops until it receives EITHER a yes OR a no. Then it compares and, if it was a yes, it assigns a weight to the variable.

Browser other questions tagged

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