How to compare if a number entered by the user is equal to a certain value

Asked

Viewed 55 times

-1

I have this code:

idade = input('Qual a sua idade? ')
if(idade == 33):
    print('Ok, não parece que você está mentindo.')
else:
    print('Você tem certeza que não pulou alguns dígitos?')

Regardless of the age I place, the code executes the else - even when I enter the correct answer - which in this case would be 33.

  • The problem is that input returns a string, then needs to convert to number, as already explained in the suggested duplicate in the blue box above. I removed the other part of the question (about returning the line in the terminal) because the idea of the site is to have a specific problem per question, but in any case this may help: https://answall.com/q/207887/112052 | https://answall.com/q/72678/112052

1 answer

1

When you do:

idade = input('Qual a sua idade? ')

You are assigning a string to the variable age and therefore your code will never run the if. Yeah, the if shall be executed only if the age be the type int. This way, the code will always execute the else.

By default, the function input() always returns a string. So to fix this problem, just convert the captured value to integer - int. As listed in the first line of the code below.

idade = int(input('Qual a sua idade? '))
if idade == 33:
    print('Ok, não parece que você está mentindo.')
else:
    print('Você tem certeza que não pulou alguns dígitos?')

Note that the first line of code captures the entered value and converts to integer and then performs the checks.

Another thing, the parentheses you had placed on the line of if are unnecessary.


Now for you to re-run the code, you can wrap it in a block while True. This way the code would be:

while True:
    idade = int(input('Qual a sua idade? '))
    if idade == 33:
        print('Ok, não parece que você está mentindo.')
    else:
        print('Você tem certeza que não pulou alguns dígitos?')
    
    while (resp := input('Desejas continuar? [S/N] ').upper()) not in {'S', 'N'}:
        print('Valor INVÁLIDO!')
    if resp == 'N':
        break

Please note that the code will be re-examined every time your reply is s or S.

Note that the lines of code...

while (resp := input('Desejas continuar? [S/N] ').upper()) not in {'S', 'N'}:
        print('Valor INVÁLIDO!')

...form a resource made available by Python 3.8 or higher which is called Assignment Expression.

This lines of code checks whether the expression assigned to the variable resp is S or N. If the value of Resp is not even S and neither N, we will receive the message Valor INVÁLIDO and we will again be asked for a response. If S, the code shall be re-examined. If N, the code will be finalised.

  • Thanks for the answers. I will put into practice your tips Solkarped, thanks!

Browser other questions tagged

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