Suner Evren
Suner Evren

Reputation: 63

Check if values are equal in Python IF statement

I have 2 values , one of them is coming from a file and one of them is coming from database. Both values are numeric . My code is Python, 2.7 version.

If I do use below code , it is working like charm

if int(val1) == int(val2) :
  print "what ever action it will do"

My question is if there is a different way to make that check? Is this an acceptable way to do that or not?

Upvotes: 0

Views: 4144

Answers (3)

Michael Kazarian
Michael Kazarian

Reputation: 4462

Is this an acceptable way to do that or not?

It depend from previous code. On first glance it work.

is if there is a different way to make that check?

You can check it trick way:

In [1]: import sys
In [2]: val1 = "12.50"; val2 = 12.5
In [3]: (float(val1) == float(val2) and sys.stdout.write("what ever action it will do"))
what ever action it will do

Upvotes: 0

Anand
Anand

Reputation: 853

I both are numeric, then type casting is not required. You can use like the below code:

 if(val1==val2):
   print "what ever action it will do"

Upvotes: 0

OBu
OBu

Reputation: 5167

if your database (or file reading module) gives you ints, you can omit one of the int-conversions, but otherwise it's fine. You usually would skip the blank in front of the :.

If there is any possibility that one of your values might not be convertable to an int (e.g. any other string), you should use a try-except-block to handle that error.

Upvotes: 3

Related Questions