Sunday, August 23, 2009

Python, comparing variable values

I have started some time ago with the Python cover to cover serie on this weblog however for some reason, namely, working on other projects I have not posted a Python cover to cover for some time now. So time to pick it up again and to all who like to follow the Python cover to cover... I will keep working on it more as I have finished some of the projects that where holding me back.

The past posts on Python I have been explaining about variable types. Now we will look on what we can do with variables on the comparing part. First we define some variables to play with:

var0 = "a"
var1 = "b"
var2 = 100
var3 = 50
var4 = float(1.1)
var5 = float(50.0)

So now we have some variables to play with. First we will use the string variables var0 and var1 . Lets compare if they are the same, to do this you use == so in this example we will be using the expression var0 == var1 which will return a boolean value which in this case this will be false. so as a small coding example you can check the code below:

>>> var0 = "a"
>>> var1 = "b"
>>> var0 == var1
False
>>>

we can also some other types of compare. For example the "not like" compare can be done by a using != as can be seen below:

>>> var0 != var1
True

And now something that you might expect on float and int values only maybe a greater or smaller than compare on a string which takes the alphabet into account:

>>> var0 > var1
False
>>> var0 <>
True
>>>

When you are comparing String values in python with greater than or smaller than functions you have to take into account that you might run into troubles because of upper and lower case characters. So it is a good thing to make sure that when you compare like this you make all characters upper or lower case before you start comparing. for this you can use the upper() and lower() functions. So if you want to turn a string into uppercase in Python, or lowercase you can use the following:

>>> "THIS IS A TEST".lower()
'this is a test'
>>> "ThIS Is A TeSt".lower()
'this is a test'
>>>


Basically all can also be done on numbers and not only on strings, Al Lukaszewski has also written some about it for about.com which you might want to read.

No comments: