I want to put 2 exceptions for my program validate data

Asked

Viewed 82 times

0

a =  ('''
Escolha a conversão que você deseja realizar:
1) Celcius-Fahrenheit
2) Fareheint-Celcius
3) Celcius-Kelvin
4) Kelvin-Celcius
5) Fahrenheit-Kelvin
6) Kelvin-Fahrenheit
''')

try :
   a = int(input(a)) and (a) < 7 and (a) > 0

except ValueError:
    print ("Escolha uma opção válida")

I’m trying to make a program that converts one temperature from one scale to another.

But every time I try to run the two main exceptions of the program (do not run letter as an option and have a value of 1 to 6 for the user to choose). Is giving this error in VSC :

Typeerror: '<' not supported between instances of 'str' and 'int'*.

I would like to know why this and how to make the program work with these two exceptions

  • You cannot compare Stings with integers (a) < 7 and (a) > 0

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

1 answer

4

I think this is what you want to do:

try:
   a = int(input(a))
   if a > 0 and a < 7:
       print ("o valor deve ser entre 1 e 6")
except ValueError:
    print ("Escolha uma opção válida")

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

What you want to do is different from validating data entry. Actually I think it’s a mistake to validate data entry to throw an exception when the data is invalid, but that’s how Python decided to be and that’s how it should do. Already validate the track the easiest is to make one if even.

You can do it differently. You can do the if throw an exception and fall into the except, but I wouldn’t do it because the reason is another, is slower, and the most appropriate message to steer is another.

Another way is to avoid the exception, but then you would have to write a code that validates the input of the data and return a boolean (what I think Python should have done for this case), but it is a lot of work, it is easy to do wrong and not worth the effort.

The reuse of the variable for different things in these cases does not cause error, but should not be done. You don’t really need a variable in the first case, but I understand why you did it, but call it mensagem. And a could have a name a little better, even if it is valor, already gives a better semantics, getting used to writing more readable code.

Browser other questions tagged

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