0

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?

5
  • It is completely acceptable. Commented Jan 16, 2014 at 10:32
  • Its a pretty good way for doing it, basic one. Just check if this suits for your problem, if it works its ok. Commented Jan 16, 2014 at 10:32
  • If you're wanting to check their numeric equality then you got it right there! Commented Jan 16, 2014 at 10:33
  • Only purpose is to check if they are equal numbers or not. Nothing else Commented Jan 16, 2014 at 10:34
  • 1
    If you are going to use them as ints, then I would say convert them as they come out of file/db Commented Jan 16, 2014 at 10:34

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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"

1 Comment

ok what if this files are coming from db from varchar(x) defined cell. yes they are numeric but how python will react ? will it count values as string or integer ?
0

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

3 Comments

Linuxoid will write it that way. Works but not very Pythonic
One should be careful when jesting around noobs. They may take you seriously
@volcano I have warned about it in answer. Furthemore it more Lisp-style then Linux-style.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.