"except" does not recognize value as wrong

Asked

Viewed 52 times

1

mensagem = input('''Clique "C" ''')
print (mensagem)

#condições relativas ao input mensagem

try : 
    mensagem == "C"
except Exception :
    print ("a casa caiu")
else :
    print ("a casa não caiu")

The program is always running "the house did not fall", wanted to know why and how to fix

  • This code will not really generate an exception, you wanted an exception to be generated if the value was different from "C"?

1 answer

3


You don’t want to use an exception there, you just want to check a state and make a decision, and to make decisions and divert the flow there is the command if.

As the name says, an exception should only be used in exceptional cases. Almost always when someone uses an exception is doing something wrong in the code. Python even encourages a little the use of exception in things not very exceptional, but at least it is a matter of interpretation of what is exceptional or not, your case is clearly not something exceptional, it is only a decision. Unless there’s something not put in the question.

Nor does it make sense to have a condition alone like this, or would have to store the value in a variable for future use or use exactly in a condition (a if, while or something like that).

With if do as you wish:

mensagem = input('''Clique "C" ''')
print (mensagem)
if mensagem == "C":
    print("a casa caiu")
else:
    print("a casa não caiu")

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

Browser other questions tagged

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